diff options
| author | Laytan <laytanlaats@hotmail.com> | 2024-12-14 16:46:17 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-12-14 16:46:17 +0100 |
| commit | 8b1c9b0ff5b7ad392fa48e050eae460da8edb982 (patch) | |
| tree | f6991ebf04ee3c95a483d49113656044341ea22c | |
| parent | 0a29d36aa3ddaa9d56d2e31bfec1a6f65487b387 (diff) | |
| parent | 6785a485e3cdb330f1df4124b2ae9a1c48faff31 (diff) | |
Merge pull request #4568 from giuliano-macedo/master
docs: improved `slice.reinterpret` docstring
| -rw-r--r-- | core/slice/slice.odin | 51 |
1 files changed, 35 insertions, 16 deletions
diff --git a/core/slice/slice.odin b/core/slice/slice.odin index c31edf281..66166bddb 100644 --- a/core/slice/slice.odin +++ b/core/slice/slice.odin @@ -48,22 +48,41 @@ to_type :: proc(buf: []u8, $T: typeid) -> (T, bool) #optional_ok { } /* - Turn a slice of one type, into a slice of another type. - - Only converts the type and length of the slice itself. - The length is rounded down to the nearest whole number of items. - - ``` - large_items := []i64{1, 2, 3, 4} - small_items := slice.reinterpret([]i32, large_items) - assert(len(small_items) == 8) - ``` - ``` - small_items := []byte{1, 0, 0, 0, 0, 0, 0, 0, - 2, 0, 0, 0} - large_items := slice.reinterpret([]i64, small_items) - assert(len(large_items) == 1) // only enough bytes to make 1 x i64; two would need at least 8 bytes. - ``` +Turn a slice of one type, into a slice of another type. + +Only converts the type and length of the slice itself. +The length is rounded down to the nearest whole number of items. + +Example: + + import "core:fmt" + import "core:slice" + + i64s_as_i32s :: proc() { + large_items := []i64{1, 2, 3, 4} + small_items := slice.reinterpret([]i32, large_items) + assert(len(small_items) == 8) + fmt.println(large_items, "->", small_items) + } + + bytes_as_i64s :: proc() { + small_items := [12]byte{} + small_items[0] = 1 + small_items[8] = 2 + large_items := slice.reinterpret([]i64, small_items[:]) + assert(len(large_items) == 1) // only enough bytes to make 1 x i64; two would need at least 8 bytes. + fmt.println(small_items, "->", large_items) + } + + reinterpret_example :: proc() { + i64s_as_i32s() + bytes_as_i64s() + } + +Output: + [1, 2, 3, 4] -> [1, 0, 2, 0, 3, 0, 4, 0] + [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0] -> [1] + */ @(require_results) reinterpret :: proc "contextless" ($T: typeid/[]$U, s: []$V) -> []U { |