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_UTIL_H
18#define AAPT_UTIL_H
19
20#include <functional>
21#include <memory>
22#include <ostream>
23#include <string>
24#include <vector>
25
26#include "androidfw/ResourceTypes.h"
27#include "androidfw/StringPiece.h"
28#include "utils/ByteOrder.h"
29
30#include "util/BigBuffer.h"
31#include "util/Maybe.h"
32
33#ifdef _WIN32
34// TODO(adamlesinski): remove once http://b/32447322 is resolved.
35// utils/ByteOrder.h includes winsock2.h on WIN32,
36// which will pull in the ERROR definition. This conflicts
37// with android-base/logging.h, which takes care of undefining
38// ERROR, but it gets included too early (before winsock2.h).
39#ifdef ERROR
40#undef ERROR
41#endif
42#endif
43
44namespace aapt {
45namespace util {
46
47template <typename T>
48struct Range {
49  T start;
50  T end;
51};
52
53std::vector<std::string> Split(const android::StringPiece& str, char sep);
54std::vector<std::string> SplitAndLowercase(const android::StringPiece& str, char sep);
55
56// Returns true if the string starts with prefix.
57bool StartsWith(const android::StringPiece& str, const android::StringPiece& prefix);
58
59// Returns true if the string ends with suffix.
60bool EndsWith(const android::StringPiece& str, const android::StringPiece& suffix);
61
62// Creates a new StringPiece that points to a substring of the original string without leading
63// whitespace.
64android::StringPiece TrimLeadingWhitespace(const android::StringPiece& str);
65
66// Creates a new StringPiece that points to a substring of the original string without trailing
67// whitespace.
68android::StringPiece TrimTrailingWhitespace(const android::StringPiece& str);
69
70// Creates a new StringPiece that points to a substring of the original string without leading or
71// trailing whitespace.
72android::StringPiece TrimWhitespace(const android::StringPiece& str);
73
74// Tests that the string is a valid Java class name.
75bool IsJavaClassName(const android::StringPiece& str);
76
77// Tests that the string is a valid Java package name.
78bool IsJavaPackageName(const android::StringPiece& str);
79
80// Tests that the string is a valid Android package name. More strict than a Java package name.
81// - First character of each component (separated by '.') must be an ASCII letter.
82// - Subsequent characters of a component can be ASCII alphanumeric or an underscore.
83// - Package must contain at least two components, unless it is 'android'.
84bool IsAndroidPackageName(const android::StringPiece& str);
85
86// Tests that the string is a valid Android split name.
87// - First character of each component (separated by '.') must be an ASCII letter.
88// - Subsequent characters of a component can be ASCII alphanumeric or an underscore.
89bool IsAndroidSplitName(const android::StringPiece& str);
90
91// Converts the class name to a fully qualified class name from the given
92// `package`. Ex:
93//
94// asdf         --> package.asdf
95// .asdf        --> package.asdf
96// .a.b         --> package.a.b
97// asdf.adsf    --> asdf.adsf
98Maybe<std::string> GetFullyQualifiedClassName(const android::StringPiece& package,
99                                              const android::StringPiece& class_name);
100
101template <typename T>
102typename std::enable_if<std::is_arithmetic<T>::value, int>::type compare(const T& a, const T& b) {
103  if (a < b) {
104    return -1;
105  } else if (a > b) {
106    return 1;
107  }
108  return 0;
109}
110
111// Makes a std::unique_ptr<> with the template parameter inferred by the compiler.
112// This will be present in C++14 and can be removed then.
113template <typename T, class... Args>
114std::unique_ptr<T> make_unique(Args&&... args) {
115  return std::unique_ptr<T>(new T{std::forward<Args>(args)...});
116}
117
118// Writes a set of items to the std::ostream, joining the times with the provided separator.
119template <typename Container>
120::std::function<::std::ostream&(::std::ostream&)> Joiner(const Container& container,
121                                                         const char* sep) {
122  using std::begin;
123  using std::end;
124  const auto begin_iter = begin(container);
125  const auto end_iter = end(container);
126  return [begin_iter, end_iter, sep](::std::ostream& out) -> ::std::ostream& {
127    for (auto iter = begin_iter; iter != end_iter; ++iter) {
128      if (iter != begin_iter) {
129        out << sep;
130      }
131      out << *iter;
132    }
133    return out;
134  };
135}
136
137// Helper method to extract a UTF-16 string from a StringPool. If the string is stored as UTF-8,
138// the conversion to UTF-16 happens within ResStringPool.
139android::StringPiece16 GetString16(const android::ResStringPool& pool, size_t idx);
140
141// Helper method to extract a UTF-8 string from a StringPool. If the string is stored as UTF-16,
142// the conversion from UTF-16 to UTF-8 does not happen in ResStringPool and is done by this method,
143// which maintains no state or cache. This means we must return an std::string copy.
144std::string GetString(const android::ResStringPool& pool, size_t idx);
145
146// Checks that the Java string format contains no non-positional arguments (arguments without
147// explicitly specifying an index) when there are more than one argument. This is an error
148// because translations may rearrange the order of the arguments in the string, which will
149// break the string interpolation.
150bool VerifyJavaStringFormat(const android::StringPiece& str);
151
152bool AppendStyledString(const android::StringPiece& input, bool preserve_spaces,
153                        std::string* out_str, std::string* out_error);
154
155class StringBuilder {
156 public:
157  StringBuilder() = default;
158
159  StringBuilder& Append(const android::StringPiece& str);
160  const std::string& ToString() const;
161  const std::string& Error() const;
162  bool IsEmpty() const;
163
164  // When building StyledStrings, we need UTF-16 indices into the string,
165  // which is what the Java layer expects when dealing with java
166  // String.charAt().
167  size_t Utf16Len() const;
168
169  explicit operator bool() const;
170
171 private:
172  std::string str_;
173  size_t utf16_len_ = 0;
174  bool quote_ = false;
175  bool trailing_space_ = false;
176  bool last_char_was_escape_ = false;
177  std::string error_;
178};
179
180inline const std::string& StringBuilder::ToString() const {
181  return str_;
182}
183
184inline const std::string& StringBuilder::Error() const {
185  return error_;
186}
187
188inline bool StringBuilder::IsEmpty() const {
189  return str_.empty();
190}
191
192inline size_t StringBuilder::Utf16Len() const {
193  return utf16_len_;
194}
195
196inline StringBuilder::operator bool() const {
197  return error_.empty();
198}
199
200// Converts a UTF8 string to a UTF16 string.
201std::u16string Utf8ToUtf16(const android::StringPiece& utf8);
202std::string Utf16ToUtf8(const android::StringPiece16& utf16);
203
204// Writes the entire BigBuffer to the output stream.
205bool WriteAll(std::ostream& out, const BigBuffer& buffer);
206
207// Copies the entire BigBuffer into a single buffer.
208std::unique_ptr<uint8_t[]> Copy(const BigBuffer& buffer);
209
210// A Tokenizer implemented as an iterable collection. It does not allocate any memory on the heap
211// nor use standard containers.
212class Tokenizer {
213 public:
214  class iterator {
215   public:
216    using reference = android::StringPiece&;
217    using value_type = android::StringPiece;
218    using difference_type = size_t;
219    using pointer = android::StringPiece*;
220    using iterator_category = std::forward_iterator_tag;
221
222    iterator(const iterator&) = default;
223    iterator& operator=(const iterator&) = default;
224
225    iterator& operator++();
226
227    android::StringPiece operator*() { return token_; }
228    bool operator==(const iterator& rhs) const;
229    bool operator!=(const iterator& rhs) const;
230
231   private:
232    friend class Tokenizer;
233
234    iterator(const android::StringPiece& s, char sep, const android::StringPiece& tok, bool end);
235
236    android::StringPiece str_;
237    char separator_;
238    android::StringPiece token_;
239    bool end_;
240  };
241
242  Tokenizer(const android::StringPiece& str, char sep);
243
244  iterator begin() const {
245    return begin_;
246  }
247
248  iterator end() const {
249    return end_;
250  }
251
252 private:
253  const iterator begin_;
254  const iterator end_;
255};
256
257inline Tokenizer Tokenize(const android::StringPiece& str, char sep) {
258  return Tokenizer(str, sep);
259}
260
261inline uint16_t HostToDevice16(uint16_t value) {
262  return htods(value);
263}
264
265inline uint32_t HostToDevice32(uint32_t value) {
266  return htodl(value);
267}
268
269inline uint16_t DeviceToHost16(uint16_t value) {
270  return dtohs(value);
271}
272
273inline uint32_t DeviceToHost32(uint32_t value) {
274  return dtohl(value);
275}
276
277// Given a path like: res/xml-sw600dp/foo.xml
278//
279// Extracts "res/xml-sw600dp/" into outPrefix.
280// Extracts "foo" into outEntry.
281// Extracts ".xml" into outSuffix.
282//
283// Returns true if successful.
284bool ExtractResFilePathParts(const android::StringPiece& path, android::StringPiece* out_prefix,
285                             android::StringPiece* out_entry, android::StringPiece* out_suffix);
286
287}  // namespace util
288
289// Stream operator for functions. Calls the function with the stream as an argument.
290// In the aapt namespace for lookup.
291inline ::std::ostream& operator<<(::std::ostream& out,
292                                  const ::std::function<::std::ostream&(::std::ostream&)>& f) {
293  return f(out);
294}
295
296}  // namespace aapt
297
298#endif  // AAPT_UTIL_H
299