xref: /third_party/node/deps/v8/src/base/strings.h (revision 1cb0ef41)
1// Copyright 2021 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef V8_BASE_STRINGS_H_
6#define V8_BASE_STRINGS_H_
7
8#include "src/base/base-export.h"
9#include "src/base/macros.h"
10#include "src/base/vector.h"
11
12namespace v8 {
13namespace base {
14
15// Latin1/UTF-16 constants
16// Code-point values in Unicode 4.0 are 21 bits wide.
17// Code units in UTF-16 are 16 bits wide.
18using uc16 = uint16_t;
19using uc32 = uint32_t;
20constexpr int kUC16Size = sizeof(uc16);
21
22V8_BASE_EXPORT int PRINTF_FORMAT(2, 0)
23    VSNPrintF(Vector<char> str, const char* format, va_list args);
24
25// Safe formatting print. Ensures that str is always null-terminated.
26// Returns the number of chars written, or -1 if output was truncated.
27V8_BASE_EXPORT int PRINTF_FORMAT(2, 3)
28    SNPrintF(Vector<char> str, const char* format, ...);
29
30V8_BASE_EXPORT void StrNCpy(base::Vector<char> dest, const char* src, size_t n);
31
32// Returns the value (0 .. 15) of a hexadecimal character c.
33// If c is not a legal hexadecimal character, returns a value < 0.
34inline int HexValue(uc32 c) {
35  c -= '0';
36  if (static_cast<unsigned>(c) <= 9) return c;
37  c = (c | 0x20) - ('a' - '0');  // detect 0x11..0x16 and 0x31..0x36.
38  if (static_cast<unsigned>(c) <= 5) return c + 10;
39  return -1;
40}
41
42inline char HexCharOfValue(int value) {
43  DCHECK(0 <= value && value <= 16);
44  if (value < 10) return value + '0';
45  return value - 10 + 'A';
46}
47
48}  // namespace base
49}  // namespace v8
50
51#endif  // V8_BASE_STRINGS_H_
52