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 #pragma once 18 19 #include <iostream> 20 21 namespace android { 22 namespace lshal { 23 24 template<typename S> 25 class NullableOStream { 26 public: NullableOStream(S & os)27 explicit NullableOStream(S &os) : mOs(&os) {} NullableOStream(S * os)28 explicit NullableOStream(S *os) : mOs(os) {} 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 } buf()56 S& buf() const { 57 return *mOs; 58 } 59 operator bool() const { // NOLINT(google-explicit-constructor) 60 return mOs != nullptr; 61 } 62 private: 63 template<typename> 64 friend class NullableOStream; 65 66 S *mOs = nullptr; 67 }; 68 69 } // namespace lshal 70 } // namespace android 71