1 // Copyright 2021 The Chromium Embedded Framework Authors. Portions copyright
2 // 2011 The Chromium Authors. All rights reserved. Use of this source code is
3 // governed by a BSD-style license that can be found in the LICENSE file.
4
5 #include "libcef/common/string_util.h"
6
7 #include "base/memory/read_only_shared_memory_region.h"
8 #include "base/memory/ref_counted_memory.h"
9 #include "third_party/blink/public/platform/web_string.h"
10
11 namespace string_util {
12
GetCefString(const blink::WebString & source,CefString & cef_string)13 void GetCefString(const blink::WebString& source, CefString& cef_string) {
14 #if defined(CEF_STRING_TYPE_UTF8)
15 cef_string.FromString(source.Utf8());
16 #else
17 cef_string.FromString16(source.Utf16());
18 #endif
19 }
20
GetCefString(scoped_refptr<base::RefCountedMemory> source,CefString & cef_string)21 void GetCefString(scoped_refptr<base::RefCountedMemory> source,
22 CefString& cef_string) {
23 if (source && source->size() > 0U) {
24 #if defined(CEF_STRING_TYPE_UTF8) || defined(CEF_STRING_TYPE_UTF16)
25 // Reference existing UTF8 or UTF16 data.
26 cef_string.FromString(source->front_as<CefString::char_type>(),
27 source->size() / sizeof(CefString::char_type),
28 /*copy=*/false);
29 #else
30 // Must convert from UTF16.
31 cef_string.FromString16(
32 source->front_as<std::u16string::value_type>(),
33 source->size() / sizeof(std::u16string::value_type));
34 #endif
35 } else {
36 cef_string.clear();
37 }
38 }
39
CreateSharedMemoryRegion(const blink::WebString & source)40 base::ReadOnlySharedMemoryRegion CreateSharedMemoryRegion(
41 const blink::WebString& source) {
42 base::ReadOnlySharedMemoryRegion region;
43
44 if (!source.IsEmpty()) {
45 #if defined(CEF_STRING_TYPE_UTF8)
46 const std::string& string = source.Utf8();
47 const size_t byte_size = string.length();
48 #else
49 const std::u16string& string = source.Utf16();
50 const size_t byte_size =
51 string.length() * sizeof(std::u16string::value_type);
52 #endif
53 auto mapped_region = base::ReadOnlySharedMemoryRegion::Create(byte_size);
54 if (mapped_region.IsValid()) {
55 memcpy(mapped_region.mapping.memory(), string.data(), byte_size);
56 region = std::move(mapped_region.region);
57 }
58 }
59
60 return region;
61 }
62
ExecuteWithScopedCefString(base::ReadOnlySharedMemoryRegion region,ScopedCefStringCallback callback)63 void ExecuteWithScopedCefString(base::ReadOnlySharedMemoryRegion region,
64 ScopedCefStringCallback callback) {
65 auto shared_buf =
66 base::RefCountedSharedMemoryMapping::CreateFromWholeRegion(region);
67 CefString str;
68 GetCefString(shared_buf, str);
69 std::move(callback).Run(str);
70 }
71
72 } // namespace string_util