jitcraft/Array.cpp
author David Anderson <dvander@alliedmods.net>
Sat Jun 30 19:38:53 2012 -0700 (2012-06-30)
changeset 12 75e385f68b7e
child 13 627b6b94e774
permissions -rw-r--r--
Refactored Array, Code to be Objects. Removed Object tagging.
     1 /*
     2  * Copyright (C) 2012 David Anderson
     3  *
     4  * This file is part of JITCraft.
     5  *
     6  * JITCraft is free software: you can redistribute it and/or modify it under
     7  * the terms of the GNU General Public License as published by the Free
     8  * Software Foundation, either version 3 of the License, or (at your option)
     9  * any later version.
    10  * 
    11  * Foobar is distributed in the hope that it will be useful, but WITHOUT ANY
    12  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
    13  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
    14  *
    15  * You should have received a copy of the GNU General Public License along with
    16  * JITCraft. If not, see http://www.gnu.org/licenses/.
    17  */
    18 #include "Array.h"
    19 #include "Heap.h"
    20 #include "Zone.h"
    21 #include "Heap-inl.h"
    22 
    23 using namespace jc;
    24 
    25 ArrayMap *
    26 ArrayMap::New(Zone *zone, Type *type, ArrayMap *contained)
    27 {
    28     // :TODO: use Local
    29     Map *obj = zone->allocateMap(MapKind_Array, sizeof(ArrayMap), MapKind_MetaArray);
    30     if (!obj)
    31         return NULL;
    32 
    33     ArrayMap *map = ArrayMap::cast(obj);
    34     map->init(type, contained);
    35     return map;
    36 }
    37 
    38 static inline size_t
    39 SizeFor(Type *type, unsigned elements)
    40 {
    41     if (type->levels() > 1)
    42         return sizeof(Array) + elements * sizeof(jc::Object *);
    43     if (type->contained()->isInt())
    44         return sizeof(Array) + elements * sizeof(int);
    45     assert(type->contained()->isFloat());
    46     return sizeof(Array) + elements * sizeof(float);
    47 }
    48 
    49 void
    50 Array::init(uint32 nelements)
    51 {
    52     WRITE_FIELD(nelements, nelements);
    53     WRITE_FIELD(elements, VoidPtr(this + 1));
    54 }
    55 
    56 Array *
    57 Array::New(Zone *zone, ArrayMap *map, uint32 elements, Heap::Tenure tenure)
    58 {
    59     // :TODO: handles
    60     size_t bytes = SizeFor(map->type(), elements);
    61     Object *obj = zone->allocate(map, bytes, tenure);
    62     if (!obj)
    63         return NULL;
    64 
    65     Array *array = Array::cast(obj);
    66     array->init(elements);
    67     return Array::cast(obj);
    68 }