Skip to content

Commit

Permalink
Add ua::Array::into_array() helper (#106)
Browse files Browse the repository at this point in the history
## Description

This is a follow-up to #105 and adds a helper method that is useful when
we deal mainly with arrays of a known size (this is usually the case for
PLCs which avoid dynamic memory allocation).

Co-authored-by: Uwe Klotz <uwe.klotz@gmail.com>
  • Loading branch information
sgoll and uklotzde committed May 8, 2024
1 parent a182495 commit 4b4fb6e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -14,6 +14,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- Add `serde` serialization for `ua::Array` and `ua::Variant` with array value.
- Add constructors `ua::Variant::scalar()` and `ua::Variant::array()`.
- Add constructor `ua::DataValue::new()`.
- Add helper method `ua::Array::into_array()` for conversion into native Rust array.

### Changed

Expand Down
23 changes: 23 additions & 0 deletions src/ua/array.rs
Expand Up @@ -266,6 +266,15 @@ impl<T: DataType> Array<T> {
self.drain_all().collect()
}

/// Converts the array into a native Rust array.
///
/// This avoids cloning the contained values and moves them into the array directly. When the
/// number of array elements does not match, this returns `None`.
#[must_use]
pub fn into_array<const N: usize>(self) -> Option<[T; N]> {
<[T; N]>::try_from(self.into_vec()).ok()
}

/// Gives up ownership and returns raw parts.
///
/// The returned raw parts must be deallocated with [`UA_Array_delete()`] to prevent leaking any
Expand Down Expand Up @@ -399,6 +408,20 @@ mod tests {
drop(array);
}

#[test]
fn convert_array() {
let array = ua::Array::from_slice(&[1, 2, 3].map(ua::Byte::new));
let wrong: Option<[ua::Byte; 4]> = array.into_array();
assert!(wrong.is_none());

let array = ua::Array::from_slice(&[1, 2, 3].map(ua::Byte::new));
let right: Option<[ua::Byte; 3]> = array.into_array();
assert_eq!(
Some([ua::Byte::new(1), ua::Byte::new(2), ua::Byte::new(3)]),
right
);
}

#[test]
fn print_array() {
let array = ua::Array::from_slice(&[1, 2, 3].map(ua::Byte::new));
Expand Down

0 comments on commit 4b4fb6e

Please sign in to comment.