• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "icing/util/encode-util.h"
16 
17 #include <cstdint>
18 #include <string>
19 #include <string_view>
20 
21 namespace icing {
22 namespace lib {
23 
24 namespace encode_util {
25 
EncodeIntToCString(uint64_t value)26 std::string EncodeIntToCString(uint64_t value) {
27   std::string encoded_str;
28   // Encode it in base128 and add 1 to make sure that there is no 0-byte. This
29   // increases the size of the encoded_str from 8-bytes to 10-bytes at worst.
30   do {
31     encoded_str.push_back((value & 0x7F) + 1);
32     value >>= 7;
33   } while (value);
34   return encoded_str;
35 }
36 
DecodeIntFromCString(std::string_view encoded_str)37 uint64_t DecodeIntFromCString(std::string_view encoded_str) {
38   uint64_t value = 0;
39   for (int i = encoded_str.length() - 1; i >= 0; --i) {
40     value <<= 7;
41     char c = encoded_str[i] - 1;
42     value |= (c & 0x7F);
43   }
44   return value;
45 }
46 
47 }  // namespace encode_util
48 
49 }  // namespace lib
50 }  // namespace icing
51