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 #pragma once 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 28 class Encoder { 29 public: 30 // Initialize encoder to encode into "buf" 31 Encoder(void* buf, size_t maxn); 32 static void AppendToString(const int64_t src, std::string* dst); 33 34 static void SerializeToPackedStringAll(std::vector<int64_t>::const_iterator begin, 35 std::vector<int64_t>::const_iterator end, 36 std::string* dst); 37 38 private: 39 // Max number of bytes needed to encode 64 bits as a varint (= ceil(64 / 7)). 40 static const int8_t kMaxLength = 10; 41 // buf_ points into the orig_ buffer, just past the last encoded byte. 42 unsigned char* buf_ = nullptr; 43 // limits_ points just past the last allocated byte in the orig_ buffer. 44 unsigned char* limit_ = nullptr; 45 // orig_ points to the start of the encoding buffer, whether or not the 46 // Encoder owns it. 47 unsigned char* orig_ = nullptr; 48 49 void put_varint64(uint64_t v); 50 51 // Return number of bytes encoded so far. 52 size_t length() const; 53 54 // Return ptr to start of encoded data. base()55 const char* base() const { 56 return reinterpret_cast<const char*>(orig_); 57 } 58 }; 59 60 } // namespace encoding 61 } // namespace aggregation 62 } // namespace dist_proc 63