/*
Copyright (C) 2001-2008, The Perl Foundation.
$Id: /mirror/trunk/src/pmc/resizablebooleanarray.pmc 31999 2008-10-15T04:41:32.358777Z cotto  $

=head1 NAME

src/pmc/resizablebooleanarray.pmc - resizable array for booleans only

=head1 DESCRIPTION

The C<ResizableBooleanArray PMC> implements an array of resizable size, which
stores booleans.  It uses the C<Boolean PMC> for all conversions.  The
C<ResizableBooleanArray PMC> extends the C<FixedBooleanArray PMC>.

=head2 Functions

=over 4

=cut

*/

#include "parrot/parrot.h"


#define BITS_PER_CHAR 8
/* MIN_ALLOC is 8 * BITS_PER_CHAR */
#define MIN_ALLOC 64

/* Round a given size in bits to the nearest allocation unit, then convert it
 * to bytes. */
#define ROUND_BYTES(size) (((size) / MIN_ALLOC + 1) * MIN_ALLOC / BITS_PER_CHAR)
/* Convert a size in bits to a size in bytes */
#define BITS_TO_BYTES(size) ((size) / BITS_PER_CHAR)

pmclass ResizableBooleanArray extends FixedBooleanArray need_ext provides array {


/*

=back

=head2 Methods

=over 4

=item C<INTVAL get_integer_keyed_int(INTVAL key)>

Returns the integer value of the element at index C<key>.

=cut

*/

    VTABLE INTVAL get_integer_keyed_int(INTVAL key) {
        INTVAL offsetkey;

        /* Try to make negative index into a real index */
        if (key < 0) {
            key = SELF.elements() + key;

            /* If it's still negative, we have a problem */
            if (key < 0)
                Parrot_ex_throw_from_c_args(interp, NULL, EXCEPTION_OUT_OF_BOUNDS,
                    "ResizableBooleanArray: index out of bounds!");
        }

        /* Check if key is greater than allocated size */
        offsetkey = key + PMC_int_val2(SELF);

        if (offsetkey >= PMC_int_val(SELF))
            return 0;

        return SUPER(offsetkey);
    }

/*

=item C<void set_integer_keyed_int(INTVAL key, INTVAL value)>

Sets the integer value of the element at index C<key> to C<value>.

=cut

*/

    VTABLE void set_integer_keyed_int(INTVAL key, INTVAL value) {
        INTVAL offsetkey;

        /* Try to make negative index into a real index */
        if (key < 0) {
            key = SELF.elements() + key;

            /* If it's still negative, we have a problem */
            if (key < 0)
                Parrot_ex_throw_from_c_args(interp, NULL, EXCEPTION_OUT_OF_BOUNDS,
                    "ResizableBooleanArray: index out of bounds!");
        }

        /* Check if key is greater than allocated size */
        offsetkey = key + PMC_int_val2(SELF);

        if (offsetkey >= PMC_int_val(SELF))
            SELF.set_integer_native(key+1);

        SUPER(offsetkey, value);
    }

/*

=item C<void set_integer_native(INTVAL size)>

Resizes the array to C<size> elements.

=cut

*/

    VTABLE void set_integer_native(INTVAL size) {
        /* Size respects any existing head position offset from unshift */
        size_t newsize = size + PMC_int_val2(SELF);
        size_t oldsize = PMC_int_val(SELF);

        size_t new_bytesize, old_bytesize;

        /* We are already at the requested size. Yay */
        if (newsize == oldsize)
            return;

        if (size < 0)
            Parrot_ex_throw_from_c_args(interp, NULL, EXCEPTION_OUT_OF_BOUNDS,
                "ResizableBooleanArray: Can't resize!");

        /* now set the new size, in bits */
        PMC_int_val(SELF) = newsize;

        /* convert sizes to bytes */
        new_bytesize  = ROUND_BYTES(newsize);
        old_bytesize  = ROUND_BYTES(oldsize);

        /* Nothing allocated yet */
        if (!PMC_data(SELF))
            PMC_data(SELF) = mem_sys_allocate_zeroed(new_bytesize);

        /* The size is different, and doesn't fit within the current
         * allocation */
        else if (new_bytesize != old_bytesize) {
            Parrot_UInt1 * old_store = PMC_data_typed(SELF, Parrot_UInt1 *);
            Parrot_UInt1 * new_store =
                (Parrot_UInt1 *)mem_sys_allocate_zeroed(newsize);
            size_t         copy_size =
                new_bytesize < old_bytesize ? new_bytesize : old_bytesize;

            /* Replace old array with new array, and free old array */
            PMC_data(SELF) = mem_sys_memmove(new_store, old_store, copy_size);
            mem_sys_free(old_store);
        }
    }

/*

=item C<void push_integer(INTVAL size)>

Extends the array by adding an element of value C<value> to the end.

=cut

*/

    VTABLE void push_integer(INTVAL value) {
        const INTVAL size = PMC_int_val(SELF) - PMC_int_val2(SELF);
        SELF.set_integer_native(size + 1);
        SELF.set_integer_keyed_int(size, value);
    }

/*

=item C<void pop_integer(INTVAL size)>

Removes and returns the last element.

=cut

*/

    VTABLE INTVAL pop_integer() {
        INTVAL size, value;

        if (SELF.elements() < 1)
            Parrot_ex_throw_from_c_args(interp, NULL, EXCEPTION_OUT_OF_BOUNDS,
                "ResizableBooleanArray: Can't pop from an empty array!");

        size  = PMC_int_val(SELF) - PMC_int_val2(SELF);
        value = SELF.get_integer_keyed_int(size - 1);
        SELF.set_integer_native(size - 1);

        return value;
    }

/*

=item C<void unshift_integer(INTVAL size)>

Extends the array by adding an element of value C<value> to the
beginning.

=cut

*/

    VTABLE void unshift_integer(INTVAL value) {
        /* If the current head position offset is 0, size this thing up by one
         * allocation unit */
        if (PMC_int_val2(SELF) <= 0) {
            Parrot_UInt1 * const sdOld = PMC_data_typed(SELF, Parrot_UInt1 *);

            /* Allocate an extra allocation unit of space in new array */
            size_t oldmemsize, newmemsize;
            Parrot_UInt1 *sdNew = NULL;
            newmemsize          = ROUND_BYTES(PMC_int_val(SELF) + MIN_ALLOC);
            sdNew               =
                (Parrot_UInt1 *)mem_sys_allocate_zeroed(newmemsize);

            /* Copy contents of old array to new array, moving the head
             * position forward by one allocation unit (in bytes). */
            oldmemsize = ROUND_BYTES(PMC_int_val(SELF));
            mem_sys_memmove(sdNew + (BITS_TO_BYTES(MIN_ALLOC)), sdOld, oldmemsize);

            /* Replace old array with new array, and free old array */
            PMC_data(SELF) = sdNew;
            mem_sys_free(sdOld);

            /* Added one allocation unit to the head position offset */
            PMC_int_val2(SELF) += MIN_ALLOC;
            PMC_int_val(SELF)  += MIN_ALLOC;

        }

        /* Move the head position */
        PMC_int_val2(SELF)--;

        /* Assign the new value as the first item */
        SELF.set_integer_keyed_int(0, value);
    }

/*

=item C<void shift_integer(INTVAL size)>

Removes and returns the first element.

=cut

*/

    VTABLE INTVAL shift_integer() {
        INTVAL value;

        if (SELF.elements() < 1)
            Parrot_ex_throw_from_c_args(interp, NULL, EXCEPTION_OUT_OF_BOUNDS,
                "ResizableBooleanArray: Can't shift from an empty array!");

        /* Get head value */
        value = SELF.get_integer_keyed_int(0);

        /* Move the head position */
        PMC_int_val2(SELF)++;

        /* If the head position offset is greater than our allocation unit
         * size, size this thing down */
        if (PMC_int_val2(SELF) >= MIN_ALLOC) {
            /* Allocate one allocation unit less of space in new array */
            Parrot_UInt1 *sdNew      = NULL;
            Parrot_UInt1 *sdOld      = NULL;
            size_t        newmemsize = ROUND_BYTES(PMC_int_val(SELF)
                                            - MIN_ALLOC);
            sdNew                    =
                (Parrot_UInt1 *)mem_sys_allocate_zeroed(newmemsize);

            /* Copy contents of old array to new array, move the head position
             * offset back by one allocation unit (in bytes) */
            sdOld = PMC_data_typed(SELF, Parrot_UInt1 *);
            mem_sys_memmove(sdNew, sdOld + (BITS_TO_BYTES(MIN_ALLOC)), newmemsize);

            /* Replace old array with new array, and free old array */
            PMC_data(SELF) = sdNew;
            mem_sys_free(sdOld);

            /* Removed one allocation unit from the head position offset */
            PMC_int_val2(SELF) -= MIN_ALLOC;
            PMC_int_val(SELF)  -= MIN_ALLOC;

        }

        return value;
    }

/*

=item C<INTVAL elements()>

=cut

*/

    VTABLE INTVAL elements() {
        return PMC_int_val(SELF) - PMC_int_val2(SELF);
    }

/*

=item C<INTVAL get_integer()>

Returns the number of elements in the array.

=cut

*/

    VTABLE INTVAL get_integer() {
        return SELF.elements();
    }

/*

=item C<PMC *clone()>

Returns a copy of the array.

=cut

*/

    VTABLE PMC *clone() {
        PMC * const dest      = pmc_new(INTERP, SELF->vtable->base_type);
        size_t      dest_size = PMC_int_val(SELF);

        PMC_int_val(dest)     = dest_size;
        PMC_int_val2(dest)    = PMC_int_val2(SELF);

        if (PMC_data(SELF)) {
            size_t dest_size_in_bits = dest_size / BITS_PER_CHAR + 1;
            PMC_data(dest) = mem_sys_allocate(dest_size_in_bits);
            mem_sys_memcopy(PMC_data(dest), PMC_data(SELF), dest_size_in_bits);
        }
        else
            PMC_data(dest) = NULL;

        PObj_active_destroy_SET(dest);
        return dest;
    }

/*

=back

=head2 Freeze/thaw Interface

=over 4

=item C<void freeze(visit_info *info)>

Used to archive the string.

=cut

*/
    VTABLE void freeze(visit_info *info) {
        /* XXX Dino - I'm concerned about freezing the entire
            allocated block of memory, it's dependent on the
            BITS_PER_CHAR value.
            Maybe we need to store that during the freeze as well
            and use it during thaw?
        */

        STRING           *s;
        IMAGE_IO * const  io   = info->image_io;
        const size_t      size = ROUND_BYTES(PMC_int_val(SELF));

        VTABLE_push_integer(INTERP, io, PMC_int_val2(SELF));
        VTABLE_push_integer(INTERP, io, PMC_int_val(SELF));

        s = string_from_cstring(INTERP, PMC_data_typed(SELF, char *), size);

        VTABLE_push_string(INTERP, io, s);
    }

/*

=item C<void thaw(visit_info *info)>

Used to unarchive the string.

=cut

*/
    VTABLE void thaw(visit_info *info) {
        IMAGE_IO * const io      = info->image_io;
        const INTVAL     headPos = VTABLE_shift_integer(INTERP, io);
        const INTVAL     tailPos = VTABLE_shift_integer(INTERP, io);
        STRING * const   s       = VTABLE_shift_string(INTERP, io);

        PMC_data(SELF)           = mem_sys_allocate_zeroed(s->bufused);
        mem_sys_memcopy(PMC_data(SELF), s->strstart, s->bufused);
        PMC_int_val2(SELF)       = headPos;
        PMC_int_val(SELF)        = tailPos;
    }

}  /* pmclass */

/*

=back

=head1 SEE ALSO

F<docs/pdds/pdd17_basic_types.pod>.

=head1 HISTORY

Initial version                  - Matt Fowles 2004-06-11

Changed allocator to double size - Matt Fowles 2004-06-15

Added push_integer               - Bernhard Schmalhofer 2004-10-17

Changed allocation code, added   - Dino Morelli 2005-06-10
  push_, pop_, shift_,
  unshift_integer, freeze, thaw

=cut

*/

/*
 * Local variables:
 *   c-file-style: "parrot"
 * End:
 * vim: expandtab shiftwidth=4:
 */
