aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorgingerBill <bill@gingerbill.org>2024-02-10 15:13:09 +0000
committergingerBill <bill@gingerbill.org>2024-02-10 15:13:09 +0000
commite201a2fabbec8bcab6ce19d12262fad61aba9a30 (patch)
treebe7a83921501600782a49ca0ea71ac62ebfdbb5a
parent5c4485f65767366c14dfd9a98945a5479ae0e449 (diff)
Add `rand.choice_enum`
-rw-r--r--core/math/rand/rand.odin20
1 files changed, 20 insertions, 0 deletions
diff --git a/core/math/rand/rand.odin b/core/math/rand/rand.odin
index 14894e82c..560dc8379 100644
--- a/core/math/rand/rand.odin
+++ b/core/math/rand/rand.odin
@@ -834,3 +834,23 @@ choice :: proc(array: $T/[]$E, r: ^Rand = nil) -> (res: E) {
}
return array[int63_max(n, r)]
}
+
+
+@(require_results)
+choice_enum :: proc($T: typeid, r: ^Rand = nil) -> T
+ where
+ intrinsics.type_is_enum(T),
+ size_of(T) <= 8,
+ len(T) == cap(T) /* Only allow contiguous enum types */
+{
+ when intrinsics.type_is_unsigned(intrinsics.type_core_type(T)) &&
+ u64(max(T)) > u64(max(i64)) {
+ i := uint64(r) % u64(len(T))
+ i += u64(min(T))
+ return T(i)
+ } else {
+ i := int63_max(i64(len(T)), r)
+ i += i64(min(T))
+ return T(i)
+ }
+} \ No newline at end of file