From 437e9b954d8a47a1acb6aa5327c6473ab8d9267c Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Thu, 17 Dec 2015 14:59:08 -0700 Subject: [PATCH] add some brainstorming example zig code --- example/guess_number/main.zig | 33 ++++++++++++++++++ example/list/list.zig | 66 +++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 example/guess_number/main.zig create mode 100644 example/list/list.zig diff --git a/example/guess_number/main.zig b/example/guess_number/main.zig new file mode 100644 index 0000000000..07de57ee06 --- /dev/null +++ b/example/guess_number/main.zig @@ -0,0 +1,33 @@ +export executable "guess_number"; + +use "std.zig"; + +fn main(argc: isize, argv: &&u8, env: &&u8) -> i32 { + print_str("Welcome to the Guess Number Game in Zig.\n"); + + var seed : u32; + ok_or_panic(os_get_random_bytes(&seed, 4)); + var rand_state = rand_init(seed); + + const answer = rand_int(&rand_state, 0, 100) + 1; + + while true { + Buffer line = readline("\nGuess a number between 1 and 100: "); + + (const err, const guess) = parse_number(line); + if err == Error.None { + if guess == answer { + print_str("You win!\n"); + return 0; + } else if guess < answer { + print_str("Guess higher.\n"); + } else { + print_str("Guess lower.\n"); + } + } else { + print_str("Invalid number format.\n"); + } + } + + return 0; +} diff --git a/example/list/list.zig b/example/list/list.zig new file mode 100644 index 0000000000..9159ee389f --- /dev/null +++ b/example/list/list.zig @@ -0,0 +1,66 @@ +pub struct List#(T: type) { + items: ?&T, + length: usize, + capacity: usize, + + pub fn (l: &List) deinit() { + free(l.items); + l.items = None; + } + + pub fn append(l: &List, item: T) -> error { + const err = l.ensure_capacity(l.length + 1); + 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 { + const new_items = realloc(l.items, better_capacity) ?? { return Error.NoMem }; + l.items = new_items; + l.capacity = better_capacity; + } + 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) { + +}