PR2957
[oota-llvm.git] / include / llvm / Support / Streams.h
1 //===- llvm/Support/Streams.h - Wrappers for iostreams ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a wrapper for the STL I/O streams.  It prevents the need
11 // to include <iostream> in a file just to get I/O.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_SUPPORT_STREAMS_H
16 #define LLVM_SUPPORT_STREAMS_H
17
18 #include <iosfwd>
19
20 namespace llvm {
21
22   /// FlushStream - Function called by BaseStream to flush an ostream.
23   void FlushStream(std::ostream &S);
24
25   /// BaseStream - Acts like the STL streams. It's a wrapper for the std::cerr,
26   /// std::cout, std::cin, etc. streams. However, it doesn't require #including
27   /// @verbatim <iostream> @endverbatm in every file (doing so increases static
28   /// c'tors & d'tors in the object code).
29   ///
30   template <typename StreamTy>
31   class BaseStream {
32     StreamTy *Stream;
33   public:
34     BaseStream() : Stream(0) {}
35     BaseStream(StreamTy &S) : Stream(&S) {}
36     BaseStream(StreamTy *S) : Stream(S) {}
37
38     StreamTy *stream() const { return Stream; }
39
40     inline BaseStream &operator << (std::ios_base &(*Func)(std::ios_base&)) {
41       if (Stream) *Stream << Func;
42       return *this;
43     }
44
45     inline BaseStream &operator << (StreamTy &(*Func)(StreamTy&)) {
46       if (Stream) *Stream << Func;
47       return *this;
48     }
49
50     void flush() {
51       if (Stream)
52         FlushStream(*Stream);
53     }
54
55     template <typename Ty>
56     BaseStream &operator << (const Ty &Thing) {
57       if (Stream) *Stream << Thing;
58       return *this;
59     }
60
61     template <typename Ty>
62     BaseStream &operator >> (Ty &Thing) {
63       if (Stream) *Stream >> Thing;
64       return *this;
65     }
66
67     template <typename Ty>
68     BaseStream &write(const Ty &A, unsigned N) {
69       if (Stream) Stream->write(A, N);
70       return *this;
71     }
72
73     operator StreamTy* () { return Stream; }
74
75     bool operator == (const StreamTy &S) { return &S == Stream; }
76     bool operator != (const StreamTy &S) { return !(*this == S); }
77     bool operator == (const BaseStream &S) { return S.Stream == Stream; }
78     bool operator != (const BaseStream &S) { return !(*this == S); }
79   };
80
81   typedef BaseStream<std::ostream> OStream;
82   typedef BaseStream<std::istream> IStream;
83   typedef BaseStream<std::stringstream> StringStream;
84
85   extern OStream cout;
86   extern OStream cerr;
87   extern IStream cin;
88
89 } // End llvm namespace
90
91 #endif