GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/string_bytes.cc Lines: 250 309 80.9 %
Date: 2020-08-17 22:13:26 Branches: 133 198 67.2 %

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 "env-inl.h"
26
#include "node_buffer.h"
27
#include "node_errors.h"
28
#include "util.h"
29
30
#include <climits>
31
#include <cstring>  // memcpy
32
33
#include <algorithm>
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
64
  ~ExternString() override {
58
32
    free(const_cast<TypeName*>(data_));
59
32
    isolate()->AdjustAmountOfExternalAllocatedMemory(-byte_length());
60
96
  }
61
62
158
  const TypeName* data() const override {
63
158
    return data_;
64
  }
65
66
273
  size_t length() const override {
67
273
    return length_;
68
  }
69
70
64
  int64_t byte_length() const {
71
64
    return length() * sizeof(*data());
72
  }
73
74
16221
  static MaybeLocal<Value> NewFromCopy(Isolate* isolate,
75
                                       const TypeName* data,
76
                                       size_t length,
77
                                       Local<Value>* error) {
78

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

16219
    if (length < EXTERN_APEX)
82
16205
      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
704549
  static MaybeLocal<Value> New(Isolate* isolate,
99
                               TypeName* data,
100
                               size_t length,
101
                               Local<Value>* error) {
102

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

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

32
    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
27
    return str.ToLocalChecked();
124
  }
125
126
32
  inline Isolate* isolate() const { return isolate_; }
127
128
 private:
129
32
  ExternString(Isolate* isolate, const TypeName* data, size_t length)
130
32
    : 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
27
MaybeLocal<Value> ExternOneByteString::NewExternal(
154
    Isolate* isolate, ExternOneByteString* h_str) {
155
54
  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
709864
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
709864
                             length);
175
709864
  if (str.IsEmpty()) {
176
    *error = node::ERR_STRING_TOO_LONG(isolate);
177
    return MaybeLocal<Value>();
178
  }
179
709864
  return str.ToLocalChecked();
180
}
181
182
183
template <>
184
10858
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
10858
                             length);
193
10858
  if (str.IsEmpty()) {
194
    *error = node::ERR_STRING_TOO_LONG(isolate);
195
    return MaybeLocal<Value>();
196
  }
197
10858
  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
183244842
static inline unsigned unhex(uint8_t x) {
243
183244842
  return unhex_table[x];
244
}
245
246
template <typename TypeName>
247
2422
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


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


91622421
    if (!~a || !~b)
256
9
      return i;
257
91622412
    buf[i] = (a << 4) | b;
258
  }
259
260
2413
  return i;
261
}
262
263
174
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
174
  uint16_t* const dst = reinterpret_cast<uint16_t*>(buf);
270
271
174
  size_t max_chars = buflen / sizeof(*dst);
272
174
  if (max_chars == 0) {
273
5
    return 0;
274
  }
275
276
169
  uint16_t* const aligned_dst = AlignUp(dst, sizeof(*dst));
277
  size_t nchars;
278
169
  if (aligned_dst == dst) {
279
328
    nchars = str->Write(isolate, dst, 0, max_chars, flags);
280
164
    *chars_written = nchars;
281
164
    return nchars * sizeof(*dst);
282
  }
283
284
5
  CHECK_EQ(reinterpret_cast<uintptr_t>(aligned_dst) % sizeof(*dst), 0);
285
286
  // Write all but the last char
287
5
  max_chars = std::min(max_chars, static_cast<size_t>(str->Length()));
288
5
  if (max_chars == 0) return 0;
289
10
  nchars = str->Write(isolate, aligned_dst, 0, max_chars - 1, flags);
290
5
  CHECK_EQ(nchars, max_chars - 1);
291
292
  // Shift everything to unaligned-left
293
5
  memmove(dst, aligned_dst, nchars * sizeof(*dst));
294
295
  // One more char to be written
296
  uint16_t last;
297
10
  CHECK_EQ(str->Write(isolate, &last, nchars, 1, flags), 1);
298
5
  memcpy(buf + nchars * sizeof(*dst), &last, sizeof(last));
299
5
  nchars++;
300
301
5
  *chars_written = nchars;
302
5
  return nchars * sizeof(*dst);
303
}
304
305
306
1201088
size_t StringBytes::Write(Isolate* isolate,
307
                          char* buf,
308
                          size_t buflen,
309
                          Local<Value> val,
310
                          enum encoding encoding,
311
                          int* chars_written) {
312
2402176
  HandleScope scope(isolate);
313
  size_t nbytes;
314
  int nchars;
315
316
1201088
  if (chars_written == nullptr)
317
1201088
    chars_written = &nchars;
318
319
2402176
  CHECK(val->IsString() == true);
320
1201088
  Local<String> str = val.As<String>();
321
322
  int flags = String::HINT_MANY_WRITES_EXPECTED |
323
              String::NO_NULL_TERMINATION |
324
1201088
              String::REPLACE_INVALID_UTF8;
325
326

1201088
  switch (encoding) {
327
    case ASCII:
328
    case LATIN1:
329
35682
      if (str->IsExternalOneByte()) {
330
1
        auto ext = str->GetExternalOneByteStringResource();
331
1
        nbytes = std::min(buflen, ext->length());
332
1
        memcpy(buf, ext->data(), nbytes);
333
      } else {
334
35681
        uint8_t* const dst = reinterpret_cast<uint8_t*>(buf);
335
71362
        nbytes = str->WriteOneByte(isolate, dst, 0, buflen, flags);
336
      }
337
35682
      *chars_written = nbytes;
338
35682
      break;
339
340
    case BUFFER:
341
    case UTF8:
342
1627808
      nbytes = str->WriteUtf8(isolate, buf, buflen, chars_written, flags);
343
813904
      break;
344
345
    case UCS2: {
346
      size_t nchars;
347
348
174
      nbytes = WriteUCS2(isolate, buf, buflen, str, flags, &nchars);
349
174
      *chars_written = static_cast<int>(nchars);
350
351
      // Node's "ucs2" encoding wants LE character data stored in
352
      // the Buffer, so we need to reorder on BE platforms.  See
353
      // https://nodejs.org/api/buffer.html regarding Node's "ucs2"
354
      // encoding specification
355
174
      if (IsBigEndian())
356
        SwapBytes16(buf, nbytes);
357
358
174
      break;
359
    }
360
361
    case BASE64:
362
348906
      if (str->IsExternalOneByte()) {
363
4
        auto ext = str->GetExternalOneByteStringResource();
364
4
        nbytes = base64_decode(buf, buflen, ext->data(), ext->length());
365
      } else {
366
697804
        String::Value value(isolate, str);
367
348902
        nbytes = base64_decode(buf, buflen, *value, value.length());
368
      }
369
348906
      *chars_written = nbytes;
370
348906
      break;
371
372
    case HEX:
373
2422
      if (str->IsExternalOneByte()) {
374
91
        auto ext = str->GetExternalOneByteStringResource();
375
91
        nbytes = hex_decode(buf, buflen, ext->data(), ext->length());
376
      } else {
377
4662
        String::Value value(isolate, str);
378
2331
        nbytes = hex_decode(buf, buflen, *value, value.length());
379
      }
380
2422
      *chars_written = nbytes;
381
2422
      break;
382
383
    default:
384
      CHECK(0 && "unknown encoding");
385
      break;
386
  }
387
388
2402176
  return nbytes;
389
}
390
391
392
// Quick and dirty size calculation
393
// Will always be at least big enough, but may have some extra
394
// UTF8 can be as much as 3x the size, Base64 can have 1-2 extra bytes
395
4339929
Maybe<size_t> StringBytes::StorageSize(Isolate* isolate,
396
                                       Local<Value> val,
397
                                       enum encoding encoding) {
398
8679858
  HandleScope scope(isolate);
399
4339937
  size_t data_size = 0;
400
4339937
  bool is_buffer = Buffer::HasInstance(val);
401
402

4339934
  if (is_buffer && (encoding == BUFFER || encoding == LATIN1)) {
403
    return Just(Buffer::Length(val));
404
  }
405
406
  Local<String> str;
407
13019799
  if (!val->ToString(isolate->GetCurrentContext()).ToLocal(&str))
408
    return Nothing<size_t>();
409
410

4339933
  switch (encoding) {
411
    case ASCII:
412
    case LATIN1:
413
33832
      data_size = str->Length();
414
33832
      break;
415
416
    case BUFFER:
417
    case UTF8:
418
      // A single UCS2 codepoint never takes up more than 3 utf8 bytes.
419
      // It is an exercise for the caller to decide when a string is
420
      // long enough to justify calling Size() instead of StorageSize()
421
4304932
      data_size = 3 * str->Length();
422
4304929
      break;
423
424
    case UCS2:
425
6
      data_size = str->Length() * sizeof(uint16_t);
426
6
      break;
427
428
    case BASE64:
429
10
      data_size = base64_decoded_size_fast(str->Length());
430
10
      break;
431
432
    case HEX:
433

1153
      CHECK(str->Length() % 2 == 0 && "invalid hex string length");
434
1153
      data_size = str->Length() / 2;
435
1153
      break;
436
437
    default:
438
      CHECK(0 && "unknown encoding");
439
      break;
440
  }
441
442
4339930
  return Just(data_size);
443
}
444
445
1114
Maybe<size_t> StringBytes::Size(Isolate* isolate,
446
                                Local<Value> val,
447
                                enum encoding encoding) {
448
2228
  HandleScope scope(isolate);
449
450


1114
  if (Buffer::HasInstance(val) && (encoding == BUFFER || encoding == LATIN1))
451
    return Just(Buffer::Length(val));
452
453
  Local<String> str;
454
3342
  if (!val->ToString(isolate->GetCurrentContext()).ToLocal(&str))
455
    return Nothing<size_t>();
456
457

1114
  switch (encoding) {
458
    case ASCII:
459
    case LATIN1:
460
17
      return Just<size_t>(str->Length());
461
462
    case BUFFER:
463
    case UTF8:
464
902
      return Just<size_t>(str->Utf8Length(isolate));
465
466
    case UCS2:
467
97
      return Just(str->Length() * sizeof(uint16_t));
468
469
    case BASE64: {
470
10
      String::Value value(isolate, str);
471
5
      return Just(base64_decoded_size(*value, value.length()));
472
    }
473
474
    case HEX:
475
93
      return Just<size_t>(str->Length() / 2);
476
  }
477
478
  UNREACHABLE();
479
}
480
481
482
483
484
4405
static bool contains_non_ascii_slow(const char* buf, size_t len) {
485
21714
  for (size_t i = 0; i < len; ++i) {
486
17432
    if (buf[i] & 0x80)
487
123
      return true;
488
  }
489
4282
  return false;
490
}
491
492
493
4796
static bool contains_non_ascii(const char* src, size_t len) {
494
4796
  if (len < 16) {
495
4298
    return contains_non_ascii_slow(src, len);
496
  }
497
498
498
  const unsigned bytes_per_word = sizeof(uintptr_t);
499
498
  const unsigned align_mask = bytes_per_word - 1;
500
498
  const unsigned unaligned = reinterpret_cast<uintptr_t>(src) & align_mask;
501
502
498
  if (unaligned > 0) {
503
51
    const unsigned n = bytes_per_word - unaligned;
504
51
    if (contains_non_ascii_slow(src, n))
505
17
      return true;
506
34
    src += n;
507
34
    len -= n;
508
  }
509
510
511
#if defined(_WIN64) || defined(_LP64)
512
481
  const uintptr_t mask = 0x8080808080808080ll;
513
#else
514
  const uintptr_t mask = 0x80808080l;
515
#endif
516
517
481
  const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
518
519
67112030
  for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
520
67111973
    if (srcw[i] & mask)
521
424
      return true;
522
  }
523
524
57
  const unsigned remainder = len & align_mask;
525
57
  if (remainder > 0) {
526
56
    const size_t offset = len - remainder;
527
56
    if (contains_non_ascii_slow(src + offset, remainder))
528
      return true;
529
  }
530
531
57
  return false;
532
}
533
534
535
490
static void force_ascii_slow(const char* src, char* dst, size_t len) {
536
5114
  for (size_t i = 0; i < len; ++i) {
537
4624
    dst[i] = src[i] & 0x7f;
538
  }
539
490
}
540
541
542
547
static void force_ascii(const char* src, char* dst, size_t len) {
543
547
  if (len < 16) {
544
106
    force_ascii_slow(src, dst, len);
545
106
    return;
546
  }
547
548
441
  const unsigned bytes_per_word = sizeof(uintptr_t);
549
441
  const unsigned align_mask = bytes_per_word - 1;
550
441
  const unsigned src_unalign = reinterpret_cast<uintptr_t>(src) & align_mask;
551
441
  const unsigned dst_unalign = reinterpret_cast<uintptr_t>(dst) & align_mask;
552
553
441
  if (src_unalign > 0) {
554
50
    if (src_unalign == dst_unalign) {
555
      const unsigned unalign = bytes_per_word - src_unalign;
556
      force_ascii_slow(src, dst, unalign);
557
      src += unalign;
558
      dst += unalign;
559
      len -= src_unalign;
560
    } else {
561
50
      force_ascii_slow(src, dst, len);
562
50
      return;
563
    }
564
  }
565
566
#if defined(_WIN64) || defined(_LP64)
567
391
  const uintptr_t mask = ~0x8080808080808080ll;
568
#else
569
  const uintptr_t mask = ~0x80808080l;
570
#endif
571
572
391
  const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
573
391
  uintptr_t* dstw = reinterpret_cast<uintptr_t*>(dst);
574
575
2824
  for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
576
2433
    dstw[i] = srcw[i] & mask;
577
  }
578
579
391
  const unsigned remainder = len & align_mask;
580
391
  if (remainder > 0) {
581
334
    const size_t offset = len - remainder;
582
334
    force_ascii_slow(src + offset, dst + offset, remainder);
583
  }
584
}
585
586
587
702524
size_t StringBytes::hex_encode(
588
    const char* src,
589
    size_t slen,
590
    char* dst,
591
    size_t dlen) {
592
  // We know how much we'll write, just make sure that there's space.
593
702524
  CHECK(dlen >= slen * 2 &&
594
      "not enough space provided for hex encode");
595
596
702524
  dlen = slen * 2;
597
573230179
  for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) {
598
    static const char hex[] = "0123456789abcdef";
599
572527655
    uint8_t val = static_cast<uint8_t>(src[i]);
600
572527655
    dst[k + 0] = hex[val >> 4];
601
572527655
    dst[k + 1] = hex[val & 15];
602
  }
603
604
702524
  return dlen;
605
}
606
607
std::string StringBytes::hex_encode(const char* src, size_t slen) {
608
  size_t dlen = slen * 2;
609
  std::string dst(dlen, '\0');
610
  hex_encode(src, slen, &dst[0], dlen);
611
  return dst;
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
1494762
MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
624
                                      const char* buf,
625
                                      size_t buflen,
626
                                      enum encoding encoding,
627
                                      Local<Value>* error) {
628
1494762
  CHECK_BUFLEN_IN_RANGE(buflen);
629
630

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


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

13380
}  // namespace node