Home | History | Annotate | Download | only in lib
      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 = input.charactersSizeInBytes();
     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, input.charactersSizeInBytes());
     38 #endif
     39   return adaptor;
     40 }
     41 
     42 }  // namespace
     43 
     44 // static
     45 void StringTraits<WTF::String>::SetToNull(WTF::String* output) {
     46   if (output->isNull())
     47     return;
     48 
     49   WTF::String result;
     50   output->swap(result);
     51 }
     52 
     53 // static
     54 void* StringTraits<WTF::String>::SetUpContext(const WTF::String& input) {
     55   return new UTF8AdaptorInfo(input);
     56 }
     57 
     58 // static
     59 void StringTraits<WTF::String>::TearDownContext(const WTF::String& input,
     60                                                 void* context) {
     61   delete ToAdaptor(input, context);
     62 }
     63 
     64 // static
     65 size_t StringTraits<WTF::String>::GetSize(const WTF::String& input,
     66                                           void* context) {
     67   return ToAdaptor(input, context)->utf8_adaptor.length();
     68 }
     69 
     70 // static
     71 const char* StringTraits<WTF::String>::GetData(const WTF::String& input,
     72                                                void* context) {
     73   return ToAdaptor(input, context)->utf8_adaptor.data();
     74 }
     75 
     76 // static
     77 bool StringTraits<WTF::String>::Read(StringDataView input,
     78                                      WTF::String* output) {
     79   WTF::String result = WTF::String::fromUTF8(input.storage(), input.size());
     80   output->swap(result);
     81   return true;
     82 }
     83 
     84 }  // namespace mojo
     85