1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/templates/native/common.c Fri Dec 09 16:22:37 2016 +0100
1.3 @@ -0,0 +1,73 @@
1.4 +/* Common operations for native functions.
1.5 +
1.6 +Copyright (C) 2016 Paul Boddie <paul@boddie.org.uk>
1.7 +
1.8 +This program is free software; you can redistribute it and/or modify it under
1.9 +the terms of the GNU General Public License as published by the Free Software
1.10 +Foundation; either version 3 of the License, or (at your option) any later
1.11 +version.
1.12 +
1.13 +This program is distributed in the hope that it will be useful, but WITHOUT
1.14 +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1.15 +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
1.16 +details.
1.17 +
1.18 +You should have received a copy of the GNU General Public License along with
1.19 +this program. If not, see <http://www.gnu.org/licenses/>.
1.20 +*/
1.21 +
1.22 +#include "types.h"
1.23 +#include "exceptions.h"
1.24 +#include "ops.h"
1.25 +#include "progconsts.h"
1.26 +#include "progops.h"
1.27 +#include "progtypes.h"
1.28 +#include "main.h"
1.29 +
1.30 +/* Utility functions. */
1.31 +
1.32 +__attr __new_int(int i)
1.33 +{
1.34 + /* Create a new integer and mutate the __data__ attribute. */
1.35 + __attr attr = __new(&__InstanceTable___builtins___int_int, &__builtins___int_int, sizeof(__obj___builtins___int_int));
1.36 + attr.value->attrs[__pos___data__].intvalue = i;
1.37 + return attr;
1.38 +}
1.39 +
1.40 +__attr __new_str(char *s)
1.41 +{
1.42 + /* Create a new string and mutate the __data__ attribute. */
1.43 + __attr attr = __new(&__InstanceTable___builtins___str_string, &__builtins___str_string, sizeof(__obj___builtins___str_string));
1.44 + attr.value->attrs[__pos___data__].strvalue = s;
1.45 + return attr;
1.46 +}
1.47 +
1.48 +__attr __new_list(__fragment *f)
1.49 +{
1.50 + /* Create a new list and mutate the __data__ attribute. */
1.51 + __attr attr = __new(&__InstanceTable___builtins___list_list, &__builtins___list_list, sizeof(__obj___builtins___list_list));
1.52 + attr.value->attrs[__pos___data__].seqvalue = f;
1.53 + return attr;
1.54 +}
1.55 +
1.56 +__fragment *__fragment_append(__fragment *data, __attr * const value)
1.57 +{
1.58 + __fragment *newdata = data;
1.59 + unsigned int size = data->size, capacity = data->capacity;
1.60 + unsigned int n;
1.61 +
1.62 + /* Re-allocate the fragment if the capacity has been reached. */
1.63 + if (size >= capacity)
1.64 + {
1.65 + /* NOTE: Consider various restrictions on capacity increases. */
1.66 + n = capacity ? capacity * 2 : 1;
1.67 + newdata = (__fragment *) __REALLOCATE(data, __FRAGMENT_SIZE(n));
1.68 + newdata->capacity = n;
1.69 + }
1.70 +
1.71 + /* Insert the new element and increment the list size. */
1.72 + newdata->attrs[size] = *value;
1.73 + newdata->size = size + 1;
1.74 +
1.75 + return newdata;
1.76 +}