Last active
March 25, 2025 11:23
-
-
Save 0riginaln0/042b11af7fa373ad4986e1c73c05a522 to your computer and use it in GitHub Desktop.
Dynamic array interface for a statically allocated array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
// odin run dynamic_from_static.odin -file | |
import "core:fmt" | |
import "core:slice" | |
MY_STATIC_ARRAY_LENGTH :: 6 | |
MY_STATIC_ARRAY: [MY_STATIC_ARRAY_LENGTH]int | |
print_slice :: proc(slice: []int) { | |
fmt.print("[") | |
for i in slice {fmt.print(i, " ")} | |
fmt.println("]") | |
} | |
main :: proc() { | |
fmt.println("MY_STATIC_ARRAY") | |
print_slice(MY_STATIC_ARRAY[:]) // [0 0 0 0 0 0 ] | |
fmt.println("SLICE [:]") | |
window := MY_STATIC_ARRAY[:] // [0 0 0 0 0 0 ] | |
print_slice(window) | |
fmt.println("DYNAMIC from SLICE") | |
dyn_s := slice.into_dynamic(window) | |
fmt.println("Dynamic len:", len(dyn_s), "cap:", cap(dyn_s)) // Dynamic len: 0 cap: 6 | |
print_slice(dyn_s[:]) // [] | |
append(&dyn_s, 1, 4) | |
inject_at(&dyn_s, 1, 2, 3) | |
fmt.println("Dynamic len:", len(dyn_s), "cap:", cap(dyn_s)) // Dynamic len: 4 cap: 6 | |
print_slice(dyn_s[:]) // [1 2 3 4 ] | |
fmt.println("MY STATIC ARRAY") | |
print_slice(MY_STATIC_ARRAY[:]) // [1 2 3 4 0 0 ] | |
fmt.println("DYNAMIC pop") | |
a := pop(&dyn_s) | |
fmt.println("got", a) // got 4 | |
print_slice(dyn_s[:]) // [1 2 3 ] | |
fmt.println("DYNAMIC fill remaining with zeros") | |
for i := len(dyn_s); i < cap(dyn_s); i += 1 { | |
assign_at(&dyn_s, i, 0) | |
} | |
print_slice(dyn_s[:]) // [1 2 3 0 0 0 ] | |
fmt.println("DYNAMIC append to full") | |
ok, error := append(&dyn_s, 21) | |
fmt.println(error) // Out_Of_Memory | |
print_slice(dyn_s[:]) // [1 2 3 0 0 0 ] | |
fmt.println("DYNAMIC remove last 4 if present") | |
if len(dyn_s) > 4 { | |
remove_range(&dyn_s, len(dyn_s) - 4, len(dyn_s)) | |
print_slice(dyn_s[:]) // [1 2 ] | |
} | |
fmt.println("Clear DYNAMIC") | |
clear(&dyn_s) | |
print_slice(dyn_s[:]) // [] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment