zig/example/list/list.zig

103 lines
2.2 KiB
Zig
Raw Normal View History

pub struct List#(T: type) {
items: ?&T,
2016-01-14 09:15:51 +08:00
length: isize,
capacity: isize,
2016-01-14 09:15:51 +08:00
pub fn deinit(l: &List) {
free(l.items);
2016-01-14 09:15:51 +08:00
l.items = null;
}
pub fn append(l: &List, item: T) -> error {
const err = l.ensure_capacity(l.length + 1);
2016-01-14 09:15:51 +08:00
if err != error.None {
return err;
}
const raw_items = l.items ?? unreachable;
l.raw_items[l.length] = item;
l.length += 1;
return 0;
}
pub fn at(l: List, index: usize) -> T {
assert(index < l.length);
const raw_items = l.items ?? unreachable;
return raw_items[index];
}
pub fn ptr_at(l: &List, index: usize) -> &T {
assert(index < l.length);
const raw_items = l.items ?? unreachable;
return &raw_items[index];
}
pub fn clear(l: &List) {
l.length = 0;
}
pub fn pop(l: &List) -> T {
assert(l.length >= 1);
l.length -= 1;
return l.items[l.length];
}
fn ensure_capacity(l: &List, new_capacity: usize) -> error {
var better_capacity = max(l.capacity, 16);
while better_capacity < new_capacity {
better_capacity *= 2;
}
if better_capacity != l.capacity {
2016-01-14 09:15:51 +08:00
const new_items = realloc(l.items, better_capacity) ?? { return error.NoMem };
l.items = new_items;
l.capacity = better_capacity;
}
2016-01-14 09:15:51 +08:00
error.None
}
}
pub fn malloc#(T: type)(count: usize) -> ?&T { realloc(None, count) }
pub fn realloc#(T: type)(ptr: ?&T, new_count: usize) -> ?&T {
}
pub fn free#(T: type)(ptr: ?&T) {
}
2016-01-14 09:15:51 +08:00
////////////////// alternate
2016-01-20 17:12:24 +08:00
// previously proposed but without ->
fn max#(T: type)(a: T, b: T) T {
2016-01-14 09:15:51 +08:00
if (a > b) a else b
}
// andy's new idea
2016-01-20 17:12:24 +08:00
// parameters can reference other inline parameters.
fn max(inline T: type, a: T, b: T) T {
2016-01-14 09:15:51 +08:00
if (a > b) a else b
}
fn f() {
2016-01-20 17:12:24 +08:00
const x: i32 = 1234;
const y: i32 = 5678;
2016-01-14 09:15:51 +08:00
const z = max(@typeof(x), x, y);
}
// So, type-generic functions don't need any fancy syntax. type-generic
// containers still do, though:
2016-01-20 17:12:24 +08:00
pub struct List(T: type) {
items: ?&T,
length: isize,
capacity: isize,
2016-01-14 09:15:51 +08:00
}
2016-01-20 17:12:24 +08:00
// we don't need '#' to indicate type generic parameters.
2016-01-14 09:15:51 +08:00
fn f() {
2016-01-20 17:12:24 +08:00
var list: List(u8);
2016-01-14 09:15:51 +08:00
}