Skip to content

Commit 4c92d8f

Browse files
committed
Use unsafe Binary constructor and add comments
1 parent 86673df commit 4c92d8f

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

rustler/src/resource.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,13 +144,22 @@ where
144144
}
145145
}
146146

147+
/// Make a resource binary associated with the given resource
148+
///
149+
/// The closure `f` is called with the referenced object and must return a slice with the same
150+
/// lifetime as the object. This means that the slice either has to be derived directly from
151+
/// the instance or that it has to have static lifetime.
147152
pub fn make_binary<'env, 'a, F>(&self, env: Env<'env>, f: F) -> Binary<'env>
148153
where
149154
F: FnOnce(&'a T) -> &'a [u8],
150155
{
151156
unsafe { self.make_binary_unsafe(env, f) }
152157
}
153158

159+
/// Make a resource binary without strict lifetime checking
160+
///
161+
/// The user *must* ensure that the lifetime of the returned slice is at least as long as the
162+
/// lifetime of the referenced instance.
154163
pub unsafe fn make_binary_unsafe<'env, 'a, 'b, F>(&self, env: Env<'env>, f: F) -> Binary<'env>
155164
where
156165
F: FnOnce(&'a T) -> &'b [u8],
@@ -164,7 +173,7 @@ where
164173
);
165174

166175
let term = Term::new(env, binary);
167-
Binary::from_term(term).unwrap()
176+
Binary::from_term_and_slice(term, bin)
168177
}
169178

170179
fn from_term(term: Term) -> Result<Self, Error> {

rustler/src/types/binary.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,6 @@
8686
//! [`OwnedBinary`]: struct.OwnedBinary.html
8787
8888
use crate::{
89-
wrapper::NIF_TERM,
9089
wrapper::binary::{alloc, new_binary, realloc, ErlNifBinary},
9190
Decoder, Encoder, Env, Error, NifResult, Term,
9291
};
@@ -237,7 +236,7 @@ unsafe impl Send for OwnedBinary {}
237236
/// See [module-level doc](index.html) for more information.
238237
#[derive(Copy, Clone)]
239238
pub struct Binary<'a> {
240-
buf: *mut u8,
239+
buf: *const u8,
241240
size: usize,
242241
term: Term<'a>,
243242
}
@@ -300,6 +299,17 @@ impl<'a> Binary<'a> {
300299
})
301300
}
302301

302+
/// Creates a Binary from a `term` and the associated slice
303+
///
304+
/// The `term` *must* be constructed from the given slice, it is not checked.
305+
pub(crate) unsafe fn from_term_and_slice(term: Term<'a>, binary: &[u8]) -> Self {
306+
Binary {
307+
term,
308+
buf: binary.as_ptr(),
309+
size: binary.len(),
310+
}
311+
}
312+
303313
/// Creates a `Binary` from `term`.
304314
///
305315
/// # Errors

0 commit comments

Comments
 (0)