1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/src/Array.cpp Tue Jul 24 23:53:34 2012 -0700
1.3 @@ -0,0 +1,77 @@
1.4 +/*
1.5 + * Copyright (C) 2012 David Anderson
1.6 + *
1.7 + * This file is part of JITCraft.
1.8 + *
1.9 + * JITCraft is free software: you can redistribute it and/or modify it under
1.10 + * the terms of the GNU General Public License as published by the Free
1.11 + * Software Foundation, either version 3 of the License, or (at your option)
1.12 + * any later version.
1.13 + *
1.14 + * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
1.15 + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1.16 + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
1.17 + *
1.18 + * You should have received a copy of the GNU General Public License along with
1.19 + * JITCraft. If not, see http://www.gnu.org/licenses/.
1.20 + */
1.21 +#include "Array.h"
1.22 +#include "Heap.h"
1.23 +#include "Zone.h"
1.24 +#include "Heap-inl.h"
1.25 +
1.26 +using namespace ke;
1.27 +
1.28 +ArrayMap *
1.29 +ArrayMap::New(Zone *zone, Handle<Type> type, Handle<ArrayMap> contained)
1.30 +{
1.31 + Local<Map> obj(zone, zone->allocateMap(MapKind_Array, sizeof(ArrayMap), MapKind_MetaArray));
1.32 + if (!obj)
1.33 + return NULL;
1.34 +
1.35 + Local<ArrayMap> map(zone, ArrayMap::cast(obj));
1.36 + map->type_ = type;
1.37 + map->contained_ = contained;
1.38 + return map;
1.39 +}
1.40 +
1.41 +static inline size_t
1.42 +SizeFor(Type *type, unsigned elements)
1.43 +{
1.44 + if (type->levels() > 1)
1.45 + return sizeof(Array) + elements * sizeof(ke::Object *);
1.46 + if (type->contained()->isInt32())
1.47 + return sizeof(Array) + elements * sizeof(int);
1.48 + if (type->contained()->primitive() == PrimitiveType_Char)
1.49 + return sizeof(Array) + elements * sizeof(char);
1.50 + assert(type->contained()->isFloat());
1.51 + return elements * sizeof(float);
1.52 +}
1.53 +
1.54 +Array *
1.55 +Array::New(Zone *zone, Handle<ArrayMap> map, uint32 elements, Heap::Tenure tenure)
1.56 +{
1.57 + size_t elementBytes = SizeFor(map->type(), elements);
1.58 + size_t bytes = sizeof(Array) + elementBytes;
1.59 + Local<Array> array(zone, Array::cast(zone->allocate(map, bytes, tenure)));
1.60 + if (!array)
1.61 + return NULL;
1.62 +
1.63 + array->nelements_ = elements;
1.64 + array->elements_ = (Array *)array + 1;
1.65 + memset(array->elements_, 0, elementBytes);
1.66 + return array;
1.67 +}
1.68 +
1.69 +Array *
1.70 +Array::NewExternal(Zone *zone, Handle<ArrayMap> map, uint32 nelements, void *buffer,
1.71 + Heap::Tenure tenure)
1.72 +{
1.73 + Local<Array> array(zone, Array::cast(zone->allocate(map, sizeof(Array), tenure)));
1.74 + if (!array)
1.75 + return NULL;
1.76 +
1.77 + array->nelements_ = nelements;
1.78 + array->elements_ = buffer;
1.79 + return array;
1.80 +}