Skip to content

Commit e403601

Browse files
authored
Add Blob::buffer_as_type() and fix mutability (#55)
1 parent 11d2c13 commit e403601

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

crates/openvino/src/blob.rs

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ impl Blob {
7676
/// # Panics
7777
///
7878
/// Panics if the returned OpenVINO size will not fit in `usize`.
79-
pub fn len(&mut self) -> Result<usize> {
79+
pub fn len(&self) -> Result<usize> {
8080
let mut size = 0;
8181
try_unsafe!(ie_blob_size(self.instance, std::ptr::addr_of_mut!(size)))?;
8282
Ok(usize::try_from(size).unwrap())
@@ -87,7 +87,7 @@ impl Blob {
8787
/// # Panics
8888
///
8989
/// Panics if the returned OpenVINO size will not fit in `usize`.
90-
pub fn byte_len(&mut self) -> Result<usize> {
90+
pub fn byte_len(&self) -> Result<usize> {
9191
let mut size = 0;
9292
try_unsafe!(ie_blob_byte_size(
9393
self.instance,
@@ -97,7 +97,7 @@ impl Blob {
9797
}
9898

9999
/// Retrieve the [`Blob`]'s data as an immutable slice of bytes.
100-
pub fn buffer(&mut self) -> Result<&[u8]> {
100+
pub fn buffer(&self) -> Result<&[u8]> {
101101
let mut buffer = Blob::empty_buffer();
102102
try_unsafe!(ie_blob_get_buffer(
103103
self.instance,
@@ -124,6 +124,28 @@ impl Blob {
124124
Ok(slice)
125125
}
126126

127+
/// Retrieve the [`Blob`]'s data as an immutable slice of type `T`.
128+
///
129+
/// # Safety
130+
///
131+
/// This function is `unsafe`, since the values of `T` may not have been properly initialized;
132+
/// however, this functionality is provided as an equivalent of what C/C++ users of OpenVINO
133+
/// currently do to access [`Blob`]s with, e.g., floating point values:
134+
/// `results.buffer_as_type::<f32>()`.
135+
pub unsafe fn buffer_as_type<T>(&self) -> Result<&[T]> {
136+
let mut buffer = Blob::empty_buffer();
137+
InferenceError::from(ie_blob_get_buffer(
138+
self.instance,
139+
std::ptr::addr_of_mut!(buffer),
140+
))?;
141+
// This is very unsafe, but very convenient: by allowing users to specify T, they can
142+
// retrieve the buffer in whatever shape they prefer. But we must ensure that they cannot
143+
// read too many bytes, so we manually calculate the resulting slice `size`.
144+
let size = self.byte_len()? / std::mem::size_of::<T>();
145+
let slice = std::slice::from_raw_parts(buffer.__bindgen_anon_1.buffer.cast::<T>(), size);
146+
Ok(slice)
147+
}
148+
127149
/// Retrieve the [`Blob`]'s data as a mutable slice of type `T`.
128150
///
129151
/// # Safety

0 commit comments

Comments
 (0)