From eba7be34e7202e7ca2ad434ae8e81859f89aeee2 Mon Sep 17 00:00:00 2001 From: Jeroen van Rijn Date: Tue, 1 Oct 2024 23:27:15 +0200 Subject: [PATCH] Add slice.to_type --- core/slice/slice.odin | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/core/slice/slice.odin b/core/slice/slice.odin index c917e6d9e..cd12a8c70 100644 --- a/core/slice/slice.odin +++ b/core/slice/slice.odin @@ -36,6 +36,17 @@ to_bytes :: proc "contextless" (s: []$T) -> []byte { return ([^]byte)(raw_data(s))[:len(s) * size_of(T)] } +/* + Turns a byte slice into a type. +*/ +@(require_results) +to_type :: proc(buf: []u8, $T: typeid) -> (T, bool) #optional_ok { + if len(buf) < size_of(T) { + return {}, false + } + return intrinsics.unaligned_load((^T)(raw_data(buf))), true +} + /* Turn a slice of one type, into a slice of another type.