GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_i18n.cc Lines: 321 359 89.4 %
Date: 2019-03-02 22:23:06 Branches: 147 222 66.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
/*
23
 * notes: by srl295
24
 *  - When in NODE_HAVE_SMALL_ICU mode, ICU is linked against "stub" (null) data
25
 *     ( stubdata/libicudata.a ) containing nothing, no data, and it's also
26
 *    linked against a "small" data file which the SMALL_ICUDATA_ENTRY_POINT
27
 *    macro names. That's the "english+root" data.
28
 *
29
 *    If icu_data_path is non-null, the user has provided a path and we assume
30
 *    it goes somewhere useful. We set that path in ICU, and exit.
31
 *    If icu_data_path is null, they haven't set a path and we want the
32
 *    "english+root" data.  We call
33
 *       udata_setCommonData(SMALL_ICUDATA_ENTRY_POINT,...)
34
 *    to load up the english+root data.
35
 *
36
 *  - when NOT in NODE_HAVE_SMALL_ICU mode, ICU is linked directly with its full
37
 *    data. All of the variables and command line options for changing data at
38
 *    runtime are disabled, as they wouldn't fully override the internal data.
39
 *    See:  http://bugs.icu-project.org/trac/ticket/10924
40
 */
41
42
43
#include "node_i18n.h"
44
45
#if defined(NODE_HAVE_I18N_SUPPORT)
46
47
#include "base_object-inl.h"
48
#include "env-inl.h"
49
#include "node.h"
50
#include "node_buffer.h"
51
#include "node_errors.h"
52
#include "node_internals.h"
53
#include "util-inl.h"
54
#include "v8.h"
55
56
#include <unicode/utypes.h>
57
#include <unicode/putil.h>
58
#include <unicode/uchar.h>
59
#include <unicode/uclean.h>
60
#include <unicode/udata.h>
61
#include <unicode/uidna.h>
62
#include <unicode/ucnv.h>
63
#include <unicode/utf8.h>
64
#include <unicode/utf16.h>
65
#include <unicode/timezone.h>
66
#include <unicode/ulocdata.h>
67
#include <unicode/uvernum.h>
68
#include <unicode/uversion.h>
69
#include <unicode/ustring.h>
70
71
#ifdef NODE_HAVE_SMALL_ICU
72
/* if this is defined, we have a 'secondary' entry point.
73
   compare following to utypes.h defs for U_ICUDATA_ENTRY_POINT */
74
#define SMALL_ICUDATA_ENTRY_POINT \
75
  SMALL_DEF2(U_ICU_VERSION_MAJOR_NUM, U_LIB_SUFFIX_C_NAME)
76
#define SMALL_DEF2(major, suff) SMALL_DEF(major, suff)
77
#ifndef U_LIB_SUFFIX_C_NAME
78
#define SMALL_DEF(major, suff) icusmdt##major##_dat
79
#else
80
#define SMALL_DEF(major, suff) icusmdt##suff##major##_dat
81
#endif
82
83
extern "C" const char U_DATA_API SMALL_ICUDATA_ENTRY_POINT[];
84
#endif
85
86
namespace node {
87
88
using v8::Context;
89
using v8::FunctionCallbackInfo;
90
using v8::HandleScope;
91
using v8::Int32;
92
using v8::Isolate;
93
using v8::Local;
94
using v8::MaybeLocal;
95
using v8::NewStringType;
96
using v8::Object;
97
using v8::ObjectTemplate;
98
using v8::String;
99
using v8::Value;
100
101
namespace i18n {
102
namespace {
103
104
template <typename T>
105
534
MaybeLocal<Object> ToBufferEndian(Environment* env, MaybeStackBuffer<T>* buf) {
106
534
  MaybeLocal<Object> ret = Buffer::New(env, buf);
107

534
  if (ret.IsEmpty())
108
    return ret;
109
110
  static_assert(sizeof(T) == 1 || sizeof(T) == 2,
111
                "Currently only one- or two-byte buffers are supported");
112

534
  if (sizeof(T) > 1 && IsBigEndian()) {
113
    SPREAD_BUFFER_ARG(ret.ToLocalChecked(), retbuf);
114
    SwapBytes16(retbuf_data, retbuf_length);
115
  }
116
117
534
  return ret;
118
}
119
120
struct Converter {
121
8
  explicit Converter(const char* name, const char* sub = nullptr)
122
8
      : conv(nullptr) {
123
8
    UErrorCode status = U_ZERO_ERROR;
124
8
    conv = ucnv_open(name, &status);
125
8
    CHECK(U_SUCCESS(status));
126
8
    if (sub != nullptr) {
127
2
      ucnv_setSubstChars(conv, sub, strlen(sub), &status);
128
    }
129
8
  }
130
131
205
  explicit Converter(UConverter* converter,
132
205
                     const char* sub = nullptr) : conv(converter) {
133
205
    CHECK_NOT_NULL(conv);
134
205
    UErrorCode status = U_ZERO_ERROR;
135
205
    if (sub != nullptr) {
136
      ucnv_setSubstChars(conv, sub, strlen(sub), &status);
137
    }
138
205
  }
139
140
213
  ~Converter() {
141
213
    ucnv_close(conv);
142
213
  }
143
144
  UConverter* conv;
145
};
146
147
class ConverterObject : public BaseObject, Converter {
148
 public:
149
  enum ConverterFlags {
150
    CONVERTER_FLAGS_FLUSH      = 0x1,
151
    CONVERTER_FLAGS_FATAL      = 0x2,
152
    CONVERTER_FLAGS_IGNORE_BOM = 0x4
153
  };
154
155
410
  ~ConverterObject() override {}
156
157
2
  static void Has(const FunctionCallbackInfo<Value>& args) {
158
2
    Environment* env = Environment::GetCurrent(args);
159
2
    HandleScope scope(env->isolate());
160
161
2
    CHECK_GE(args.Length(), 1);
162
4
    Utf8Value label(env->isolate(), args[0]);
163
164
2
    UErrorCode status = U_ZERO_ERROR;
165
2
    UConverter* conv = ucnv_open(*label, &status);
166
6
    args.GetReturnValue().Set(!!U_SUCCESS(status));
167
4
    ucnv_close(conv);
168
2
  }
169
170
205
  static void Create(const FunctionCallbackInfo<Value>& args) {
171
205
    Environment* env = Environment::GetCurrent(args);
172
205
    HandleScope scope(env->isolate());
173
174
205
    Local<ObjectTemplate> t = ObjectTemplate::New(env->isolate());
175
205
    t->SetInternalFieldCount(1);
176
    Local<Object> obj;
177
615
    if (!t->NewInstance(env->context()).ToLocal(&obj)) return;
178
179
205
    CHECK_GE(args.Length(), 2);
180
410
    Utf8Value label(env->isolate(), args[0]);
181
820
    int flags = args[1]->Uint32Value(env->context()).ToChecked();
182
    bool fatal =
183
205
        (flags & CONVERTER_FLAGS_FATAL) == CONVERTER_FLAGS_FATAL;
184
    bool ignoreBOM =
185
205
        (flags & CONVERTER_FLAGS_IGNORE_BOM) == CONVERTER_FLAGS_IGNORE_BOM;
186
187
205
    UErrorCode status = U_ZERO_ERROR;
188
205
    UConverter* conv = ucnv_open(*label, &status);
189
205
    if (U_FAILURE(status))
190
      return;
191
192
205
    if (fatal) {
193
94
      status = U_ZERO_ERROR;
194
      ucnv_setToUCallBack(conv, UCNV_TO_U_CALLBACK_STOP,
195
94
                          nullptr, nullptr, nullptr, &status);
196
    }
197
198
205
    new ConverterObject(env, obj, conv, ignoreBOM);
199
615
    args.GetReturnValue().Set(obj);
200
  }
201
202
616
  static void Decode(const FunctionCallbackInfo<Value>& args) {
203
616
    Environment* env = Environment::GetCurrent(args);
204
205
616
    CHECK_GE(args.Length(), 3);  // Converter, Buffer, Flags
206
207
    ConverterObject* converter;
208
1756
    ASSIGN_OR_RETURN_UNWRAP(&converter, args[0].As<Object>());
209

4928
    SPREAD_BUFFER_ARG(args[1], input_obj);
210
2464
    int flags = args[2]->Uint32Value(env->context()).ToChecked();
211
212
616
    UErrorCode status = U_ZERO_ERROR;
213
616
    MaybeStackBuffer<UChar> result;
214
    MaybeLocal<Object> ret;
215
616
    size_t limit = ucnv_getMinCharSize(converter->conv) *
216
616
                   input_obj_length;
217
616
    if (limit > 0)
218
590
      result.AllocateSufficientStorage(limit);
219
220
616
    UBool flush = (flags & CONVERTER_FLAGS_FLUSH) == CONVERTER_FLAGS_FLUSH;
221
616
    OnScopeLeave cleanup([&]() {
222
616
      if (flush) {
223
        // Reset the converter state.
224
198
        converter->bomSeen_ = false;
225
198
        ucnv_reset(converter->conv);
226
      }
227
1324
    });
228
229
616
    const char* source = input_obj_data;
230
616
    size_t source_length = input_obj_length;
231
232

616
    if (converter->unicode_ && !converter->ignoreBOM_ && !converter->bomSeen_) {
233
187
      int32_t bomOffset = 0;
234
187
      ucnv_detectUnicodeSignature(source, source_length, &bomOffset, &status);
235
187
      source += bomOffset;
236
187
      source_length -= bomOffset;
237
187
      converter->bomSeen_ = true;
238
    }
239
240
616
    UChar* target = *result;
241
    ucnv_toUnicode(converter->conv,
242
616
                   &target, target + (limit * sizeof(UChar)),
243
                   &source, source + source_length,
244
1232
                   nullptr, flush, &status);
245
246
616
    if (U_SUCCESS(status)) {
247
524
      if (limit > 0)
248
498
        result.SetLength(target - &result[0]);
249
524
      ret = ToBufferEndian(env, &result);
250
1048
      args.GetReturnValue().Set(ret.ToLocalChecked());
251
524
      return;
252
    }
253
254
368
    args.GetReturnValue().Set(status);
255
  }
256
257
  SET_NO_MEMORY_INFO()
258
  SET_MEMORY_INFO_NAME(ConverterObject)
259
  SET_SELF_SIZE(ConverterObject)
260
261
 protected:
262
205
  ConverterObject(Environment* env,
263
                  Local<Object> wrap,
264
                  UConverter* converter,
265
                  bool ignoreBOM,
266
                  const char* sub = nullptr) :
267
                  BaseObject(env, wrap),
268
                  Converter(converter, sub),
269
205
                  ignoreBOM_(ignoreBOM) {
270
205
    MakeWeak();
271
272
205
    switch (ucnv_getType(converter)) {
273
      case UCNV_UTF8:
274
      case UCNV_UTF16_BigEndian:
275
      case UCNV_UTF16_LittleEndian:
276
205
        unicode_ = true;
277
205
        break;
278
      default:
279
        unicode_ = false;
280
    }
281
205
  }
282
283
 private:
284
  bool unicode_ = false;     // True if this is a Unicode converter
285
  bool ignoreBOM_ = false;   // True if the BOM should be ignored on Unicode
286
  bool bomSeen_ = false;     // True if the BOM has been seen
287
};
288
289
// One-Shot Converters
290
291
2
void CopySourceBuffer(MaybeStackBuffer<UChar>* dest,
292
                      const char* data,
293
                      const size_t length,
294
                      const size_t length_in_chars) {
295
2
  dest->AllocateSufficientStorage(length_in_chars);
296
2
  char* dst = reinterpret_cast<char*>(**dest);
297
2
  memcpy(dst, data, length);
298
2
  if (IsBigEndian()) {
299
    SwapBytes16(dst, length);
300
  }
301
2
}
302
303
typedef MaybeLocal<Object> (*TranscodeFunc)(Environment* env,
304
                                            const char* fromEncoding,
305
                                            const char* toEncoding,
306
                                            const char* source,
307
                                            const size_t source_length,
308
                                            UErrorCode* status);
309
310
2
MaybeLocal<Object> Transcode(Environment* env,
311
                             const char* fromEncoding,
312
                             const char* toEncoding,
313
                             const char* source,
314
                             const size_t source_length,
315
                             UErrorCode* status) {
316
2
  *status = U_ZERO_ERROR;
317
  MaybeLocal<Object> ret;
318
2
  MaybeStackBuffer<char> result;
319
4
  Converter to(toEncoding, "?");
320
4
  Converter from(fromEncoding);
321
2
  const uint32_t limit = source_length * ucnv_getMaxCharSize(to.conv);
322
2
  result.AllocateSufficientStorage(limit);
323
2
  char* target = *result;
324
  ucnv_convertEx(to.conv, from.conv, &target, target + limit,
325
                 &source, source + source_length, nullptr, nullptr,
326
2
                 nullptr, nullptr, true, true, status);
327
2
  if (U_SUCCESS(*status)) {
328
2
    result.SetLength(target - &result[0]);
329
2
    ret = ToBufferEndian(env, &result);
330
  }
331
4
  return ret;
332
}
333
334
4
MaybeLocal<Object> TranscodeToUcs2(Environment* env,
335
                                   const char* fromEncoding,
336
                                   const char* toEncoding,
337
                                   const char* source,
338
                                   const size_t source_length,
339
                                   UErrorCode* status) {
340
4
  *status = U_ZERO_ERROR;
341
  MaybeLocal<Object> ret;
342
4
  MaybeStackBuffer<UChar> destbuf(source_length);
343
8
  Converter from(fromEncoding);
344
4
  const size_t length_in_chars = source_length * sizeof(UChar);
345
  ucnv_toUChars(from.conv, *destbuf, length_in_chars,
346
4
                source, source_length, status);
347
4
  if (U_SUCCESS(*status))
348
4
    ret = ToBufferEndian(env, &destbuf);
349
8
  return ret;
350
}
351
352
MaybeLocal<Object> TranscodeFromUcs2(Environment* env,
353
                                     const char* fromEncoding,
354
                                     const char* toEncoding,
355
                                     const char* source,
356
                                     const size_t source_length,
357
                                     UErrorCode* status) {
358
  *status = U_ZERO_ERROR;
359
  MaybeStackBuffer<UChar> sourcebuf;
360
  MaybeLocal<Object> ret;
361
  Converter to(toEncoding, "?");
362
  const size_t length_in_chars = source_length / sizeof(UChar);
363
  CopySourceBuffer(&sourcebuf, source, source_length, length_in_chars);
364
  MaybeStackBuffer<char> destbuf(length_in_chars);
365
  const uint32_t len = ucnv_fromUChars(to.conv, *destbuf, length_in_chars,
366
                                       *sourcebuf, length_in_chars, status);
367
  if (U_SUCCESS(*status)) {
368
    destbuf.SetLength(len);
369
    ret = ToBufferEndian(env, &destbuf);
370
  }
371
  return ret;
372
}
373
374
2
MaybeLocal<Object> TranscodeUcs2FromUtf8(Environment* env,
375
                                         const char* fromEncoding,
376
                                         const char* toEncoding,
377
                                         const char* source,
378
                                         const size_t source_length,
379
                                         UErrorCode* status) {
380
2
  *status = U_ZERO_ERROR;
381
2
  MaybeStackBuffer<UChar> destbuf;
382
  int32_t result_length;
383
2
  u_strFromUTF8(*destbuf, destbuf.capacity(), &result_length,
384
4
                source, source_length, status);
385
  MaybeLocal<Object> ret;
386
2
  if (U_SUCCESS(*status)) {
387
1
    destbuf.SetLength(result_length);
388
1
    ret = ToBufferEndian(env, &destbuf);
389
1
  } else if (*status == U_BUFFER_OVERFLOW_ERROR) {
390
1
    *status = U_ZERO_ERROR;
391
1
    destbuf.AllocateSufficientStorage(result_length);
392
    u_strFromUTF8(*destbuf, result_length, &result_length,
393
1
                  source, source_length, status);
394
1
    if (U_SUCCESS(*status)) {
395
1
      destbuf.SetLength(result_length);
396
1
      ret = ToBufferEndian(env, &destbuf);
397
    }
398
  }
399
2
  return ret;
400
}
401
402
2
MaybeLocal<Object> TranscodeUtf8FromUcs2(Environment* env,
403
                                         const char* fromEncoding,
404
                                         const char* toEncoding,
405
                                         const char* source,
406
                                         const size_t source_length,
407
                                         UErrorCode* status) {
408
2
  *status = U_ZERO_ERROR;
409
  MaybeLocal<Object> ret;
410
2
  const size_t length_in_chars = source_length / sizeof(UChar);
411
  int32_t result_length;
412
2
  MaybeStackBuffer<UChar> sourcebuf;
413
4
  MaybeStackBuffer<char> destbuf;
414
2
  CopySourceBuffer(&sourcebuf, source, source_length, length_in_chars);
415
2
  u_strToUTF8(*destbuf, destbuf.capacity(), &result_length,
416
4
              *sourcebuf, length_in_chars, status);
417
2
  if (U_SUCCESS(*status)) {
418
1
    destbuf.SetLength(result_length);
419
1
    ret = ToBufferEndian(env, &destbuf);
420
1
  } else if (*status == U_BUFFER_OVERFLOW_ERROR) {
421
1
    *status = U_ZERO_ERROR;
422
1
    destbuf.AllocateSufficientStorage(result_length);
423
1
    u_strToUTF8(*destbuf, result_length, &result_length, *sourcebuf,
424
2
                length_in_chars, status);
425
1
    if (U_SUCCESS(*status)) {
426
1
      destbuf.SetLength(result_length);
427
1
      ret = ToBufferEndian(env, &destbuf);
428
    }
429
  }
430
4
  return ret;
431
}
432
433
20
const char* EncodingName(const enum encoding encoding) {
434

20
  switch (encoding) {
435
2
    case ASCII: return "us-ascii";
436
4
    case LATIN1: return "iso8859-1";
437
8
    case UCS2: return "utf16le";
438
6
    case UTF8: return "utf-8";
439
    default: return nullptr;
440
  }
441
}
442
443
22
bool SupportedEncoding(const enum encoding encoding) {
444
22
  switch (encoding) {
445
    case ASCII:
446
    case LATIN1:
447
    case UCS2:
448
20
    case UTF8: return true;
449
2
    default: return false;
450
  }
451
}
452
453
12
void Transcode(const FunctionCallbackInfo<Value>&args) {
454
12
  Environment* env = Environment::GetCurrent(args);
455
12
  Isolate* isolate = env->isolate();
456
12
  UErrorCode status = U_ZERO_ERROR;
457
  MaybeLocal<Object> result;
458
459
12
  CHECK(Buffer::HasInstance(args[0]));
460

96
  SPREAD_BUFFER_ARG(args[0], ts_obj);
461
12
  const enum encoding fromEncoding = ParseEncoding(isolate, args[1], BUFFER);
462
12
  const enum encoding toEncoding = ParseEncoding(isolate, args[2], BUFFER);
463
464

12
  if (SupportedEncoding(fromEncoding) && SupportedEncoding(toEncoding)) {
465
10
    TranscodeFunc tfn = &Transcode;
466

10
    switch (fromEncoding) {
467
      case ASCII:
468
      case LATIN1:
469
4
        if (toEncoding == UCS2)
470
4
          tfn = &TranscodeToUcs2;
471
4
        break;
472
      case UTF8:
473
4
        if (toEncoding == UCS2)
474
2
          tfn = &TranscodeUcs2FromUtf8;
475
4
        break;
476
      case UCS2:
477
2
        switch (toEncoding) {
478
          case UCS2:
479
            tfn = &Transcode;
480
            break;
481
          case UTF8:
482
2
            tfn = &TranscodeUtf8FromUcs2;
483
2
            break;
484
          default:
485
            tfn = &TranscodeFromUcs2;
486
        }
487
2
        break;
488
      default:
489
        // This should not happen because of the SupportedEncoding checks
490
        ABORT();
491
    }
492
493
    result = tfn(env, EncodingName(fromEncoding), EncodingName(toEncoding),
494
10
                 ts_obj_data, ts_obj_length, &status);
495
  } else {
496
2
    status = U_ILLEGAL_ARGUMENT_ERROR;
497
  }
498
499
12
  if (result.IsEmpty())
500
6
    return args.GetReturnValue().Set(status);
501
502
20
  return args.GetReturnValue().Set(result.ToLocalChecked());
503
}
504
505
2
void ICUErrorName(const FunctionCallbackInfo<Value>& args) {
506
2
  Environment* env = Environment::GetCurrent(args);
507
4
  CHECK(args[0]->IsInt32());
508
6
  UErrorCode status = static_cast<UErrorCode>(args[0].As<Int32>()->Value());
509
  args.GetReturnValue().Set(
510
      String::NewFromUtf8(env->isolate(),
511
                          u_errorName(status),
512
6
                          NewStringType::kNormal).ToLocalChecked());
513
2
}
514
515
}  // anonymous namespace
516
517
4249
bool InitializeICUDirectory(const std::string& path) {
518
4249
  UErrorCode status = U_ZERO_ERROR;
519
4249
  if (path.empty()) {
520
#ifdef NODE_HAVE_SMALL_ICU
521
    // install the 'small' data.
522
4247
    udata_setCommonData(&SMALL_ICUDATA_ENTRY_POINT, &status);
523
#else  // !NODE_HAVE_SMALL_ICU
524
    // no small data, so nothing to do.
525
#endif  // !NODE_HAVE_SMALL_ICU
526
  } else {
527
2
    u_setDataDirectory(path.c_str());
528
2
    u_init(&status);
529
  }
530
4249
  return status == U_ZERO_ERROR;
531
}
532
533
382
int32_t ToUnicode(MaybeStackBuffer<char>* buf,
534
                  const char* input,
535
                  size_t length) {
536
382
  UErrorCode status = U_ZERO_ERROR;
537
382
  uint32_t options = UIDNA_NONTRANSITIONAL_TO_UNICODE;
538
382
  UIDNA* uidna = uidna_openUTS46(options, &status);
539
382
  if (U_FAILURE(status))
540
    return -1;
541
382
  UIDNAInfo info = UIDNA_INFO_INITIALIZER;
542
543
  int32_t len = uidna_nameToUnicodeUTF8(uidna,
544
                                        input, length,
545
382
                                        **buf, buf->capacity(),
546
                                        &info,
547
382
                                        &status);
548
549
  // Do not check info.errors like we do with ToASCII since ToUnicode always
550
  // returns a string, despite any possible errors that may have occurred.
551
552
382
  if (status == U_BUFFER_OVERFLOW_ERROR) {
553
    status = U_ZERO_ERROR;
554
    buf->AllocateSufficientStorage(len);
555
    len = uidna_nameToUnicodeUTF8(uidna,
556
                                  input, length,
557
                                  **buf, buf->capacity(),
558
                                  &info,
559
                                  &status);
560
  }
561
562
  // info.errors is ignored as UTS #46 ToUnicode always produces a Unicode
563
  // string, regardless of whether an error occurred.
564
565
382
  if (U_FAILURE(status)) {
566
    len = -1;
567
    buf->SetLength(0);
568
  } else {
569
382
    buf->SetLength(len);
570
  }
571
572
382
  uidna_close(uidna);
573
382
  return len;
574
}
575
576
12442
int32_t ToASCII(MaybeStackBuffer<char>* buf,
577
                const char* input,
578
                size_t length,
579
                enum idna_mode mode) {
580
12442
  UErrorCode status = U_ZERO_ERROR;
581
  uint32_t options =                  // CheckHyphens = false; handled later
582
    UIDNA_CHECK_BIDI |                // CheckBidi = true
583
    UIDNA_CHECK_CONTEXTJ |            // CheckJoiners = true
584
12442
    UIDNA_NONTRANSITIONAL_TO_ASCII;   // Nontransitional_Processing
585
12442
  if (mode == IDNA_STRICT) {
586
    options |= UIDNA_USE_STD3_RULES;  // UseSTD3ASCIIRules = beStrict
587
                                      // VerifyDnsLength = beStrict;
588
                                      //   handled later
589
  }
590
591
12442
  UIDNA* uidna = uidna_openUTS46(options, &status);
592
12442
  if (U_FAILURE(status))
593
    return -1;
594
12442
  UIDNAInfo info = UIDNA_INFO_INITIALIZER;
595
596
  int32_t len = uidna_nameToASCII_UTF8(uidna,
597
                                       input, length,
598
12442
                                       **buf, buf->capacity(),
599
                                       &info,
600
12442
                                       &status);
601
602
12442
  if (status == U_BUFFER_OVERFLOW_ERROR) {
603
2
    status = U_ZERO_ERROR;
604
2
    buf->AllocateSufficientStorage(len);
605
    len = uidna_nameToASCII_UTF8(uidna,
606
                                 input, length,
607
2
                                 **buf, buf->capacity(),
608
                                 &info,
609
2
                                 &status);
610
  }
611
612
  // In UTS #46 which specifies ToASCII, certain error conditions are
613
  // configurable through options, and the WHATWG URL Standard promptly elects
614
  // to disable some of them to accommodate for real-world use cases.
615
  // Unfortunately, ICU4C's IDNA module does not support disabling some of
616
  // these options through `options` above, and thus continues throwing
617
  // unnecessary errors. To counter this situation, we just filter out the
618
  // errors that may have happened afterwards, before deciding whether to
619
  // return an error from this function.
620
621
  // CheckHyphens = false
622
  // (Specified in the current UTS #46 draft rev. 18.)
623
  // Refs:
624
  // - https://github.com/whatwg/url/issues/53
625
  // - https://github.com/whatwg/url/pull/309
626
  // - http://www.unicode.org/review/pri317/
627
  // - http://www.unicode.org/reports/tr46/tr46-18.html
628
  // - https://www.icann.org/news/announcement-2000-01-07-en
629
12442
  info.errors &= ~UIDNA_ERROR_HYPHEN_3_4;
630
12442
  info.errors &= ~UIDNA_ERROR_LEADING_HYPHEN;
631
12442
  info.errors &= ~UIDNA_ERROR_TRAILING_HYPHEN;
632
633
12442
  if (mode != IDNA_STRICT) {
634
    // VerifyDnsLength = beStrict
635
12442
    info.errors &= ~UIDNA_ERROR_EMPTY_LABEL;
636
12442
    info.errors &= ~UIDNA_ERROR_LABEL_TOO_LONG;
637
12442
    info.errors &= ~UIDNA_ERROR_DOMAIN_NAME_TOO_LONG;
638
  }
639
640


12442
  if (U_FAILURE(status) || (mode != IDNA_LENIENT && info.errors != 0)) {
641
78
    len = -1;
642
78
    buf->SetLength(0);
643
  } else {
644
12364
    buf->SetLength(len);
645
  }
646
647
12442
  uidna_close(uidna);
648
12442
  return len;
649
}
650
651
189
static void ToUnicode(const FunctionCallbackInfo<Value>& args) {
652
189
  Environment* env = Environment::GetCurrent(args);
653
189
  CHECK_GE(args.Length(), 1);
654
567
  CHECK(args[0]->IsString());
655
189
  Utf8Value val(env->isolate(), args[0]);
656
657
378
  MaybeStackBuffer<char> buf;
658
189
  int32_t len = ToUnicode(&buf, *val, val.length());
659
660
189
  if (len < 0) {
661
189
    return env->ThrowError("Cannot convert name to Unicode");
662
  }
663
664
  args.GetReturnValue().Set(
665
      String::NewFromUtf8(env->isolate(),
666
189
                          *buf,
667
                          NewStringType::kNormal,
668
756
                          len).ToLocalChecked());
669
}
670
671
9834
static void ToASCII(const FunctionCallbackInfo<Value>& args) {
672
9834
  Environment* env = Environment::GetCurrent(args);
673
9834
  CHECK_GE(args.Length(), 1);
674
29502
  CHECK(args[0]->IsString());
675
9834
  Utf8Value val(env->isolate(), args[0]);
676
  // optional arg
677
29502
  bool lenient = args[1]->BooleanValue(env->isolate());
678
9834
  enum idna_mode mode = lenient ? IDNA_LENIENT : IDNA_DEFAULT;
679
680
19659
  MaybeStackBuffer<char> buf;
681
9834
  int32_t len = ToASCII(&buf, *val, val.length(), mode);
682
683
9834
  if (len < 0) {
684
9843
    return env->ThrowError("Cannot convert name to ASCII");
685
  }
686
687
  args.GetReturnValue().Set(
688
      String::NewFromUtf8(env->isolate(),
689
9825
                          *buf,
690
                          NewStringType::kNormal,
691
39300
                          len).ToLocalChecked());
692
}
693
694
// This is similar to wcwidth except that it takes the current unicode
695
// character properties database into consideration, allowing it to
696
// correctly calculate the column widths of things like emoji's and
697
// newer wide characters. wcwidth, on the other hand, uses a fixed
698
// algorithm that does not take things like emoji into proper
699
// consideration.
700
//
701
// TODO(TimothyGu): Investigate Cc (C0/C1 control codes). Both VTE (used by
702
// GNOME Terminal) and Konsole don't consider them to be zero-width (see refs
703
// below), and when printed in VTE it is Narrow. However GNOME Terminal doesn't
704
// allow it to be input. Linux's PTY terminal prints control characters as
705
// Narrow rhombi.
706
//
707
// TODO(TimothyGu): Investigate Hangul jamo characters. Medial vowels and final
708
// consonants are 0-width when combined with initial consonants; otherwise they
709
// are technically Wide. But many terminals (including Konsole and
710
// VTE/GLib-based) implement all medials and finals as 0-width.
711
//
712
// Refs: https://eev.ee/blog/2015/09/12/dark-corners-of-unicode/#combining-characters-and-character-width
713
// Refs: https://github.com/GNOME/glib/blob/79e4d4c6be/glib/guniprop.c#L388-L420
714
// Refs: https://github.com/KDE/konsole/blob/8c6a5d13c0/src/konsole_wcwidth.cpp#L101-L223
715
131107
static int GetColumnWidth(UChar32 codepoint,
716
                          bool ambiguous_as_full_width = false) {
717
  const auto zero_width_mask = U_GC_CC_MASK |  // C0/C1 control code
718
                               U_GC_CF_MASK |  // Format control character
719
                               U_GC_ME_MASK |  // Enclosing mark
720
131107
                               U_GC_MN_MASK;   // Nonspacing mark
721

262269
  if (codepoint != 0x00AD &&  // SOFT HYPHEN is Cf but not zero-width
722
262157
      ((U_MASK(u_charType(codepoint)) & zero_width_mask) ||
723
131051
       u_hasBinaryProperty(codepoint, UCHAR_EMOJI_MODIFIER))) {
724
56
    return 0;
725
  }
726
727
  // UCHAR_EAST_ASIAN_WIDTH is the Unicode property that identifies a
728
  // codepoint as being full width, wide, ambiguous, neutral, narrow,
729
  // or halfwidth.
730
131051
  const int eaw = u_getIntPropertyValue(codepoint, UCHAR_EAST_ASIAN_WIDTH);
731

131051
  switch (eaw) {
732
    case U_EA_FULLWIDTH:
733
    case U_EA_WIDE:
734
124
      return 2;
735
    case U_EA_AMBIGUOUS:
736
      // See: http://www.unicode.org/reports/tr11/#Ambiguous for details
737
4
      if (ambiguous_as_full_width) {
738
1
        return 2;
739
      }
740
      // If ambiguous_as_full_width is false:
741
      // Fall through
742
    case U_EA_NEUTRAL:
743
60
      if (u_hasBinaryProperty(codepoint, UCHAR_EMOJI_PRESENTATION)) {
744
        return 2;
745
      }
746
      // Fall through
747
    case U_EA_HALFWIDTH:
748
    case U_EA_NARROW:
749
    default:
750
130926
      return 1;
751
  }
752
}
753
754
// Returns the column width for the given String.
755
130734
static void GetStringWidth(const FunctionCallbackInfo<Value>& args) {
756
130734
  Environment* env = Environment::GetCurrent(args);
757
130734
  if (args.Length() < 1)
758
130638
    return;
759
760
261468
  bool ambiguous_as_full_width = args[1]->IsTrue();
761
261468
  bool expand_emoji_sequence = args[2]->IsTrue();
762
763
261468
  if (args[0]->IsNumber()) {
764
    uint32_t val;
765
522552
    if (!args[0]->Uint32Value(env->context()).To(&val)) return;
766
391914
    args.GetReturnValue().Set(GetColumnWidth(val, ambiguous_as_full_width));
767
130638
    return;
768
  }
769
770
96
  TwoByteValue value(env->isolate(), args[0]);
771
  // reinterpret_cast is required by windows to compile
772
96
  UChar* str = reinterpret_cast<UChar*>(*value);
773
  static_assert(sizeof(*str) == sizeof(**value),
774
                "sizeof(*str) == sizeof(**value)");
775
96
  UChar32 c = 0;
776
  UChar32 p;
777
96
  size_t n = 0;
778
96
  uint32_t width = 0;
779
780
664
  while (n < value.length()) {
781
472
    p = c;
782


472
    U16_NEXT(str, n, value.length(), c);
783
    // Don't count individual emoji codepoints that occur within an
784
    // emoji sequence. This is not necessarily foolproof. Some
785
    // environments display emoji sequences in the appropriate
786
    // condensed form (as a single emoji glyph), other environments
787
    // may not understand an emoji sequence and will display each
788
    // individual emoji separately. When this happens, the width
789
    // calculated will be off, and there's no reliable way of knowing
790
    // in advance if a particular sequence is going to be supported.
791
    // The expand_emoji_sequence option allows the caller to skip this
792
    // check and count each code within an emoji sequence separately.
793

1409
    if (!expand_emoji_sequence &&
794

943
        n > 0 && p == 0x200d &&  // 0x200d == ZWJ (zero width joiner)
795
3
        (u_hasBinaryProperty(c, UCHAR_EMOJI_PRESENTATION) ||
796
         u_hasBinaryProperty(c, UCHAR_EMOJI_MODIFIER))) {
797
3
      continue;
798
    }
799
469
    width += GetColumnWidth(c, ambiguous_as_full_width);
800
  }
801
192
  args.GetReturnValue().Set(width);
802
}
803
804
4409
void Initialize(Local<Object> target,
805
                Local<Value> unused,
806
                Local<Context> context,
807
                void* priv) {
808
4409
  Environment* env = Environment::GetCurrent(context);
809
4409
  env->SetMethod(target, "toUnicode", ToUnicode);
810
4409
  env->SetMethod(target, "toASCII", ToASCII);
811
4409
  env->SetMethod(target, "getStringWidth", GetStringWidth);
812
813
  // One-shot converters
814
4409
  env->SetMethod(target, "icuErrName", ICUErrorName);
815
4409
  env->SetMethod(target, "transcode", Transcode);
816
817
  // ConverterObject
818
4409
  env->SetMethod(target, "getConverter", ConverterObject::Create);
819
4409
  env->SetMethod(target, "decode", ConverterObject::Decode);
820
4409
  env->SetMethod(target, "hasConverter", ConverterObject::Has);
821
4409
}
822
823
}  // namespace i18n
824
}  // namespace node
825
826
4292
NODE_MODULE_CONTEXT_AWARE_INTERNAL(icu, node::i18n::Initialize)
827
828
#endif  // NODE_HAVE_I18N_SUPPORT