ostreams.cc 2.29 KB
Newer Older
1 2 3 4
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/ostreams.h"
6
#include "src/objects.h"
7

8
#if V8_OS_WIN
9
#if _MSC_VER < 1900
10 11
#define snprintf sprintf_s
#endif
12
#endif
13 14 15 16

namespace v8 {
namespace internal {

17
OFStreamBase::OFStreamBase(FILE* f) : f_(f) {}
18 19


20
OFStreamBase::~OFStreamBase() {}
21 22


svenpanne's avatar
svenpanne committed
23
int OFStreamBase::sync() {
24 25 26
  std::fflush(f_);
  return 0;
}
27 28


29 30
OFStreamBase::int_type OFStreamBase::overflow(int_type c) {
  return (c != EOF) ? std::fputc(c, f_) : c;
31 32 33
}


svenpanne's avatar
svenpanne committed
34 35 36 37 38 39 40
std::streamsize OFStreamBase::xsputn(const char* s, std::streamsize n) {
  return static_cast<std::streamsize>(
      std::fwrite(s, 1, static_cast<size_t>(n), f_));
}


OFStream::OFStream(FILE* f) : std::ostream(nullptr), buf_(f) {
41
  DCHECK_NOT_NULL(f);
svenpanne's avatar
svenpanne committed
42
  rdbuf(&buf_);
43
}
44 45


46
OFStream::~OFStream() {}
47 48


49
namespace {
50

51
// Locale-independent predicates.
52 53 54
bool IsPrint(uint16_t c) { return 0x20 <= c && c <= 0x7e; }
bool IsSpace(uint16_t c) { return (0x9 <= c && c <= 0xd) || c == 0x20; }
bool IsOK(uint16_t c) { return (IsPrint(c) || IsSpace(c)) && c != '\\'; }
55 56


57
std::ostream& PrintUC16(std::ostream& os, uint16_t c, bool (*pred)(uint16_t)) {
58
  char buf[10];
59 60
  const char* format = pred(c) ? "%c" : (c <= 0xff) ? "\\x%02x" : "\\u%04x";
  snprintf(buf, sizeof(buf), format, c);
61 62 63
  return os << buf;
}

64 65 66 67 68 69 70 71 72 73

std::ostream& PrintUC32(std::ostream& os, int32_t c, bool (*pred)(uint16_t)) {
  if (c <= String::kMaxUtf16CodeUnit) {
    return PrintUC16(os, static_cast<uint16_t>(c), pred);
  }
  char buf[13];
  snprintf(buf, sizeof(buf), "\\u{%06x}", c);
  return os << buf;
}

74
}  // namespace
75

76 77

std::ostream& operator<<(std::ostream& os, const AsReversiblyEscapedUC16& c) {
78 79 80 81
  return PrintUC16(os, c.value, IsOK);
}


danno's avatar
danno committed
82 83 84
std::ostream& operator<<(std::ostream& os, const AsEscapedUC16ForJSON& c) {
  if (c.value == '\n') return os << "\\n";
  if (c.value == '\r') return os << "\\r";
85
  if (c.value == '\t') return os << "\\t";
danno's avatar
danno committed
86 87 88 89 90
  if (c.value == '\"') return os << "\\\"";
  return PrintUC16(os, c.value, IsOK);
}


91
std::ostream& operator<<(std::ostream& os, const AsUC16& c) {
92
  return PrintUC16(os, c.value, IsPrint);
93
}
94

95 96 97 98 99

std::ostream& operator<<(std::ostream& os, const AsUC32& c) {
  return PrintUC32(os, c.value, IsPrint);
}

100 101
}  // namespace internal
}  // namespace v8