Skip to main content

afia_component/
data_element_value.rs

1//! Types related to getting and setting an input element's value.
2
3use crate::dom::element::DomElement;
4
5/// An error when attempting to retrieve an input element's value.
6#[derive(Debug)]
7pub enum InputElementGetValueError {
8    /// The element was not an `<input>` element.
9    ElementIsNotHtmlInputElement,
10    /// The out buffer was smaller than the minimum allowed size.
11    OutBufferBelowMinimumSize,
12    /// The out buffer was smaller than the length of the input element's value.
13    #[allow(missing_docs)]
14    OutBufferSmallerThanValue { value_len: usize },
15    #[allow(missing_docs)]
16    Unrecognized { error_code: i32 },
17}
18
19impl DomElement {
20    /// Get the input element's value.
21    pub fn value<'out>(
22        &self,
23        out_buffer: &'out mut [u8],
24    ) -> Result<&'out str, InputElementGetValueError> {
25        let returned = unsafe {
26            afia_component_sys::input_element_value(
27                self.component_imports_ptr(),
28                self.to_i64(),
29                out_buffer.as_mut_ptr(),
30                out_buffer.len(),
31            )
32        };
33
34        match returned {
35            length if length >= 0 => {
36                let length = length as usize;
37
38                // SAFETY: here we are trusting that the Afia host worked as expected and wrote a
39                // utf8 string to the buffer.
40                let string = unsafe { std::str::from_utf8_unchecked(&out_buffer[0..length]) };
41
42                Ok(string)
43            }
44            -3 => Err(InputElementGetValueError::ElementIsNotHtmlInputElement),
45            -4 => Err(InputElementGetValueError::OutBufferBelowMinimumSize),
46            -5 => {
47                let mut val_len = [0; 4];
48                val_len.copy_from_slice(&out_buffer[0..4]);
49                let val = i32::from_le_bytes(val_len);
50                Err(InputElementGetValueError::OutBufferSmallerThanValue {
51                    value_len: val as usize,
52                })
53            }
54            unknown_error_code => Err(InputElementGetValueError::Unrecognized {
55                error_code: unknown_error_code,
56            }),
57        }
58    }
59}