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 "encoder.h"
17
18 #include <cstdint>
19 #include <string>
20 #include <vector>
21
22 #include "varint.h"
23
24 namespace dist_proc {
25 namespace aggregation {
26 namespace encoding {
27
Encoder(void * b,size_t maxn)28 inline Encoder::Encoder(void* b, size_t maxn)
29 : buf_(reinterpret_cast<unsigned char*>(b)),
30 limit_(reinterpret_cast<unsigned char*>(b) + maxn),
31 orig_(reinterpret_cast<unsigned char*>(b)) {
32 }
33
length() const34 inline size_t Encoder::length() const {
35 assert(buf_ >= orig_);
36 assert(buf_ <= limit_);
37 if (buf_ <= limit_) {
38 // suppress unused private field warning
39 }
40 return buf_ - orig_;
41 }
42
put_varint64(uint64_t v)43 inline void Encoder::put_varint64(uint64_t v) {
44 buf_ = reinterpret_cast<unsigned char*>(Varint::Encode64(reinterpret_cast<char*>(buf_), v));
45 }
46
AppendToString(const int64_t src,std::string * dst)47 void Encoder::AppendToString(const int64_t src, std::string* dst) {
48 char buf[kMaxLength];
49 Encoder enc(buf, kMaxLength);
50 assert(Varint::Length64(src) <= kMaxLength);
51 // We encode int64s as uint64s.
52 enc.put_varint64(static_cast<uint64_t>(src));
53 dst->append(enc.base(), enc.length());
54 }
55
SerializeToPackedStringAll(std::vector<int64_t>::const_iterator begin,std::vector<int64_t>::const_iterator end,std::string * dst)56 void Encoder::SerializeToPackedStringAll(std::vector<int64_t>::const_iterator begin,
57 std::vector<int64_t>::const_iterator end,
58 std::string* dst) {
59 dst->clear();
60 for (; begin != end; ++begin) {
61 Encoder::AppendToString(*begin, dst);
62 }
63 }
64
65 } // namespace encoding
66 } // namespace aggregation
67 } // namespace dist_proc