/* Illustrative reference-counted values. Not a production runtime. */
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Object Object;
typedef enum { INTEGER, REAL, STRING, VECTOR, ARRAY } Kind;
struct Object {
    Kind kind;
    size_t refs;
    union {
        int integer;
        double real;
        struct { char *bytes; size_t len; } string;
        Object *vector[3];
        struct { Object **items; size_t len; } array;
    } as;
};

/* Test hook: fail after n successful allocations; SIZE_MAX disables it. */
static size_t budget = SIZE_MAX, live_allocations = 0;
static void *allocate(size_t n) {
    if (budget == 0) return NULL;
    if (budget != SIZE_MAX) --budget;
    void *p = malloc(n);
    if (p) ++live_allocations;
    return p;
}
static void dispose(void *p) { if (p) { --live_allocations; free(p); } }
static bool retain(Object *o) {
    if (!o) return true;
    if (o->refs == SIZE_MAX) return false;
    ++o->refs;
    return true;
}
/* Requires NULL or one owned reference to a live object. */
static void release(Object *o) {
    if (!o || --o->refs) return;
    switch (o->kind) {
    case STRING: dispose(o->as.string.bytes); break;
    case VECTOR:
        for (size_t i = 0; i < 3; ++i) release(o->as.vector[i]);
        break;
    case ARRAY:
        for (size_t i = 0; i < o->as.array.len; ++i) release(o->as.array.items[i]);
        dispose(o->as.array.items); break;
    case INTEGER: case REAL: break;
    }
    dispose(o);
}
static Object *new_object(Kind k) {
    Object *o = allocate(sizeof *o);
    if (o) { o->kind = k; o->refs = 1; }
    return o;
}
static Object *integer(int x) {
    Object *o = new_object(INTEGER); if (o) o->as.integer = x; return o;
}
static Object *real(double x) {
    Object *o = new_object(REAL); if (o) o->as.real = x; return o;
}
static Object *string_n(const char *s, size_t n) {
    if (n == SIZE_MAX) return NULL;
    Object *o = new_object(STRING);
    if (!o) return NULL;
    o->as.string.bytes = allocate(n + 1);
    if (!o->as.string.bytes) { dispose(o); return NULL; }
    memcpy(o->as.string.bytes, s, n);
    o->as.string.bytes[n] = '\0'; o->as.string.len = n;
    return o;
}
static Object *string(const char *s) { return s ? string_n(s, strlen(s)) : NULL; }
/* Inputs borrowed; each successful slot becomes an owned edge. */
static Object *vector(Object *x, Object *y, Object *z) {
    Object *values[3] = {x, y, z};
    Object *o = new_object(VECTOR);
    if (!o) return NULL;
    for (size_t i = 0; i < 3; ++i) o->as.vector[i] = NULL;
    for (size_t i = 0; i < 3; ++i) {
        if (!retain(values[i])) { release(o); return NULL; }
        o->as.vector[i] = values[i];
    }
    return o;
}
static Object *array(size_t n) {
    if (n > SIZE_MAX / sizeof(Object *)) return NULL;
    Object *o = new_object(ARRAY);
    if (!o) return NULL;
    o->as.array.len = n; o->as.array.items = NULL;
    if (n) {
        o->as.array.items = allocate(n * sizeof *o->as.array.items);
        if (!o->as.array.items) { dispose(o); return NULL; }
        for (size_t i = 0; i < n; ++i) o->as.array.items[i] = NULL;
    }
    return o;
}
static bool set(Object *a, size_t i, Object *value) {
    if (!a || a->kind != ARRAY || i >= a->as.array.len || !retain(value)) return false;
    Object *old = a->as.array.items[i];
    a->as.array.items[i] = value; release(old); return true;
}
/* A true return can still put NULL in *out for an empty slot. */
static bool get(const Object *a, size_t i, Object **out) {
    if (!a || a->kind != ARRAY || !out || i >= a->as.array.len) return false;
    *out = a->as.array.items[i]; return true;
}
static bool length(const Object *o, size_t *out) {
    if (!o || !out) return false;
    switch (o->kind) {
    case INTEGER: case REAL: *out = 1; break;
    case STRING: *out = o->as.string.len; break;
    case VECTOR: *out = 3; break;
    case ARRAY: *out = o->as.array.len; break;
    default: return false;
    }
    return true;
}
/* Borrowed inputs, new owned output; NULL means unsupported or failure.
   Cyclic/deep vector inputs are outside this recursive function's contract. */
static Object *add(const Object *a, const Object *b) {
    if (!a || !b) return NULL;
    if (a->kind == INTEGER && b->kind == INTEGER) {
        int x = a->as.integer, y = b->as.integer;
        if ((y > 0 && x > INT_MAX - y) || (y < 0 && x < INT_MIN - y)) return NULL;
        return integer(x + y);
    }
    if ((a->kind == INTEGER || a->kind == REAL) &&
        (b->kind == INTEGER || b->kind == REAL)) {
        double x = a->kind == INTEGER ? (double)a->as.integer : a->as.real;
        double y = b->kind == INTEGER ? (double)b->as.integer : b->as.real;
        return real(x + y);
    }
    if (a->kind == STRING && b->kind == STRING) {
        size_t x = a->as.string.len, y = b->as.string.len;
        if (x == SIZE_MAX || y > SIZE_MAX - x - 1) return NULL;
        Object *o = new_object(STRING); if (!o) return NULL;
        o->as.string.bytes = allocate(x + y + 1);
        if (!o->as.string.bytes) { dispose(o); return NULL; }
        memcpy(o->as.string.bytes, a->as.string.bytes, x);
        memcpy(o->as.string.bytes + x, b->as.string.bytes, y + 1);
        o->as.string.len = x + y; return o;
    }
    if (a->kind == VECTOR && b->kind == VECTOR) {
        Object *parts[3] = {NULL, NULL, NULL}, *result = NULL;
        for (size_t i = 0; i < 3; ++i) {
            parts[i] = add(a->as.vector[i], b->as.vector[i]);
            if (!parts[i]) goto done;
        }
        result = vector(parts[0], parts[1], parts[2]);
    done:
        for (size_t i = 0; i < 3; ++i) release(parts[i]);
        return result;
    }
    if (a->kind == ARRAY && b->kind == ARRAY) {
        size_t x = a->as.array.len, y = b->as.array.len;
        if (y > SIZE_MAX - x) return NULL;
        Object *o = array(x + y); if (!o) return NULL;
        for (size_t i = 0; i < x + y; ++i) {
            Object *v = i < x ? a->as.array.items[i] : b->as.array.items[i - x];
            if (!set(o, i, v)) { release(o); return NULL; }
        }
        return o;
    }
    return NULL;
}
int main(void) {
    Object *one = integer(1), *two = integer(2), *r = real(0.5);
    Object *s = string("hi"), *t = string("!");
    Object *a = array(2), *v = NULL, *sum = NULL, *out = NULL;
    assert(one && two && r && s && t && a);
    assert(set(a, 0, one) && set(a, 0, one));
    assert(get(a, 1, &out) && out == NULL && !get(a, 2, &out));
    size_t n; assert(length(a, &n) && n == 2 && length(s, &n) && n == 2);
    sum = add(one, two); assert(sum && sum->as.integer == 3); release(sum);
    sum = add(one, r); assert(sum && sum->kind == REAL && sum->as.real == 1.5); release(sum);
    sum = add(s, t); assert(sum && strcmp(sum->as.string.bytes, "hi!") == 0); release(sum);
    sum = add(a, a); assert(sum && length(sum, &n) && n == 4 && get(sum, 2, &out) && out == one); release(sum);
    v = vector(one, two, one); assert(v);
    sum = add(v, v); assert(sum && sum->as.vector[0]->as.integer == 2 && sum->as.vector[1]->as.integer == 4); release(sum);
    assert(!add(s, one));
    Object *max = integer(INT_MAX); assert(max && !add(max, one)); release(max);
    /* Fail each allocation in vector addition and verify rollback. */
    size_t baseline = live_allocations;
    for (size_t limit = 0; limit < 4; ++limit) {
        budget = limit; sum = add(v, v); assert(!sum && live_allocations == baseline);
    }
    budget = SIZE_MAX;
    release(v); release(a); release(t); release(s); release(r); release(two); release(one);
    assert(live_allocations == 0);
    puts("numeric, string, array and vector addition: ok");
    puts("bounds, overflow and allocation rollback: ok");
    return 0;
}
