blob: 7cffcf81930aa6388174a2906739a03a3e1e7d3d [file] [log] [blame]
Yifan Hong4b865492017-02-28 19:38:24 -08001/*
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
Steven Moreland0b8e3872019-06-25 08:54:34 -070017#pragma once
Yifan Hong4b865492017-02-28 19:38:24 -080018
19#include <iostream>
20
21namespace android {
22namespace lshal {
23
24template<typename S>
25class NullableOStream {
26public:
Chih-Hung Hsieh45e31c72018-12-20 15:47:01 -080027 explicit NullableOStream(S &os) : mOs(&os) {}
28 explicit NullableOStream(S *os) : mOs(os) {}
Yifan Hong4b865492017-02-28 19:38:24 -080029 NullableOStream &operator=(S &os) {
30 mOs = &os;
31 return *this;
32 }
33 NullableOStream &operator=(S *os) {
34 mOs = os;
35 return *this;
36 }
37 template<typename Other>
38 NullableOStream &operator=(const NullableOStream<Other> &other) {
39 mOs = other.mOs;
40 return *this;
41 }
42
43 const NullableOStream &operator<<(std::ostream& (*pf)(std::ostream&)) const {
44 if (mOs) {
45 (*mOs) << pf;
46 }
47 return *this;
48 }
49 template<typename T>
50 const NullableOStream &operator<<(const T &rhs) const {
51 if (mOs) {
52 (*mOs) << rhs;
53 }
54 return *this;
55 }
56 S& buf() const {
57 return *mOs;
58 }
Chih-Hung Hsieh45e31c72018-12-20 15:47:01 -080059 operator bool() const { // NOLINT(google-explicit-constructor)
Yifan Hong4b865492017-02-28 19:38:24 -080060 return mOs != nullptr;
61 }
62private:
63 template<typename>
64 friend class NullableOStream;
65
66 S *mOs = nullptr;
67};
68
69} // namespace lshal
70} // namespace android