• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 AAPT_SOURCE_H
18 #define AAPT_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 aapt {
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(const android::StringPiece& path) : path(path.to_string()) {  // NOLINT(implicit)
38   }
39 
SourceSource40   inline Source(const android::StringPiece& path, const android::StringPiece& archive)
41       : path(path.to_string()), archive(archive.to_string()) {}
42 
SourceSource43   inline Source(const android::StringPiece& path, size_t line)
44       : path(path.to_string()), line(line) {}
45 
WithLineSource46   inline Source WithLine(size_t line) const {
47     return Source(path, line);
48   }
49 
to_stringSource50   std::string to_string() const {
51     std::string s = path;
52     if (archive) {
53       s = ::android::base::StringPrintf("%s@%s", archive.value().c_str(), s.c_str());
54     }
55     if (line) {
56       s = ::android::base::StringPrintf("%s:%zd", s.c_str(), line.value());
57     }
58     return s;
59   }
60 };
61 
62 //
63 // Implementations
64 //
65 
66 inline ::std::ostream& operator<<(::std::ostream& out, const Source& source) {
67   return out << source.to_string();
68 }
69 
70 inline bool operator==(const Source& lhs, const Source& rhs) {
71   return lhs.path == rhs.path && lhs.line == rhs.line;
72 }
73 
74 inline bool operator<(const Source& lhs, const Source& rhs) {
75   int cmp = lhs.path.compare(rhs.path);
76   if (cmp < 0) return true;
77   if (cmp > 0) return false;
78   if (lhs.line) {
79     if (rhs.line) {
80       return lhs.line.value() < rhs.line.value();
81     }
82     return false;
83   }
84   return bool(rhs.line);
85 }
86 
87 }  // namespace aapt
88 
89 #endif  // AAPT_SOURCE_H
90