1 /*
2  * Copyright (C) 2018 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 ANDROID_APEXD_STRING_LOG_H_
18 #define ANDROID_APEXD_STRING_LOG_H_
19 
20 // Simple helper class to create strings similar to LOGs.
21 // Usage sample:
22 //   std::string msg = StringLog() << "Hello " << std::hex << 1234;
23 
24 #include <cstring>
25 #include <iomanip>
26 #include <iostream>
27 #include <sstream>
28 
29 #include <errno.h>
30 
31 template <typename T>
32 class BaseStringLog {
33  public:
BaseStringLog()34   BaseStringLog() {}
35 
36   // Pipe in values.
37   template <class U>
38   T& operator<<(const U& t) {
39     os_stream << t;
40     return static_cast<T&>(*this);
41   }
42 
43   // Pipe in modifiers.
44   T& operator<<(std::ostream& (*f)(std::ostream&)) {
45     os_stream << f;
46     return static_cast<T&>(*this);
47   }
48 
49   // Get the current string.
50   // NOLINTNEXTLINE(google-explicit-constructor)
string()51   operator std::string() const { return os_stream.str(); }
52 
53  private:
54   std::ostringstream os_stream;
55 };
56 
57 class StringLog : public BaseStringLog<StringLog> {};
58 
59 class PStringLog : public BaseStringLog<PStringLog> {
60  public:
PStringLog()61   PStringLog() : errno_(errno) {}
62 
63   // Get the current string.
64   // NOLINTNEXTLINE(google-explicit-constructor)
string()65   operator std::string() const {
66     return (BaseStringLog::operator std::string())
67         .append(": ")
68         .append(strerror(errno_));
69   }
70 
71  private:
72   int errno_;
73 };
74 
75 #endif  // ANDROID_APEXD_STRING_LOG_H_
76