/*
 * 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/.
 */
#include "Array.h"
#include "Heap.h"
#include "Zone.h"
#include "Heap-inl.h"

using namespace ke;

ArrayMap *
ArrayMap::New(Zone *zone, Handle<Type> type, Handle<ArrayMap> contained)
{
    Local<Map> obj(zone, zone->allocateMap(MapKind_Array, sizeof(ArrayMap), MapKind_MetaArray));
    if (!obj)
        return NULL;

    Local<ArrayMap> map(zone, ArrayMap::cast(obj));
    map->type_ = type;
    map->contained_ = contained;
    return map;
}

static inline size_t
SizeFor(Type *type, unsigned elements)
{
    if (type->levels() > 1)
        return sizeof(Array) + elements * sizeof(ke::Object *);
    if (type->contained()->isInt32())
        return sizeof(Array) + elements * sizeof(int);
    if (type->contained()->primitive() == PrimitiveType_Char)
        return sizeof(Array) + elements * sizeof(char);
    assert(type->contained()->isFloat());
    return elements * sizeof(float);
}

Array *
Array::New(Zone *zone, Handle<ArrayMap> map, uint32 elements, Heap::Tenure tenure)
{
    size_t elementBytes = SizeFor(map->type(), elements);
    size_t bytes = sizeof(Array) + elementBytes;
    Local<Array> array(zone, Array::cast(zone->allocate(map, bytes, tenure)));
    if (!array)
        return NULL;

    array->nelements_ = elements;
    array->elements_ = (Array *)array + 1;
    memset(array->elements_, 0, elementBytes);
    return array;
}

Array *
Array::NewExternal(Zone *zone, Handle<ArrayMap> map, uint32 nelements, void *buffer,
                   Heap::Tenure tenure)
{
    Local<Array> array(zone, Array::cast(zone->allocate(map, sizeof(Array), tenure)));
    if (!array)
        return NULL;

    array->nelements_ = nelements;
    array->elements_ = buffer;
    return array;
}
