1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "v8_native_string.h"
17
18 #include "utils/log.h"
19
V8NativeString(V8NativeEngine * engine,const char * value,size_t length)20 V8NativeString::V8NativeString(V8NativeEngine* engine, const char* value, size_t length)
21 : V8NativeString(
22 engine,
23 v8::String::NewFromUtf8(engine->GetIsolate(), value, v8::NewStringType::kNormal, length).ToLocalChecked())
24 {
25 }
V8NativeString(V8NativeEngine * engine,v8::Local<v8::Value> value)26 V8NativeString::V8NativeString(V8NativeEngine* engine, v8::Local<v8::Value> value) : V8NativeValue(engine, value) {}
27
~V8NativeString()28 V8NativeString::~V8NativeString() {}
29
GetInterface(int interfaceId)30 void* V8NativeString::GetInterface(int interfaceId)
31 {
32 return (NativeString::INTERFACE_ID == interfaceId) ? (NativeString*)this : nullptr;
33 }
34
GetCString(char * buffer,size_t size,size_t * length)35 void V8NativeString::GetCString(char* buffer, size_t size, size_t* length)
36 {
37 if (length == nullptr) {
38 HILOG_ERROR("length is nullptr");
39 return;
40 }
41
42 v8::Local<v8::String> val = value_;
43 if (buffer == nullptr) {
44 *length = val->Utf8Length(engine_->GetIsolate());
45 } else if (size != 0) {
46 int copied = val->WriteUtf8(engine_->GetIsolate(), buffer, size, nullptr,
47 v8::String::REPLACE_INVALID_UTF8 | v8::String::NO_NULL_TERMINATION);
48 buffer[copied] = '\0';
49 *length = copied;
50 } else {
51 *length = 0;
52 }
53 }
54
GetLength()55 size_t V8NativeString::GetLength()
56 {
57 v8::Local<v8::String> value = value_;
58 return value->Utf8Length(engine_->GetIsolate());
59 }
60
EncodeWriteUtf8(char * buffer,size_t bufferSize,int32_t * nchars)61 size_t V8NativeString::EncodeWriteUtf8(char* buffer, size_t bufferSize, int32_t* nchars)
62 {
63 if (nchars == nullptr) {
64 HILOG_ERROR("nchars is nullptr");
65 return 0;
66 }
67
68 v8::Local<v8::String> val = value_;
69 int32_t copied = 0;
70 if (buffer == nullptr) {
71 copied = val->Utf8Length(engine_->GetIsolate());
72 } else {
73 copied = val->WriteUtf8(engine_->GetIsolate(),
74 buffer,
75 static_cast<int32_t>(bufferSize),
76 nchars,
77 v8::String::REPLACE_INVALID_UTF8 | v8::String::NO_NULL_TERMINATION);
78 buffer[copied] = '\0';
79 }
80
81 return static_cast<size_t>(copied);
82 }
83