/* vim: set ts=4 sw=4 tw=99 et:
 *
 * Copyright (C) 2012 David Anderson
 *
 * This file is part of SourcePawn.
 *
 * SourcePawn 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.
 * 
 * SourcePawn 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
 * SourcePawn. If not, see http://www.gnu.org/licenses/.
 */
#ifndef _include_jitcraft_fixedarray_h_
#define _include_jitcraft_fixedarray_h_

#include "Heap.h"

namespace ke {

// A fixed-length array that contains Object * slots.
class FixedArray : public Object
{
    uint32 length_;

  private:
    Object **vec() {
        return reinterpret_cast<Object **>(this + 1);
    }

  public:
    static FixedArray *New(Zone *zone, unsigned length, Heap::Tenure tenure);

    unsigned length() {
        return length_;
    }
    Object *at(size_t i) {
        assert(i < length());
        return vec()[i];
    }
    void set(Zone *zone, size_t i, Object *obj) {
        assert(i < length());
        write(zone, &vec()[i], obj);
    }
    size_t objSize() {
        return SizeFor(length());
    }

    static inline size_t SizeFor(unsigned length) {
        return sizeof(FixedArray) + sizeof(Object *) * length;
    }

    static inline FixedArray *cast(Object *obj) {
        assert(!obj || obj->is(MapKind_FixedArray));
        return reinterpret_cast<FixedArray *>(obj);
    }
};

// A fixed-length array containing raw bytes.
class ByteArray : public Object
{
    uint32 length_;

  public:
    static ByteArray *New(Zone *zone, unsigned length, Heap::Tenure tenure = Heap::Tenure_Default);
    static ByteArray *New(Zone *zone, Handle<Map> map, unsigned length, Heap::Tenure tenure = Heap::Tenure_Default);

    unsigned length() {
        return length_;
    }
    Address raw() {
        return Address(this) + offsetToElements();
    }
    size_t objSize() {
        return SizeFor(length());
    }

    static inline size_t offsetToElements() {
        return sizeof(ByteArray);
    }

    static inline size_t SizeFor(unsigned length) {
        return sizeof(ByteArray) + sizeof(uint8) * length;
    }

    static inline ByteArray *cast(Object *obj) {
        assert(!obj || obj->is(MapKind_ByteArray));
        return reinterpret_cast<ByteArray *>(obj);
    }
};

}

#endif // _include_jitcraft_fixedarray_h_
