| @@ -19,7 +19,9 @@ |
| 19 | 19 | |
| 20 | 20 | use std::ffi::{c_char, c_void}; |
| 21 | 21 | |
| 22 | | −/// A tilcayo value: a tagged 63-bit int or a pointer to a heap block. |
| 22 | +/// A tilcayo value: a tagged 63-bit int or a pointer to a heap block (an |
| 23 | +/// `Int` outside 63 bits is a block: use [`int_i64`] and [`int_from_i64`] |
| 24 | +/// for `Int`s that may be big). |
| 23 | 25 | pub type Value = usize; |
| 24 | 26 | |
| 25 | 27 | /// An actor's execution context (opaque). |
| @@ -36,6 +38,8 @@ unsafe extern "C" { |
| 36 | 38 | fn tl_string_from(ctx: *mut Ctx, bytes: *const c_char, len: usize) -> Value; |
| 37 | 39 | fn tl_string_len(s: Value) -> usize; |
| 38 | 40 | fn tl_string_ptr(s: Value) -> *const c_char; |
| 41 | + fn tl_int_to_i64(v: Value, out: *mut i64) -> bool; |
| 42 | + fn tl_int_from_i64(ctx: *mut Ctx, n: i64) -> Value; |
| 39 | 43 | /// Wrap a foreign pointer with its finalizer as a `Resource<t>`. |
| 40 | 44 | pub fn tl_resource_new( |
| 41 | 45 | ctx: *mut Ctx, |
| @@ -47,16 +51,39 @@ unsafe extern "C" { |
| 47 | 51 | pub fn tl_resource_get(r: Value) -> *mut c_void; |
| 48 | 52 | } |
| 49 | 53 | |
| 50 | | −/// An `Int`. |
| 54 | +/// A small `Int`: `n` must be within 63 bits (`-2^62..2^62`). |
| 51 | 55 | pub fn int(n: i64) -> Value { |
| 52 | 56 | ((n as u64) << 1) as usize | 1 |
| 53 | 57 | } |
| 54 | 58 | |
| 55 | | −/// The `i64` of an `Int`. |
| 59 | +/// The `i64` of a small `Int` (low bit 1). A big `Int` is a block: see |
| 60 | +/// [`int_i64`]. |
| 56 | 61 | pub fn int_get(v: Value) -> i64 { |
| 57 | 62 | (v as i64) >> 1 |
| 58 | 63 | } |
| 59 | 64 | |
| 65 | +/// The `i64` of any `Int` (borrowed), if it fits. |
| 66 | +/// |
| 67 | +/// # Safety |
| 68 | +/// `v` must be a live `Int`. |
| 69 | +pub unsafe fn int_i64(v: Value) -> Option<i64> { |
| 70 | + if v & 1 == 1 { |
| 71 | + return Some(int_get(v)); |
| 72 | + } |
| 73 | + let mut n = 0; |
| 74 | + // SAFETY: forwarded caller guarantee; `n` is valid for a write. |
| 75 | + unsafe { tl_int_to_i64(v, &mut n) }.then_some(n) |
| 76 | +} |
| 77 | + |
| 78 | +/// An `Int` (owned) for any `i64`: big outside 63 bits. |
| 79 | +/// |
| 80 | +/// # Safety |
| 81 | +/// `ctx` must be the context the binding was called with. |
| 82 | +pub unsafe fn int_from_i64(ctx: *mut Ctx, n: i64) -> Value { |
| 83 | + // SAFETY: forwarded caller guarantee. |
| 84 | + unsafe { tl_int_from_i64(ctx, n) } |
| 85 | +} |
| 86 | + |
| 60 | 87 | /// A `Bool`. |
| 61 | 88 | pub fn bool(b: bool) -> Value { |
| 62 | 89 | if b { TRUE } else { FALSE } |