//! returns: 0
//! Functions return references into storage that their region parameter
//! borrows, and borrow blocks name the region of a reference.

/// One entry of a map.
record Entry: Copy {
    /// Lookup key.
    key: u64,
    /// Stored value.
    value: u32,
}

/// Fixed map of four entries.
record Map {
    /// Entries in insertion order.
    entries: [Entry; 4],
    /// Number of entries in use.
    len: u32,
}

/// Find the value of `key`.
fn get(map: &'r Map, key: u64) -> ?&'r u32 {
    for i in 0 .. map.len {
        if map.entries[i].key == key {
            return &map.entries[i].value;
        }
    }
    return nil;
}

/// Find the value of `key` for update.
fn getMut(map: &'r mut Map, key: u64) -> ?&'r mut u32 {
    for i in 0 .. map.len {
        if map.entries[i].key == key {
            return &mut map.entries[i].value;
        }
    }
    return nil;
}

/// Return the first entry.
fn first(map: &'r Map) -> &'r Entry {
    return &map.entries[0];
}

/// Return the value of an entry, chaining through another region function.
fn firstValue(map: &'r Map) -> &'r u32 {
    let entry = first(map);
    return &entry.value;
}

/// Return the value of `key` or of the first entry.
fn getOrFirst(map: &'r Map, key: u64) -> &'r u32 {
    if let v = get(map, key) {
        return v;
    }
    return firstValue(map);
}

/// Return the value of `entry` unless `other` has the same key. The result
/// borrows only from `entry`.
fn distinct(entry: &'a Entry, other: &'b Entry) -> ?&'a u32 {
    if entry.key == other.key {
        return nil;
    }
    return &entry.value;
}

/// Return the entries in use.
fn used(map: &'r Map) -> &'r [Entry] {
    return &map.entries[..map.len];
}

/// Return the entries after the first `n`, or nil past the end.
fn skip(entries: &'r [Entry], n: u32) -> ?&'r [Entry] {
    if n > entries.len {
        return nil;
    }
    return &entries[n..];
}

/// Return the entries before the first whose key is in `keys`.
fn until(entries: &'r [Entry], keys: &[u64]) -> &'r [Entry] {
    for e, i in entries {
        for k in keys {
            if e.key == k {
                return &entries[..i];
            }
        }
    }
    return entries;
}

/// Error of a lookup.
union LookupError { Missing }

/// Find the value of `key`, or throw.
fn find(map: &'r mut Map, key: u64) -> &'r mut u32 throws (LookupError) {
    for i in 0 .. map.len {
        if map.entries[i].key == key {
            return &mut map.entries[i].value;
        }
    }
    throw LookupError::Missing;
}

/// Return the entries from index `n`, or throw past the end.
fn from(entries: &'r [Entry], n: u32) -> &'r [Entry] throws (LookupError) {
    if n > entries.len {
        throw LookupError::Missing;
    }
    return &entries[n..];
}

/// Find the value of `key` through a throwing function, and propagate errors.
fn findAgain(map: &'r mut Map, key: u64) -> &'r mut u32 throws (LookupError) {
    return try find(map, key);
}

/// Return the values after the first, for update.
fn tail(values: &'r mut [u32]) -> &'r mut [u32] {
    return &mut values[1..];
}

/// Add `n` to a value.
fn add(value: &mut u32, n: u32) {
    set *value += n;
}

/// Read a value.
fn read(value: &u32) -> u32 {
    return *value;
}

/// Insert a value.
fn (m: &mut Map) insert(key: u64, value: u32) {
    set m.entries[m.len] = Entry { key, value };
    set m.len += 1;
}

/// Return the entries in use through a method.
fn (m: &'r Map) all() -> &'r [Entry] {
    return used(m);
}

/// Find a value through a method.
fn (m: &'r Map) find(key: u64) -> ?&'r u32 {
    return get(m, key);
}

@default fn main() -> i32 {
    let mut map = Map { entries: [Entry { key: 0, value: 0 }; 4], len: 0 };
    map.insert(41, 1);
    map.insert(42, 2);

    let m: &'r Map = &map {
        let value = get(m, 42) else {
            return 1;
        };
        let other: &'r u32 = firstValue(m);
        assert read(value) + *other == 3;
        assert *getOrFirst(m, 99) == 1;
        if let _ = distinct(first(m), first(m)) {
            return 4;
        }
        let entries = used(m);
        assert entries.len == 2;
        let rest = skip(entries, 1) else {
            return 5;
        };
        assert rest.len == 1 and rest[0].key == 42;
        if let _ = skip(m.all(), 3) {
            return 6;
        }
        assert until(entries, &[7, 42]).len == 1;
        assert until(entries, &[]).len == 2;
        if let found = m.find(41) {
            assert *found == 1;
        } else {
            return 2;
        }
    }
    map.insert(43, 3);

    let w: &'w mut Map = &mut map {
        if let v = getMut(w, 43) {
            add(v, 4);
        }
        let v = getMut(w, 42) else {
            return 3;
        };
        set *v = 9;
    }
    let mut values: [u32; 3] = [1, 2, 3];
    let v: &'v mut [u32] = &mut values[..] {
        let t = tail(v);
        set t[0] = 5;
        assert t.len == 2;
    }
    assert values[1] == 5;

    let t: &'t mut Map = &mut map {
        if let _ = try? find(t, 99) {
            return 8;
        }
        assert read(try! find(t, 42)) == 9;
        if let tail = try? from(used(t), 2) {
            assert tail.len == 1 and tail[0].key == 43;
        } else {
            return 9;
        }
        if let _ = try? from(used(t), 4) {
            return 10;
        }
        let v = try findAgain(t, 41) catch {
            return 7;
        };
        set *v = 8;
    }
    assert map.entries[0].value == 8;
    assert map.entries[2].value == 7;
    assert map.entries[1].value == 9;
    return 0;
}
