• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef FRAMEWORK_NATIVE_CMDS_LSHAL_NULLABLE_O_STREAM_H_
18 #define FRAMEWORK_NATIVE_CMDS_LSHAL_NULLABLE_O_STREAM_H_
19 
20 #include <iostream>
21 
22 namespace android {
23 namespace lshal {
24 
25 template<typename S>
26 class NullableOStream {
27 public:
NullableOStream(S & os)28     explicit NullableOStream(S &os) : mOs(&os) {}
NullableOStream(S * os)29     explicit NullableOStream(S *os) : mOs(os) {}
30     NullableOStream &operator=(S &os) {
31         mOs = &os;
32         return *this;
33     }
34     NullableOStream &operator=(S *os) {
35         mOs = os;
36         return *this;
37     }
38     template<typename Other>
39     NullableOStream &operator=(const NullableOStream<Other> &other) {
40         mOs = other.mOs;
41         return *this;
42     }
43 
44     const NullableOStream &operator<<(std::ostream& (*pf)(std::ostream&)) const {
45         if (mOs) {
46             (*mOs) << pf;
47         }
48         return *this;
49     }
50     template<typename T>
51     const NullableOStream &operator<<(const T &rhs) const {
52         if (mOs) {
53             (*mOs) << rhs;
54         }
55         return *this;
56     }
buf()57     S& buf() const {
58         return *mOs;
59     }
60     operator bool() const { // NOLINT(google-explicit-constructor)
61         return mOs != nullptr;
62     }
63 private:
64     template<typename>
65     friend class NullableOStream;
66 
67     S *mOs = nullptr;
68 };
69 
70 }  // namespace lshal
71 }  // namespace android
72 
73 #endif  // FRAMEWORK_NATIVE_CMDS_LSHAL_NULLABLE_O_STREAM_H_
74