A small Jai library for making it easy to share pointers/references to the same data, while making it easy to get rid of the pointer/reference when it is no longer needed.
You just create a variable using with the Ref(T)
type, where you replace T
with your type. For example Ref(int)
.
Then you initialize it with init(*ref_variable)
where ref_variable
is your variable,
and it will initialize the value to all 0s.
And you can now get a pointer to the inner value using get(ref_variable)
, so you can read it,
or even set it using something like get(ref_variable).* = 10;
.
Aditionally, you can copy it without re-allocating anything by using the copy(ref_variable)
function.
So, you can do something like this other_ref := copy(ref_variable);
.
Then you can get rid of it using the deinit(*ref_variable)
function, and if it's the last one,
it will also dealocate the internal pointer it uses to syncronice all the references.
Though you would have to free any other memory in the value, for example if you have a reference to a pointer,
or something containing a pointer.
If you want to do this, you could look at the internal counter, like this: ref_variable.counted.count
,
and if it's 1 it will be deallocated on the next call to deinit
if you don't copy it in the meantime.
So you can make a custom deinit function:
my_deinit :: (ref: *Ref(Foo)) {
if ref.counted.count == 1 then deinit(get(ref));
deinit(ref);
}
$ jai -version
Version: beta 0.1.091, built on 8 June 2024.