Yifan Hong | 4b86549 | 2017-02-28 19:38:24 -0800 | [diff] [blame] | 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 | |
Steven Moreland | 0b8e387 | 2019-06-25 08:54:34 -0700 | [diff] [blame] | 17 | #pragma once |
Yifan Hong | 4b86549 | 2017-02-28 19:38:24 -0800 | [diff] [blame] | 18 | |
| 19 | #include <iostream> |
| 20 | |
| 21 | namespace android { |
| 22 | namespace lshal { |
| 23 | |
| 24 | template<typename S> |
| 25 | class NullableOStream { |
| 26 | public: |
Chih-Hung Hsieh | 45e31c7 | 2018-12-20 15:47:01 -0800 | [diff] [blame] | 27 | explicit NullableOStream(S &os) : mOs(&os) {} |
| 28 | explicit NullableOStream(S *os) : mOs(os) {} |
Yifan Hong | 4b86549 | 2017-02-28 19:38:24 -0800 | [diff] [blame] | 29 | 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 Hsieh | 45e31c7 | 2018-12-20 15:47:01 -0800 | [diff] [blame] | 59 | operator bool() const { // NOLINT(google-explicit-constructor) |
Yifan Hong | 4b86549 | 2017-02-28 19:38:24 -0800 | [diff] [blame] | 60 | return mOs != nullptr; |
| 61 | } |
Yifan Hong | 6b13e50 | 2024-02-01 16:54:36 -0800 | [diff] [blame] | 62 | void flush() { |
| 63 | if (mOs) { |
| 64 | mOs->flush(); |
| 65 | } |
| 66 | } |
Yifan Hong | 4b86549 | 2017-02-28 19:38:24 -0800 | [diff] [blame] | 67 | private: |
| 68 | template<typename> |
| 69 | friend class NullableOStream; |
| 70 | |
| 71 | S *mOs = nullptr; |
| 72 | }; |
| 73 | |
| 74 | } // namespace lshal |
| 75 | } // namespace android |