Skip to main content

grafton_ndi/advanced/
config.rs

1use std::{fmt, sync::Arc};
2
3use crate::{Error, Result};
4
5/// The JSON configuration of one Advanced SDK object.
6///
7/// The SDK accepts a JSON document when it creates a sender, receiver, finder
8/// and several other objects; the document's properties are defined by the
9/// NDI Advanced SDK documentation. This type holds one such document: it is
10/// checked to be a JSON object, kept byte for byte (unknown properties
11/// included), immutable, and cheap to clone. Most objects take it through an
12/// options value's `config` setter, such as
13/// [`SenderOptions::config`](crate::SenderOptions::config).
14/// Genlock uses [`GenlockOptions::config`](super::GenlockOptions::config).
15///
16/// A configuration can carry vendor credentials or network details, so its
17/// `Debug` output shows no content and no error message quotes it.
18///
19/// # Examples
20///
21/// ```
22/// use grafton_ndi::advanced::AdvancedConfig;
23///
24/// let config = AdvancedConfig::parse(r#"{"ndi": {"machinename": "studio-a"}}"#)?;
25/// assert_eq!(format!("{config:?}"), "AdvancedConfig([REDACTED])");
26/// # Ok::<(), grafton_ndi::Error>(())
27/// ```
28#[derive(Clone, PartialEq, Eq, Hash)]
29pub struct AdvancedConfig(Arc<str>);
30
31impl AdvancedConfig {
32    /// Accept a JSON object of at most one mebibyte.
33    ///
34    /// # Errors
35    ///
36    /// [`Error::InvalidInput`] when the text is too large, is not
37    /// valid JSON (including a raw NUL byte), or is not an object.
38    pub fn parse(json: impl AsRef<str>) -> Result<Self> {
39        Self::parse_with_limit(json, 1024 * 1024)
40    }
41
42    /// Accept a JSON object of at most `maximum_bytes` bytes.
43    ///
44    /// # Errors
45    ///
46    /// As for [`parse`](Self::parse).
47    pub fn parse_with_limit(json: impl AsRef<str>, maximum_bytes: usize) -> Result<Self> {
48        let json = json.as_ref();
49        if json.len() > maximum_bytes {
50            return Err(Error::InvalidInput(
51                crate::InputDefect::ConfigurationTooLarge,
52            ));
53        }
54        let value: serde_json::Value = serde_json::from_str(json)
55            .map_err(|_| Error::InvalidInput(crate::InputDefect::ConfigurationJson))?;
56        if !value.is_object() {
57            return Err(Error::InvalidInput(
58                crate::InputDefect::ConfigurationNotObject,
59            ));
60        }
61        let mut terminated = String::with_capacity(json.len() + 1);
62        terminated.push_str(json);
63        terminated.push('\0');
64        Ok(Self(Arc::from(terminated)))
65    }
66
67    /// The JSON text exactly as it was given. It may contain vendor
68    /// credentials or network details; the name is a reminder not to log it.
69    pub fn expose_json(&self) -> &str {
70        &self.0[..self.0.len() - 1]
71    }
72
73    /// Lend the exact buffer, or NULL for the SDK's default configuration.
74    /// Retain the returned owner until the native instance is destroyed.
75    pub(crate) fn lend<R>(
76        config: Option<&Self>,
77        call: impl FnOnce(*const std::ffi::c_char) -> R,
78    ) -> (R, RetainedConfig) {
79        let config = config.cloned();
80        let result = call(config.as_ref().map_or(std::ptr::null(), Self::as_ptr));
81        (result, RetainedConfig { _config: config })
82    }
83
84    /// The text as a C string. Every clone shares this one buffer, which
85    /// neither moves nor is freed while any clone of `self` lives.
86    fn as_ptr(&self) -> *const std::ffi::c_char {
87        self.0.as_ptr().cast()
88    }
89}
90
91/// The configuration that was lent to an SDK creation call.
92#[derive(Default)]
93pub(crate) struct RetainedConfig {
94    _config: Option<AdvancedConfig>,
95}
96
97impl fmt::Debug for AdvancedConfig {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        f.write_str("AdvancedConfig([REDACTED])")
100    }
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    #[test]
108    fn retains_extensions_and_redacts_values() {
109        let input = r#" {"ndi":{"vendor":{"id":"private-value"}},"future":[1,2]} "#;
110        let config = AdvancedConfig::parse(input).unwrap();
111        assert_eq!(config.expose_json(), input);
112        assert!(!format!("{config:?}").contains("private-value"));
113        assert!(AdvancedConfig::parse("[1]").is_err());
114        assert!(AdvancedConfig::parse_with_limit(input, 3).is_err());
115        let error = AdvancedConfig::parse("{\"private-value\":").unwrap_err();
116        assert!(!error.to_string().contains("private-value"));
117    }
118
119    #[test]
120    fn rust_and_native_views_share_the_exact_terminated_utf8() {
121        let input = " {\"label\":\"カメラ\",\"escaped\":\"\\u0000\"} ";
122        let config = AdvancedConfig::parse(input).unwrap();
123        let clone = config.clone();
124        assert_eq!(config.as_ptr(), clone.as_ptr());
125        // SAFETY: construction appends the sole NUL to the shared UTF-8 buffer.
126        let native = unsafe { std::ffi::CStr::from_ptr(config.as_ptr()) };
127        assert_eq!(native.to_str().unwrap(), input);
128        assert_eq!(native.to_bytes(), config.expose_json().as_bytes());
129        assert_eq!(config.expose_json().as_ptr(), config.as_ptr().cast());
130        // Raw NUL is invalid JSON at every position, including before and
131        // after the object. An escaped \\u0000 remains valid above.
132        for position in 0..=input.len() {
133            if input.is_char_boundary(position) {
134                let mut with_nul = input.to_owned();
135                with_nul.insert(position, '\0');
136                assert!(matches!(
137                    AdvancedConfig::parse(with_nul),
138                    Err(Error::InvalidInput(crate::InputDefect::ConfigurationJson))
139                ));
140            }
141        }
142    }
143
144    #[test]
145    fn lending_keeps_the_same_buffer_alive_and_passes_null_when_unset() {
146        let (pointer, retained) = AdvancedConfig::lend(None, |pointer| pointer);
147        assert!(pointer.is_null());
148        assert!(retained._config.is_none());
149
150        let input = r#"{"ndi":{}}"#;
151        let given = AdvancedConfig::parse(input).unwrap();
152        let (pointer, retained) = AdvancedConfig::lend(Some(&given), |pointer| pointer);
153        assert_eq!(pointer, given.as_ptr());
154        let buffer = Arc::downgrade(&given.0);
155        drop(given);
156        // SAFETY: the retained owner keeps this exact buffer alive.
157        assert_eq!(
158            unsafe { std::ffi::CStr::from_ptr(pointer) }
159                .to_str()
160                .unwrap(),
161            input
162        );
163        assert!(buffer.upgrade().is_some());
164        drop(retained);
165        assert!(buffer.upgrade().is_none());
166    }
167}