1// Copyright 2014 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#include "src/ostreams.h"
6#include "src/objects.h"
7
8#if V8_OS_WIN
9#if _MSC_VER < 1900
10#define snprintf sprintf_s
11#endif
12#endif
13
14namespace v8 {
15namespace internal {
16
17OFStreamBase::OFStreamBase(FILE* f) : f_(f) {}
18
19
20OFStreamBase::~OFStreamBase() {}
21
22
23int OFStreamBase::sync() {
24  std::fflush(f_);
25  return 0;
26}
27
28
29OFStreamBase::int_type OFStreamBase::overflow(int_type c) {
30  return (c != EOF) ? std::fputc(c, f_) : c;
31}
32
33
34std::streamsize OFStreamBase::xsputn(const char* s, std::streamsize n) {
35  return static_cast<std::streamsize>(
36      std::fwrite(s, 1, static_cast<size_t>(n), f_));
37}
38
39
40OFStream::OFStream(FILE* f) : std::ostream(nullptr), buf_(f) {
41  DCHECK_NOT_NULL(f);
42  rdbuf(&buf_);
43}
44
45
46OFStream::~OFStream() {}
47
48
49namespace {
50
51// Locale-independent predicates.
52bool IsPrint(uint16_t c) { return 0x20 <= c && c <= 0x7e; }
53bool IsSpace(uint16_t c) { return (0x9 <= c && c <= 0xd) || c == 0x20; }
54bool IsOK(uint16_t c) { return (IsPrint(c) || IsSpace(c)) && c != '\\'; }
55
56
57std::ostream& PrintUC16(std::ostream& os, uint16_t c, bool (*pred)(uint16_t)) {
58  char buf[10];
59  const char* format = pred(c) ? "%c" : (c <= 0xff) ? "\\x%02x" : "\\u%04x";
60  snprintf(buf, sizeof(buf), format, c);
61  return os << buf;
62}
63
64
65std::ostream& PrintUC32(std::ostream& os, int32_t c, bool (*pred)(uint16_t)) {
66  if (c <= String::kMaxUtf16CodeUnit) {
67    return PrintUC16(os, static_cast<uint16_t>(c), pred);
68  }
69  char buf[13];
70  snprintf(buf, sizeof(buf), "\\u{%06x}", c);
71  return os << buf;
72}
73
74}  // namespace
75
76
77std::ostream& operator<<(std::ostream& os, const AsReversiblyEscapedUC16& c) {
78  return PrintUC16(os, c.value, IsOK);
79}
80
81
82std::ostream& operator<<(std::ostream& os, const AsEscapedUC16ForJSON& c) {
83  if (c.value == '\n') return os << "\\n";
84  if (c.value == '\r') return os << "\\r";
85  if (c.value == '\t') return os << "\\t";
86  if (c.value == '\"') return os << "\\\"";
87  return PrintUC16(os, c.value, IsOK);
88}
89
90
91std::ostream& operator<<(std::ostream& os, const AsUC16& c) {
92  return PrintUC16(os, c.value, IsPrint);
93}
94
95
96std::ostream& operator<<(std::ostream& os, const AsUC32& c) {
97  return PrintUC32(os, c.value, IsPrint);
98}
99
100std::ostream& operator<<(std::ostream& os, const AsHex& hex) {
101  char buf[20];
102  snprintf(buf, sizeof(buf), "%.*" PRIx64, hex.min_width, hex.value);
103  return os << buf;
104}
105
106}  // namespace internal
107}  // namespace v8
108