1 // Copyright 2016 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "mojo/public/cpp/bindings/string_traits_wtf.h" 6 7 #include <string.h> 8 9 #include "base/logging.h" 10 #include "mojo/public/cpp/bindings/lib/array_internal.h" 11 #include "third_party/WebKit/Source/wtf/text/StringUTF8Adaptor.h" 12 13 namespace mojo { 14 namespace { 15 16 struct UTF8AdaptorInfo { 17 explicit UTF8AdaptorInfo(const WTF::String& input) : utf8_adaptor(input) { 18 #if DCHECK_IS_ON() 19 original_size_in_bytes = static_cast<size_t>(input.sizeInBytes()); 20 #endif 21 } 22 23 ~UTF8AdaptorInfo() {} 24 25 WTF::StringUTF8Adaptor utf8_adaptor; 26 27 #if DCHECK_IS_ON() 28 // For sanity check only. 29 size_t original_size_in_bytes; 30 #endif 31 }; 32 33 UTF8AdaptorInfo* ToAdaptor(const WTF::String& input, void* context) { 34 UTF8AdaptorInfo* adaptor = static_cast<UTF8AdaptorInfo*>(context); 35 36 #if DCHECK_IS_ON() 37 DCHECK_EQ(adaptor->original_size_in_bytes, 38 static_cast<size_t>(input.sizeInBytes())); 39 #endif 40 return adaptor; 41 } 42 43 } // namespace 44 45 // static 46 void StringTraits<WTF::String>::SetToNull(WTF::String* output) { 47 if (output->isNull()) 48 return; 49 50 WTF::String result; 51 output->swap(result); 52 } 53 54 // static 55 void* StringTraits<WTF::String>::SetUpContext(const WTF::String& input) { 56 return new UTF8AdaptorInfo(input); 57 } 58 59 // static 60 void StringTraits<WTF::String>::TearDownContext(const WTF::String& input, 61 void* context) { 62 delete ToAdaptor(input, context); 63 } 64 65 // static 66 size_t StringTraits<WTF::String>::GetSize(const WTF::String& input, 67 void* context) { 68 return ToAdaptor(input, context)->utf8_adaptor.length(); 69 } 70 71 // static 72 const char* StringTraits<WTF::String>::GetData(const WTF::String& input, 73 void* context) { 74 return ToAdaptor(input, context)->utf8_adaptor.data(); 75 } 76 77 // static 78 bool StringTraits<WTF::String>::Read(StringDataView input, 79 WTF::String* output) { 80 WTF::String result = WTF::String::fromUTF8(input.storage(), input.size()); 81 output->swap(result); 82 return true; 83 } 84 85 } // namespace mojo 86