1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/src/CompactBuffer.h Tue Jul 24 23:53:34 2012 -0700
1.3 @@ -0,0 +1,100 @@
1.4 +/* vim: set ts=4 sw=4 tw=99 et:
1.5 + *
1.6 + * Copyright (C) 2012 David Anderson
1.7 + *
1.8 + * This file is part of JITCraft.
1.9 + *
1.10 + * JITCraft is free software: you can redistribute it and/or modify it under
1.11 + * the terms of the GNU General Public License as published by the Free
1.12 + * Software Foundation, either version 3 of the License, or (at your option)
1.13 + * any later version.
1.14 + *
1.15 + * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
1.16 + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1.17 + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
1.18 + *
1.19 + * You should have received a copy of the GNU General Public License along with
1.20 + * JITCraft. If not, see http://www.gnu.org/licenses/.
1.21 + */
1.22 +#ifndef _include_jc_compact_buffer_h_
1.23 +#define _include_jc_compact_buffer_h_
1.24 +
1.25 +#include "AllocatorPolicies.h"
1.26 +#include "Utility.h"
1.27 +#include "Vector.h"
1.28 +
1.29 +namespace ke {
1.30 +
1.31 +class CompactBufferReader
1.32 +{
1.33 + const uint8 *pos_;
1.34 + const uint8 *end_;
1.35 +
1.36 + public:
1.37 + CompactBufferReader(const uint8 *start, const uint8 *end)
1.38 + : pos_(start),
1.39 + end_(end)
1.40 + {
1.41 + }
1.42 +
1.43 + uint8 readUint8() {
1.44 + assert(pos_ < end_);
1.45 + return *pos_++;
1.46 + }
1.47 +
1.48 + uint32 readUint32() {
1.49 + uint32 value = 0;
1.50 + uint32 shift = 0;
1.51 +
1.52 + uint8 byte;
1.53 + do {
1.54 + byte = readUint8();
1.55 + value |= (byte >> 1) << shift;
1.56 + shift += 7;
1.57 + } while (byte & 1);
1.58 +
1.59 + assert(shift < 32);
1.60 + return value;
1.61 + }
1.62 +
1.63 + bool done() const {
1.64 + return pos_ == end_;
1.65 + }
1.66 +};
1.67 +
1.68 +class CompactBufferWriter
1.69 +{
1.70 + Vector<uint8, ZoneAllocatorPolicy> buffer_;
1.71 + bool enoughMemory_;
1.72 +
1.73 + public:
1.74 + CompactBufferWriter()
1.75 + : enoughMemory_(true)
1.76 + {
1.77 + }
1.78 +
1.79 + void writeUint8(unsigned value) {
1.80 + enoughMemory_ &= buffer_.append(value);
1.81 + }
1.82 + void writeUint32(unsigned value) {
1.83 + do {
1.84 + writeUint8(((value & 0x7F) << 1) | (value > 0x7F));
1.85 + value >>= 7;
1.86 + } while (value);
1.87 + }
1.88 +
1.89 + uint8 *buffer() const {
1.90 + return buffer_.buffer();
1.91 + }
1.92 + size_t length() const {
1.93 + return buffer_.length();
1.94 + }
1.95 +
1.96 + bool oom() const {
1.97 + return !enoughMemory_;
1.98 + }
1.99 +};
1.100 +
1.101 +}
1.102 +
1.103 +#endif // _include_jc_compact_buffer_h_