Mercurial > crates > nonstick
diff src/conv.rs @ 79:2128123b9406
Format (oops!) and make some fun and/or stupid conversions available.
author | Paul Fisher <paul@pfish.zone> |
---|---|
date | Sun, 08 Jun 2025 04:21:58 -0400 |
parents | 002adfb98c5c |
children | 05291b601f0a |
line wrap: on
line diff
--- a/src/conv.rs Sun Jun 08 03:48:40 2025 -0400 +++ b/src/conv.rs Sun Jun 08 04:21:58 2025 -0400 @@ -160,55 +160,47 @@ ); /// Owned binary data. -/// -/// You can take ownership of the stored data by destructuring it: -/// -/// ``` -/// # use nonstick::BinaryData; -/// # let binary_data = BinaryData::new(vec![99, 88, 77], 66); -/// let (data, data_type) = binary_data.into(); -/// ``` #[derive(Debug, Default, PartialEq)] pub struct BinaryData { - data: Vec<u8>, - data_type: u8, + /// The data. + pub data: Vec<u8>, + /// A tag describing the type of the data, to use how you please. + pub data_type: u8, } impl BinaryData { /// Creates a `BinaryData` with the given contents and type. pub fn new(data: impl Into<Vec<u8>>, data_type: u8) -> Self { - Self { data: data.into(), data_type } + Self { + data: data.into(), + data_type, + } + } +} + +impl<IV: Into<Vec<u8>>> From<(IV, u8)> for BinaryData { + /// Makes a new BinaryData from borrowed data. + fn from((data, data_type): (IV, u8)) -> Self { + Self { + data: data.into(), + data_type, + } } } impl From<BinaryData> for (Vec<u8>, u8) { + /// Easy destructuring. fn from(value: BinaryData) -> Self { (value.data, value.data_type) } } -impl From<(&'_[u8], u8)> for BinaryData { - fn from((data, data_type): (&'_[u8], u8)) -> Self { - Self { - data: data.to_vec(), - data_type, - } - } -} - -impl<'a> From<&'a BinaryData> for (&'a[u8], u8) { +impl<'a> From<&'a BinaryData> for (&'a [u8], u8) { fn from(value: &'a BinaryData) -> Self { (&value.data, value.data_type) } } -impl From<BinaryData> for Vec<u8> { - /// Takes ownership of the data stored herein. - fn from(value: BinaryData) -> Self { - value.data - } -} - q_and_a!( InfoMsg<'a, Q = &'a str, A = ()>, Message::Info, @@ -517,7 +509,7 @@ conv.communicate(&[radio.message(), bin.message()]); assert_eq!("zero", radio.answer().unwrap()); - assert_eq!(BinaryData::new(vec![5, 5, 5], 5), bin.answer().unwrap()); + assert_eq!(BinaryData::from(([5, 5, 5], 5)), bin.answer().unwrap()); } fn test_mux() { @@ -546,7 +538,7 @@ } Message::BinaryPrompt(prompt) => { assert_eq!((&[1, 2, 3][..], 69), prompt.question()); - prompt.set_answer(Ok(BinaryData::new(vec![3, 2, 1], 42))) + prompt.set_answer(Ok(BinaryData::from((&[3, 2, 1], 42)))) } Message::RadioPrompt(ask) => { assert_eq!("radio?", ask.question());