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