• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
7 #if V8_OS_WIN
8 #if _MSC_VER < 1900
9 #define snprintf sprintf_s
10 #endif
11 #endif
12 
13 namespace v8 {
14 namespace internal {
15 
OFStreamBase(FILE * f)16 OFStreamBase::OFStreamBase(FILE* f) : f_(f) {}
17 
18 
~OFStreamBase()19 OFStreamBase::~OFStreamBase() {}
20 
21 
sync()22 int OFStreamBase::sync() {
23   std::fflush(f_);
24   return 0;
25 }
26 
27 
overflow(int_type c)28 OFStreamBase::int_type OFStreamBase::overflow(int_type c) {
29   return (c != EOF) ? std::fputc(c, f_) : c;
30 }
31 
32 
xsputn(const char * s,std::streamsize n)33 std::streamsize OFStreamBase::xsputn(const char* s, std::streamsize n) {
34   return static_cast<std::streamsize>(
35       std::fwrite(s, 1, static_cast<size_t>(n), f_));
36 }
37 
38 
OFStream(FILE * f)39 OFStream::OFStream(FILE* f) : std::ostream(nullptr), buf_(f) {
40   DCHECK_NOT_NULL(f);
41   rdbuf(&buf_);
42 }
43 
44 
~OFStream()45 OFStream::~OFStream() {}
46 
47 
48 namespace {
49 
50 // Locale-independent predicates.
IsPrint(uint16_t c)51 bool IsPrint(uint16_t c) { return 0x20 <= c && c <= 0x7e; }
IsSpace(uint16_t c)52 bool IsSpace(uint16_t c) { return (0x9 <= c && c <= 0xd) || c == 0x20; }
IsOK(uint16_t c)53 bool IsOK(uint16_t c) { return (IsPrint(c) || IsSpace(c)) && c != '\\'; }
54 
55 
PrintUC16(std::ostream & os,uint16_t c,bool (* pred)(uint16_t))56 std::ostream& PrintUC16(std::ostream& os, uint16_t c, bool (*pred)(uint16_t)) {
57   char buf[10];
58   const char* format = pred(c) ? "%c" : (c <= 0xff) ? "\\x%02x" : "\\u%04x";
59   snprintf(buf, sizeof(buf), format, c);
60   return os << buf;
61 }
62 
63 }  // namespace
64 
65 
operator <<(std::ostream & os,const AsReversiblyEscapedUC16 & c)66 std::ostream& operator<<(std::ostream& os, const AsReversiblyEscapedUC16& c) {
67   return PrintUC16(os, c.value, IsOK);
68 }
69 
70 
operator <<(std::ostream & os,const AsEscapedUC16ForJSON & c)71 std::ostream& operator<<(std::ostream& os, const AsEscapedUC16ForJSON& c) {
72   if (c.value == '\n') return os << "\\n";
73   if (c.value == '\r') return os << "\\r";
74   if (c.value == '\t') return os << "\\t";
75   if (c.value == '\"') return os << "\\\"";
76   return PrintUC16(os, c.value, IsOK);
77 }
78 
79 
operator <<(std::ostream & os,const AsUC16 & c)80 std::ostream& operator<<(std::ostream& os, const AsUC16& c) {
81   return PrintUC16(os, c.value, IsPrint);
82 }
83 
84 }  // namespace internal
85 }  // namespace v8
86