• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2021 Google LLC
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 #include "varint.h"
17 
18 #include <cstdint>
19 
Encode32(char * sptr,uint32_t v)20 char* Varint::Encode32(char* sptr, uint32_t v) {
21     return Encode32Inline(sptr, v);
22 }
23 
Encode64(char * sptr,uint64_t v)24 char* Varint::Encode64(char* sptr, uint64_t v) {
25     if (v < (1u << 28)) {
26         return Varint::Encode32(sptr, v);
27     } else {
28         // Operate on characters as unsigneds
29         unsigned char* ptr = reinterpret_cast<unsigned char*>(sptr);
30         // Rather than computing four subresults and or'ing each with 0x80,
31         // we can do two ors now.  (Doing one now wouldn't work.)
32         const uint32_t x32 = v | (1 << 7) | (1 << 21);
33         const uint32_t y32 = v | (1 << 14) | (1 << 28);
34         *(ptr++) = x32;
35         *(ptr++) = y32 >> 7;
36         *(ptr++) = x32 >> 14;
37         *(ptr++) = y32 >> 21;
38         if (v < (1ull << 35)) {
39             *(ptr++) = v >> 28;
40             return reinterpret_cast<char*>(ptr);
41         } else {
42             *(ptr++) = (v >> 28) | (1 << 7);
43             return Varint::Encode32(reinterpret_cast<char*>(ptr), v >> 35);
44         }
45     }
46 }
47