GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage/nodes/benchmark/out/../src/string_bytes.cc Lines: 252 307 82.1 %
Date: 2019-01-07 12:15:22 Branches: 139 204 68.1 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#include "string_bytes.h"
23
24
#include "base64.h"
25
#include "node_internals.h"
26
#include "node_errors.h"
27
#include "node_buffer.h"
28
29
#include <limits.h>
30
#include <string.h>  // memcpy
31
32
#include <algorithm>
33
#include <vector>
34
35
// When creating strings >= this length v8's gc spins up and consumes
36
// most of the execution time. For these cases it's more performant to
37
// use external string resources.
38
#define EXTERN_APEX 0xFBEE9
39
40
namespace node {
41
42
using v8::HandleScope;
43
using v8::Isolate;
44
using v8::Just;
45
using v8::Local;
46
using v8::Maybe;
47
using v8::MaybeLocal;
48
using v8::Nothing;
49
using v8::String;
50
using v8::Value;
51
52
namespace {
53
54
template <typename ResourceType, typename TypeName>
55
class ExternString: public ResourceType {
56
 public:
57
62
  ~ExternString() override {
58
31
    free(const_cast<TypeName*>(data_));
59
31
    isolate()->AdjustAmountOfExternalAllocatedMemory(-byte_length());
60

93
  }
61
62
91
  const TypeName* data() const override {
63
91
    return data_;
64
  }
65
66
198
  size_t length() const override {
67
198
    return length_;
68
  }
69
70
62
  int64_t byte_length() const {
71
62
    return length() * sizeof(*data());
72
  }
73
74
8026
  static MaybeLocal<Value> NewFromCopy(Isolate* isolate,
75
                                       const TypeName* data,
76
                                       size_t length,
77
                                       Local<Value>* error) {
78

8026
    if (length == 0)
79
2
      return String::Empty(isolate);
80
81

8024
    if (length < EXTERN_APEX)
82
8010
      return NewSimpleFromCopy(isolate, data, length, error);
83
84
14
    TypeName* new_data = node::UncheckedMalloc<TypeName>(length);
85

14
    if (new_data == nullptr) {
86
      *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
87
      return MaybeLocal<Value>();
88
    }
89
14
    memcpy(new_data, data, length * sizeof(*new_data));
90
91
    return ExternString<ResourceType, TypeName>::New(isolate,
92
                                                     new_data,
93
                                                     length,
94
14
                                                     error);
95
  }
96
97
  // uses "data" for external resource, and will be free'd on gc
98
3412
  static MaybeLocal<Value> New(Isolate* isolate,
99
                               TypeName* data,
100
                               size_t length,
101
                               Local<Value>* error) {
102

3412
    if (length == 0)
103
      return String::Empty(isolate);
104
105

3412
    if (length < EXTERN_APEX) {
106
3381
      MaybeLocal<Value> str = NewSimpleFromCopy(isolate, data, length, error);
107
3381
      free(data);
108
3381
      return str;
109
    }
110
111
    ExternString* h_str = new ExternString<ResourceType, TypeName>(isolate,
112
                                                                   data,
113
31
                                                                   length);
114
31
    MaybeLocal<Value> str = NewExternal(isolate, h_str);
115
31
    isolate->AdjustAmountOfExternalAllocatedMemory(h_str->byte_length());
116
117

31
    if (str.IsEmpty()) {
118

5
      delete h_str;
119
5
      *error = node::ERR_STRING_TOO_LONG(isolate);
120
5
      return MaybeLocal<Value>();
121
    }
122
123
26
    return str.ToLocalChecked();
124
  }
125
126
31
  inline Isolate* isolate() const { return isolate_; }
127
128
 private:
129
31
  ExternString(Isolate* isolate, const TypeName* data, size_t length)
130
31
    : isolate_(isolate), data_(data), length_(length) { }
131
  static MaybeLocal<Value> NewExternal(Isolate* isolate,
132
                                       ExternString* h_str);
133
134
  // This method does not actually create ExternString instances.
135
  static MaybeLocal<Value> NewSimpleFromCopy(Isolate* isolate,
136
                                             const TypeName* data,
137
                                             size_t length,
138
                                             Local<Value>* error);
139
140
  Isolate* isolate_;
141
  const TypeName* data_;
142
  size_t length_;
143
};
144
145
146
typedef ExternString<String::ExternalOneByteStringResource,
147
                     char> ExternOneByteString;
148
typedef ExternString<String::ExternalStringResource,
149
                     uint16_t> ExternTwoByteString;
150
151
152
template <>
153
26
MaybeLocal<Value> ExternOneByteString::NewExternal(
154
    Isolate* isolate, ExternOneByteString* h_str) {
155
52
  return String::NewExternalOneByte(isolate, h_str).FromMaybe(Local<Value>());
156
}
157
158
159
template <>
160
5
MaybeLocal<Value> ExternTwoByteString::NewExternal(
161
    Isolate* isolate, ExternTwoByteString* h_str) {
162
10
  return String::NewExternalTwoByte(isolate, h_str).FromMaybe(Local<Value>());
163
}
164
165
template <>
166
8159
MaybeLocal<Value> ExternOneByteString::NewSimpleFromCopy(Isolate* isolate,
167
                                                         const char* data,
168
                                                         size_t length,
169
                                                         Local<Value>* error) {
170
  MaybeLocal<String> str =
171
      String::NewFromOneByte(isolate,
172
                             reinterpret_cast<const uint8_t*>(data),
173
                             v8::NewStringType::kNormal,
174
8159
                             length);
175
8159
  if (str.IsEmpty()) {
176
    *error = node::ERR_STRING_TOO_LONG(isolate);
177
    return MaybeLocal<Value>();
178
  }
179
8159
  return str.ToLocalChecked();
180
}
181
182
183
template <>
184
3232
MaybeLocal<Value> ExternTwoByteString::NewSimpleFromCopy(Isolate* isolate,
185
                                                         const uint16_t* data,
186
                                                         size_t length,
187
                                                         Local<Value>* error) {
188
  MaybeLocal<String> str =
189
      String::NewFromTwoByte(isolate,
190
                             data,
191
                             v8::NewStringType::kNormal,
192
3232
                             length);
193
3232
  if (str.IsEmpty()) {
194
    *error = node::ERR_STRING_TOO_LONG(isolate);
195
    return MaybeLocal<Value>();
196
  }
197
3232
  return str.ToLocalChecked();
198
}
199
200
}  // anonymous namespace
201
202
// supports regular and URL-safe base64
203
const int8_t unbase64_table[256] =
204
  { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1,
205
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
206
    -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63,
207
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
208
    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
209
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63,
210
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
211
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
212
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
213
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
214
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
215
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
216
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
217
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
218
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
219
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
220
  };
221
222
223
static const int8_t unhex_table[256] =
224
  { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
225
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
226
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
227
     0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
228
    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
229
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
230
    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
231
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
232
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
233
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
234
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
235
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
236
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
237
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
238
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
239
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
240
  };
241
242
45242566
static inline unsigned unhex(uint8_t x) {
243
45242566
  return unhex_table[x];
244
}
245
246
template <typename TypeName>
247
2348
static size_t hex_decode(char* buf,
248
                         size_t len,
249
                         const TypeName* src,
250
                         const size_t srcLen) {
251
  size_t i;
252


22623622
  for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) {
253
22621283
    unsigned a = unhex(src[i * 2 + 0]);
254
22621283
    unsigned b = unhex(src[i * 2 + 1]);
255


22621283
    if (!~a || !~b)
256
9
      return i;
257
22621274
    buf[i] = (a << 4) | b;
258
  }
259
260
2339
  return i;
261
}
262
263
511
size_t StringBytes::WriteUCS2(Isolate* isolate,
264
                              char* buf,
265
                              size_t buflen,
266
                              Local<String> str,
267
                              int flags,
268
                              size_t* chars_written) {
269
511
  uint16_t* const dst = reinterpret_cast<uint16_t*>(buf);
270
271
511
  size_t max_chars = buflen / sizeof(*dst);
272
511
  if (max_chars == 0) {
273
5
    return 0;
274
  }
275
276
  size_t nchars;
277
506
  size_t alignment = reinterpret_cast<uintptr_t>(dst) % sizeof(*dst);
278
506
  if (alignment == 0) {
279
1004
    nchars = str->Write(isolate, dst, 0, max_chars, flags);
280
502
    *chars_written = nchars;
281
502
    return nchars * sizeof(*dst);
282
  }
283
284
  uint16_t* aligned_dst =
285
4
      reinterpret_cast<uint16_t*>(buf + sizeof(*dst) - alignment);
286
4
  CHECK_EQ(reinterpret_cast<uintptr_t>(aligned_dst) % sizeof(*dst), 0);
287
288
  // Write all but the last char
289
8
  nchars = str->Write(isolate, aligned_dst, 0, max_chars - 1, flags);
290
291
  // Shift everything to unaligned-left
292
4
  memmove(dst, aligned_dst, nchars * sizeof(*dst));
293
294
  // One more char to be written
295
  uint16_t last;
296

8
  if (nchars == max_chars - 1 &&
297
8
      str->Write(isolate, &last, nchars, 1, flags) != 0) {
298
4
    memcpy(buf + nchars * sizeof(*dst), &last, sizeof(last));
299
4
    nchars++;
300
  }
301
302
4
  *chars_written = nchars;
303
4
  return nchars * sizeof(*dst);
304
}
305
306
307
402778
size_t StringBytes::Write(Isolate* isolate,
308
                          char* buf,
309
                          size_t buflen,
310
                          Local<Value> val,
311
                          enum encoding encoding,
312
                          int* chars_written) {
313
402778
  HandleScope scope(isolate);
314
  size_t nbytes;
315
  int nchars;
316
317
402778
  if (chars_written == nullptr)
318
402778
    chars_written = &nchars;
319
320
805556
  CHECK(val->IsString() == true);
321
402778
  Local<String> str = val.As<String>();
322
323
  int flags = String::HINT_MANY_WRITES_EXPECTED |
324
              String::NO_NULL_TERMINATION |
325
402778
              String::REPLACE_INVALID_UTF8;
326
327

402778
  switch (encoding) {
328
    case ASCII:
329
    case LATIN1:
330
30803
      if (str->IsExternalOneByte()) {
331
1
        auto ext = str->GetExternalOneByteStringResource();
332
1
        nbytes = std::min(buflen, ext->length());
333
1
        memcpy(buf, ext->data(), nbytes);
334
      } else {
335
30802
        uint8_t* const dst = reinterpret_cast<uint8_t*>(buf);
336
61604
        nbytes = str->WriteOneByte(isolate, dst, 0, buflen, flags);
337
      }
338
30803
      *chars_written = nbytes;
339
30803
      break;
340
341
    case BUFFER:
342
    case UTF8:
343
737796
      nbytes = str->WriteUtf8(isolate, buf, buflen, chars_written, flags);
344
368898
      break;
345
346
    case UCS2: {
347
      size_t nchars;
348
349
511
      nbytes = WriteUCS2(isolate, buf, buflen, str, flags, &nchars);
350
511
      *chars_written = static_cast<int>(nchars);
351
352
      // Node's "ucs2" encoding wants LE character data stored in
353
      // the Buffer, so we need to reorder on BE platforms.  See
354
      // https://nodejs.org/api/buffer.html regarding Node's "ucs2"
355
      // encoding specification
356
511
      if (IsBigEndian())
357
        SwapBytes16(buf, nbytes);
358
359
511
      break;
360
    }
361
362
    case BASE64:
363
218
      if (str->IsExternalOneByte()) {
364
4
        auto ext = str->GetExternalOneByteStringResource();
365
4
        nbytes = base64_decode(buf, buflen, ext->data(), ext->length());
366
      } else {
367
214
        String::Value value(isolate, str);
368
214
        nbytes = base64_decode(buf, buflen, *value, value.length());
369
      }
370
218
      *chars_written = nbytes;
371
218
      break;
372
373
    case HEX:
374
2348
      if (str->IsExternalOneByte()) {
375
22
        auto ext = str->GetExternalOneByteStringResource();
376
22
        nbytes = hex_decode(buf, buflen, ext->data(), ext->length());
377
      } else {
378
2326
        String::Value value(isolate, str);
379
2326
        nbytes = hex_decode(buf, buflen, *value, value.length());
380
      }
381
2348
      *chars_written = nbytes;
382
2348
      break;
383
384
    default:
385
      CHECK(0 && "unknown encoding");
386
      break;
387
  }
388
389
402778
  return nbytes;
390
}
391
392
393
867
bool StringBytes::IsValidString(Local<String> string,
394
                                enum encoding enc) {
395

997
  if (enc == HEX && string->Length() % 2 != 0)
396
3
    return false;
397
  // TODO(bnoordhuis) Add BASE64 check?
398
864
  return true;
399
}
400
401
402
// Quick and dirty size calculation
403
// Will always be at least big enough, but may have some extra
404
// UTF8 can be as much as 3x the size, Base64 can have 1-2 extra bytes
405
1759825
Maybe<size_t> StringBytes::StorageSize(Isolate* isolate,
406
                                       Local<Value> val,
407
                                       enum encoding encoding) {
408
1759825
  HandleScope scope(isolate);
409
1759825
  size_t data_size = 0;
410
1759825
  bool is_buffer = Buffer::HasInstance(val);
411
412

1759825
  if (is_buffer && (encoding == BUFFER || encoding == LATIN1)) {
413
    return Just(Buffer::Length(val));
414
  }
415
416
  Local<String> str;
417
5279475
  if (!val->ToString(isolate->GetCurrentContext()).ToLocal(&str))
418
    return Nothing<size_t>();
419
420

1759826
  switch (encoding) {
421
    case ASCII:
422
    case LATIN1:
423
29853
      data_size = str->Length();
424
29853
      break;
425
426
    case BUFFER:
427
    case UTF8:
428
      // A single UCS2 codepoint never takes up more than 3 utf8 bytes.
429
      // It is an exercise for the caller to decide when a string is
430
      // long enough to justify calling Size() instead of StorageSize()
431
1728804
      data_size = 3 * str->Length();
432
1728802
      break;
433
434
    case UCS2:
435
6
      data_size = str->Length() * sizeof(uint16_t);
436
6
      break;
437
438
    case BASE64:
439
10
      data_size = base64_decoded_size_fast(str->Length());
440
10
      break;
441
442
    case HEX:
443

1153
      CHECK(str->Length() % 2 == 0 && "invalid hex string length");
444
1153
      data_size = str->Length() / 2;
445
1153
      break;
446
447
    default:
448
      CHECK(0 && "unknown encoding");
449
      break;
450
  }
451
452
1759824
  return Just(data_size);
453
}
454
455
4730
Maybe<size_t> StringBytes::Size(Isolate* isolate,
456
                                Local<Value> val,
457
                                enum encoding encoding) {
458
4730
  HandleScope scope(isolate);
459
460


4730
  if (Buffer::HasInstance(val) && (encoding == BUFFER || encoding == LATIN1))
461
    return Just(Buffer::Length(val));
462
463
  Local<String> str;
464
14190
  if (!val->ToString(isolate->GetCurrentContext()).ToLocal(&str))
465
    return Nothing<size_t>();
466
467

4730
  switch (encoding) {
468
    case ASCII:
469
    case LATIN1:
470
17
      return Just<size_t>(str->Length());
471
472
    case BUFFER:
473
    case UTF8:
474
4587
      return Just<size_t>(str->Utf8Length(isolate));
475
476
    case UCS2:
477
97
      return Just(str->Length() * sizeof(uint16_t));
478
479
    case BASE64: {
480
5
      String::Value value(isolate, str);
481
5
      return Just(base64_decoded_size(*value, value.length()));
482
    }
483
484
    case HEX:
485
24
      return Just<size_t>(str->Length() / 2);
486
  }
487
488
  UNREACHABLE();
489
}
490
491
492
493
494
4268
static bool contains_non_ascii_slow(const char* buf, size_t len) {
495
21182
  for (size_t i = 0; i < len; ++i) {
496
16973
    if (buf[i] & 0x80)
497
59
      return true;
498
  }
499
4209
  return false;
500
}
501
502
503
4419
static bool contains_non_ascii(const char* src, size_t len) {
504
4419
  if (len < 16) {
505
4187
    return contains_non_ascii_slow(src, len);
506
  }
507
508
232
  const unsigned bytes_per_word = sizeof(uintptr_t);
509
232
  const unsigned align_mask = bytes_per_word - 1;
510
232
  const unsigned unaligned = reinterpret_cast<uintptr_t>(src) & align_mask;
511
512
232
  if (unaligned > 0) {
513
51
    const unsigned n = bytes_per_word - unaligned;
514
51
    if (contains_non_ascii_slow(src, n))
515
17
      return true;
516
34
    src += n;
517
34
    len -= n;
518
  }
519
520
521
#if defined(_WIN64) || defined(_LP64)
522
215
  const uintptr_t mask = 0x8080808080808080ll;
523
#else
524
  const uintptr_t mask = 0x80808080l;
525
#endif
526
527
215
  const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
528
529
134220640
  for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
530
134220590
    if (srcw[i] & mask)
531
165
      return true;
532
  }
533
534
50
  const unsigned remainder = len & align_mask;
535
50
  if (remainder > 0) {
536
30
    const size_t offset = len - remainder;
537
30
    if (contains_non_ascii_slow(src + offset, remainder))
538
      return true;
539
  }
540
541
50
  return false;
542
}
543
544
545
208
static void force_ascii_slow(const char* src, char* dst, size_t len) {
546
3357
  for (size_t i = 0; i < len; ++i) {
547
3149
    dst[i] = src[i] & 0x7f;
548
  }
549
208
}
550
551
552
224
static void force_ascii(const char* src, char* dst, size_t len) {
553
224
  if (len < 16) {
554
42
    force_ascii_slow(src, dst, len);
555
42
    return;
556
  }
557
558
182
  const unsigned bytes_per_word = sizeof(uintptr_t);
559
182
  const unsigned align_mask = bytes_per_word - 1;
560
182
  const unsigned src_unalign = reinterpret_cast<uintptr_t>(src) & align_mask;
561
182
  const unsigned dst_unalign = reinterpret_cast<uintptr_t>(dst) & align_mask;
562
563
182
  if (src_unalign > 0) {
564
50
    if (src_unalign == dst_unalign) {
565
      const unsigned unalign = bytes_per_word - src_unalign;
566
      force_ascii_slow(src, dst, unalign);
567
      src += unalign;
568
      dst += unalign;
569
      len -= src_unalign;
570
    } else {
571
50
      force_ascii_slow(src, dst, len);
572
50
      return;
573
    }
574
  }
575
576
#if defined(_WIN64) || defined(_LP64)
577
132
  const uintptr_t mask = ~0x8080808080808080ll;
578
#else
579
  const uintptr_t mask = ~0x80808080l;
580
#endif
581
582
132
  const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
583
132
  uintptr_t* dstw = reinterpret_cast<uintptr_t*>(dst);
584
585
891
  for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
586
759
    dstw[i] = srcw[i] & mask;
587
  }
588
589
132
  const unsigned remainder = len & align_mask;
590
132
  if (remainder > 0) {
591
116
    const size_t offset = len - remainder;
592
116
    force_ascii_slow(src + offset, dst + offset, remainder);
593
  }
594
}
595
596
597
2595
static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) {
598
  // We know how much we'll write, just make sure that there's space.
599
2595
  CHECK(dlen >= slen * 2 &&
600
      "not enough space provided for hex encode");
601
602
2595
  dlen = slen * 2;
603
1078976160
  for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) {
604
    static const char hex[] = "0123456789abcdef";
605
1078973565
    uint8_t val = static_cast<uint8_t>(src[i]);
606
1078973565
    dst[k + 0] = hex[val >> 4];
607
1078973565
    dst[k + 1] = hex[val & 15];
608
  }
609
610
2595
  return dlen;
611
}
612
613
614
#define CHECK_BUFLEN_IN_RANGE(len)                                    \
615
  do {                                                                \
616
    if ((len) > Buffer::kMaxLength) {                                 \
617
      *error = node::ERR_BUFFER_TOO_LARGE(isolate);                   \
618
      return MaybeLocal<Value>();                                     \
619
    }                                                                 \
620
  } while (0)
621
622
623
625194
MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
624
                                      const char* buf,
625
                                      size_t buflen,
626
                                      enum encoding encoding,
627
                                      Local<Value>* error) {
628
625194
  CHECK_BUFLEN_IN_RANGE(buflen);
629
630

625194
  if (!buflen && encoding != BUFFER) {
631
157
    return String::Empty(isolate);
632
  }
633
634
  MaybeLocal<String> val;
635
636


625037
  switch (encoding) {
637
    case BUFFER:
638
      {
639
530
        if (buflen > node::Buffer::kMaxLength) {
640
          *error = node::ERR_BUFFER_TOO_LARGE(isolate);
641
          return MaybeLocal<Value>();
642
        }
643
530
        auto maybe_buf = Buffer::Copy(isolate, buf, buflen);
644
530
        if (maybe_buf.IsEmpty()) {
645
          *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
646
          return MaybeLocal<Value>();
647
        }
648
530
        return maybe_buf.ToLocalChecked();
649
      }
650
651
    case ASCII:
652
4419
      if (contains_non_ascii(buf, buflen)) {
653
224
        char* out = node::UncheckedMalloc(buflen);
654
224
        if (out == nullptr) {
655
          *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
656
          return MaybeLocal<Value>();
657
        }
658
224
        force_ascii(buf, out, buflen);
659
224
        return ExternOneByteString::New(isolate, out, buflen, error);
660
      } else {
661
4195
        return ExternOneByteString::NewFromCopy(isolate, buf, buflen, error);
662
      }
663
664
    case UTF8:
665
      val = String::NewFromUtf8(isolate,
666
                                buf,
667
                                v8::NewStringType::kNormal,
668
613083
                                buflen);
669
613084
      if (val.IsEmpty()) {
670
3
        *error = node::ERR_STRING_TOO_LONG(isolate);
671
3
        return MaybeLocal<Value>();
672
      }
673
613081
      return val.ToLocalChecked();
674
675
    case LATIN1:
676
646
      return ExternOneByteString::NewFromCopy(isolate, buf, buflen, error);
677
678
    case BASE64: {
679
525
      size_t dlen = base64_encoded_size(buflen);
680
525
      char* dst = node::UncheckedMalloc(dlen);
681
525
      if (dst == nullptr) {
682
        *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
683
        return MaybeLocal<Value>();
684
      }
685
686
525
      size_t written = base64_encode(buf, buflen, dst, dlen);
687
525
      CHECK_EQ(written, dlen);
688
689
525
      return ExternOneByteString::New(isolate, dst, dlen, error);
690
    }
691
692
    case HEX: {
693
2595
      size_t dlen = buflen * 2;
694
2595
      char* dst = node::UncheckedMalloc(dlen);
695
2595
      if (dst == nullptr) {
696
        *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
697
        return MaybeLocal<Value>();
698
      }
699
2595
      size_t written = hex_encode(buf, buflen, dst, dlen);
700
2595
      CHECK_EQ(written, dlen);
701
702
2595
      return ExternOneByteString::New(isolate, dst, dlen, error);
703
    }
704
705
    case UCS2: {
706
3239
      if (IsBigEndian()) {
707
        uint16_t* dst = node::UncheckedMalloc<uint16_t>(buflen / 2);
708
        if (dst == nullptr) {
709
          *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
710
          return MaybeLocal<Value>();
711
        }
712
        for (size_t i = 0, k = 0; k < buflen / 2; i += 2, k += 1) {
713
          // The input is in *little endian*, because that's what Node.js
714
          // expects, so the high byte comes after the low byte.
715
          const uint8_t hi = static_cast<uint8_t>(buf[i + 1]);
716
          const uint8_t lo = static_cast<uint8_t>(buf[i + 0]);
717
          dst[k] = static_cast<uint16_t>(hi) << 8 | lo;
718
        }
719
        return ExternTwoByteString::New(isolate, dst, buflen / 2, error);
720
      }
721
3239
      if (reinterpret_cast<uintptr_t>(buf) % 2 != 0) {
722
        // Unaligned data still means we can't directly pass it to V8.
723
54
        char* dst = node::UncheckedMalloc(buflen);
724
54
        if (dst == nullptr) {
725
          *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
726
          return MaybeLocal<Value>();
727
        }
728
54
        memcpy(dst, buf, buflen);
729
        return ExternTwoByteString::New(
730
54
            isolate, reinterpret_cast<uint16_t*>(dst), buflen / 2, error);
731
      }
732
      return ExternTwoByteString::NewFromCopy(
733
3185
          isolate, reinterpret_cast<const uint16_t*>(buf), buflen / 2, error);
734
    }
735
736
    default:
737
      CHECK(0 && "unknown encoding");
738
      break;
739
  }
740
741
  UNREACHABLE();
742
}
743
744
745
MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
746
                                      const uint16_t* buf,
747
                                      size_t buflen,
748
                                      Local<Value>* error) {
749
  CHECK_BUFLEN_IN_RANGE(buflen);
750
751
  // Node's "ucs2" encoding expects LE character data inside a
752
  // Buffer, so we need to reorder on BE platforms.  See
753
  // https://nodejs.org/api/buffer.html regarding Node's "ucs2"
754
  // encoding specification
755
  if (IsBigEndian()) {
756
    uint16_t* dst = node::UncheckedMalloc<uint16_t>(buflen);
757
    if (dst == nullptr) {
758
      *error = node::ERR_MEMORY_ALLOCATION_FAILED(isolate);
759
      return MaybeLocal<Value>();
760
    }
761
    size_t nbytes = buflen * sizeof(uint16_t);
762
    memcpy(dst, buf, nbytes);
763
    SwapBytes16(reinterpret_cast<char*>(dst), nbytes);
764
    return ExternTwoByteString::New(isolate, dst, buflen, error);
765
  } else {
766
    return ExternTwoByteString::NewFromCopy(isolate, buf, buflen, error);
767
  }
768
}
769
770
544376
MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
771
                                      const char* buf,
772
                                      enum encoding encoding,
773
                                      Local<Value>* error) {
774
544376
  const size_t len = strlen(buf);
775
544376
  return Encode(isolate, buf, len, encoding, error);
776
}
777
778
}  // namespace node