From 80d51103ab9dfdbe60efb7f1da66b3241eed9f98 Mon Sep 17 00:00:00 2001 From: Zach Shipko Date: Fri, 8 May 2020 15:02:38 -0700 Subject: [PATCH] Fix docs --- README.md | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 8396107b..c525b852 100644 --- a/README.md +++ b/README.md @@ -172,32 +172,43 @@ This chart contains the mapping between Rust and OCaml types used by `ocaml::fun | `BTreeMap` | `('a, 'b) list` | | `LinkedList` | `'a list` | -Additionally, `Pointer` can be used to create and access Rust types on the OCaml heap. +NOTE: Even though `&[Value]` is specifically marked as no copy, any type like `Option` would also qualify since the inner value is not converted to a Rust type. However, `Option` will do full unmarshaling into Rust types. Another thing to note: `FromValue` for `str` and `&[u8]` is zero-copy, however `ToValue` for `str` and `&[u8]` creates a new value - this is necessary to ensure the string is registered with the OCaml runtime. + +If you're concerned with minimizing allocations/conversions you should use `Value` type directly. + +#### Pointers to Rust values on the OCaml heap + +`Pointer` can be used to create and access Rust types on the OCaml heap. For example, for a type that implements `Custom`: ```rust +use ocaml::FromValue; + struct MyType; -custom!(MyType); +unsafe extern "C" fn mytype_finalizer(v: ocaml::Value) { + let ptr: ocaml::Pointer = ocaml::Pointer::from_value(v); + ptr.drop_in_place() +} + +ocaml::custom_finalize!(MyType, mytype_finalizer); #[ocaml::func] -fn new_my_type() -> Pointer { - ocaml::Pointer::alloc_custom(MyType) +pub fn new_my_type() -> ocaml::Pointer { + ocaml::Pointer::alloc_custom(MyType) + // ocaml::Pointer::alloc_final(MyType, finalizer) can also be used + // if you don't intend to implement `Custom` } -#[ocaml::func]] -fn my_type_example(t: Pointer) { - let my_type = t.as_mut(); - // MyType has no fields, but normally you - // would do something with MyType here +#[ocaml::func] +pub fn my_type_example(t: ocaml::Pointer) { + let my_type = t.as_mut(); + // MyType has no fields, but normally you + // would do something with MyType here } ``` -NOTE: Even though `&[Value]` is specifically marked as no copy, any type like `Option` would also qualify since the inner value is not converted to a Rust type. However, `Option` will do full unmarshaling into Rust types. Another thing to note: `FromValue` for `str` and `&[u8]` is zero-copy, however `ToValue` for `str` and `&[u8]` creates a new value - this is necessary to ensure the string is registered with the OCaml runtime. - -If you're concerned with minimizing allocations/conversions you should use `Value` type directly. - ## Upgrading Since 0.10 and later have a much different API compared to earlier version, here is are some major differences that should be considered when upgrading: