ytil_noxi/
extract.rs

1//! Primitive extraction trait implementations for Nvim `Object` kinds.
2
3use color_eyre::eyre::Context;
4use nvim_oxi::Dictionary;
5use nvim_oxi::Object;
6use nvim_oxi::ObjectKind;
7
8/// Trait for extracting typed values from Nvim objects.
9pub trait OxiExtract {
10    type Out;
11
12    /// Extracts a typed value from an Nvim [`Object`] by key from a [`Dictionary`] with error context.
13    ///
14    /// # Errors
15    /// - The value has a different kind than expected for the target type.
16    fn extract_from_dict(key: &str, value: &Object, dict: &Dictionary) -> color_eyre::Result<Self::Out>;
17}
18
19/// Implementation for extracting [`String`] values from Nvim objects.
20impl OxiExtract for nvim_oxi::String {
21    type Out = String;
22
23    /// Extract from dict.
24    fn extract_from_dict(key: &str, value: &Object, dict: &Dictionary) -> color_eyre::Result<Self::Out> {
25        let out = Self::try_from(value.clone())
26            .with_context(|| unexpected_kind_error_msg(value, key, dict, ObjectKind::String))?;
27        Ok(out.to_string())
28    }
29}
30
31/// Implementation for extracting [`i64`] values from Nvim objects.
32impl OxiExtract for nvim_oxi::Integer {
33    type Out = Self;
34
35    /// Extract from dict.
36    fn extract_from_dict(key: &str, value: &Object, dict: &Dictionary) -> color_eyre::Result<Self::Out> {
37        let out = Self::try_from(value.clone())
38            .with_context(|| unexpected_kind_error_msg(value, key, dict, ObjectKind::Integer))?;
39        Ok(out)
40    }
41}
42
43/// Generates an error message for unexpected [`Object`] kind.
44pub fn unexpected_kind_error_msg(obj: &Object, key: &str, dict: &Dictionary, expected_kind: ObjectKind) -> String {
45    format!(
46        "value {obj:#?} of key {key:?} in dict {dict:#?} is {0:#?} but {expected_kind:?} was expected",
47        obj.kind()
48    )
49}