1 /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ 2 // vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4: 3 #ident "$Id$" 4 /*====== 5 This file is part of TokuDB 6 7 8 Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved. 9 10 TokuDBis is free software: you can redistribute it and/or modify 11 it under the terms of the GNU General Public License, version 2, 12 as published by the Free Software Foundation. 13 14 TokuDB is distributed in the hope that it will be useful, 15 but WITHOUT ANY WARRANTY; without even the implied warranty of 16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 GNU General Public License for more details. 18 19 You should have received a copy of the GNU General Public License 20 along with TokuDB. If not, see <http://www.gnu.org/licenses/>. 21 22 ======= */ 23 24 #ident "Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved." 25 26 #ifndef _TOKUDB_VLQ_H 27 #define _TOKUDB_VLQ_H 28 29 namespace tokudb { 30 31 // Variable length encode an unsigned integer into a buffer with limit s. 32 // Returns the number of bytes used to encode n in the buffer. 33 // Returns 0 if the buffer is too small. vlq_encode_ui(T n,void * p,size_t s)34 template <class T> size_t vlq_encode_ui(T n, void *p, size_t s) { 35 unsigned char *pp = (unsigned char *)p; 36 size_t i = 0; 37 while (n >= 128) { 38 if (i >= s) 39 return 0; // not enough space 40 pp[i++] = n%128; 41 n = n/128; 42 } 43 if (i >= s) 44 return 0; // not enough space 45 pp[i++] = 128+n; 46 return i; 47 } 48 49 // Variable length decode an unsigned integer from a buffer with limit s. 50 // Returns the number of bytes used to decode the buffer. 51 // Returns 0 if the buffer is too small. vlq_decode_ui(T * np,void * p,size_t s)52 template <class T> size_t vlq_decode_ui(T *np, void *p, size_t s) { 53 unsigned char *pp = (unsigned char *)p; 54 T n = 0; 55 size_t i = 0; 56 while (1) { 57 if (i >= s) 58 return 0; // not a full decode 59 T m = pp[i]; 60 n |= (m & 127) << (7*i); 61 i++; 62 if ((m & 128) != 0) 63 break; 64 } 65 *np = n; 66 return i; 67 } 68 } 69 70 #endif 71