1 /*
2  * Copyright (C) 2015 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_SOURCE_H
18 #define _ANDROID_SOURCE_H
19 
20 #include <optional>
21 #include <ostream>
22 #include <string>
23 
24 #include "android-base/stringprintf.h"
25 #include "androidfw/StringPiece.h"
26 
27 namespace android {
28 
29 // Represents a file on disk. Used for logging and showing errors.
30 struct Source {
31   std::string path;
32   std::optional<size_t> line;
33   std::optional<std::string> archive;
34 
35   Source() = default;
36 
SourceSource37   inline Source(android::StringPiece path) : path(path) {  // NOLINT(implicit)
38   }
39 
SourceSource40   inline Source(android::StringPiece path, android::StringPiece archive)
41       : path(path), archive(archive) {
42   }
43 
SourceSource44   inline Source(android::StringPiece path, size_t line) : path(path), line(line) {
45   }
46 
WithLineSource47   inline Source WithLine(size_t line) const {
48     return Source(path, line);
49   }
50 
to_stringSource51   std::string to_string() const {
52     std::string s = path;
53     if (archive) {
54       s = ::android::base::StringPrintf("%s@%s", archive.value().c_str(), s.c_str());
55     }
56     if (line) {
57       s = ::android::base::StringPrintf("%s:%zd", s.c_str(), line.value());
58     }
59     return s;
60   }
61 };
62 
63 //
64 // Implementations
65 //
66 
67 inline ::std::ostream& operator<<(::std::ostream& out, const Source& source) {
68   return out << source.to_string();
69 }
70 
71 inline bool operator==(const Source& lhs, const Source& rhs) {
72   return lhs.path == rhs.path && lhs.line == rhs.line;
73 }
74 
75 inline bool operator<(const Source& lhs, const Source& rhs) {
76   int cmp = lhs.path.compare(rhs.path);
77   if (cmp < 0) return true;
78   if (cmp > 0) return false;
79   if (lhs.line) {
80     if (rhs.line) {
81       return lhs.line.value() < rhs.line.value();
82     }
83     return false;
84   }
85   return bool(rhs.line);
86 }
87 
88 }  // namespace android
89 
90 #endif  // _ANDROID_SOURCE_H
91