xref: /aosp_15_r20/external/icing/icing/util/encode-util.h (revision 8b6cd535a057e39b3b86660c4aa06c99747c2136)
1 // Copyright (C) 2023 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef ICING_UTIL_ENCODE_UTIL_H_
16 #define ICING_UTIL_ENCODE_UTIL_H_
17 
18 #include <cstdint>
19 #include <string>
20 #include <string_view>
21 
22 namespace icing {
23 namespace lib {
24 
25 namespace encode_util {
26 
27 // Converts an unsigned 64-bit integer to a C string that doesn't contain 0-byte
28 // since C string uses 0-byte as terminator. This increases the size of the
29 // encoded_str from 8-bytes to 10-bytes at worst.
30 //
31 // Note that it is compatible with unsigned 32-bit integers, i.e. casting an
32 // uint32_t to uint64_t with the same value and encoding it by this method will
33 // get the same string.
34 std::string EncodeIntToCString(uint64_t value);
35 
36 // Converts a C string (encoded from EncodeIntToCString()) to an unsigned 64-bit
37 // integer.
38 uint64_t DecodeIntFromCString(std::string_view encoded_str);
39 
40 // Converts the given string which may contains 0-byte to a C string.
41 //
42 // The output C string that does not contain 0-byte since C string uses 0-byte
43 // as terminator.
44 // This will increase the size of the encoded_str.
45 // new_length = ceil(old_length / 7.0 * 8.0)
46 // Eg1: This increases the size from 32-bytes of sha-256 hash to 37-bytes C
47 // string.
48 // Eg2: This increases the size from 1-byte string to 2-bytes C string.
49 // Eg3: This increases the size from 2-byte string to 3-bytes C string.
50 std::string EncodeStringToCString(const std::string& input);
51 
52 }  // namespace encode_util
53 
54 }  // namespace lib
55 }  // namespace icing
56 
57 #endif  // ICING_UTIL_ENCODE_UTIL_H_
58