/* vim: set ts=4 sw=4 tw=99 et:
 *
 * Copyright (C) 2012 David Anderson
 *
 * This file is part of JITCraft.
 *
 * JITCraft is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 * 
 * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * JITCraft. If not, see http://www.gnu.org/licenses/.
 */
#ifndef _include_jc_compact_buffer_h_
#define _include_jc_compact_buffer_h_

#include "AllocatorPolicies.h"
#include "Utility.h"
#include "Vector.h"

namespace ke {

class CompactBufferReader
{
    const uint8 *pos_;
    const uint8 *end_;

  public:
    CompactBufferReader(const uint8 *start, const uint8 *end)
      : pos_(start),
        end_(end)
    {
    }

    uint8 readUint8() {
        assert(pos_ < end_);
        return *pos_++;
    }

    uint32 readUint32() {
        uint32 value = 0;
        uint32 shift = 0;

        uint8 byte;
        do {
            byte = readUint8();
            value |= (byte >> 1) << shift;
            shift += 7;
        } while (byte & 1);

        assert(shift < 32);
        return value;
    }

    bool done() const {
        return pos_ == end_;
    }
};

class CompactBufferWriter
{
    Vector<uint8, ZoneAllocatorPolicy> buffer_;
    bool enoughMemory_;

  public:
    CompactBufferWriter()
      : enoughMemory_(true)
    {
    }

    void writeUint8(unsigned value) {
        enoughMemory_ &= buffer_.append(value);
    }
    void writeUint32(unsigned value) {
        do {
            writeUint8(((value & 0x7F) << 1) | (value > 0x7F));
            value >>= 7;
        } while (value);
    }

    uint8 *buffer() const {
        return buffer_.buffer();
    }
    size_t length() const {
        return buffer_.length();
    }

    bool oom() const {
        return !enoughMemory_;
    }
};

}

#endif // _include_jc_compact_buffer_h_
