grafton_ndi/advanced/
config.rs1use std::{fmt, sync::Arc};
2
3use crate::{Error, Result};
4
5#[derive(Clone, PartialEq, Eq, Hash)]
29pub struct AdvancedConfig(Arc<str>);
30
31impl AdvancedConfig {
32 pub fn parse(json: impl AsRef<str>) -> Result<Self> {
39 Self::parse_with_limit(json, 1024 * 1024)
40 }
41
42 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 pub fn expose_json(&self) -> &str {
70 &self.0[..self.0.len() - 1]
71 }
72
73 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 fn as_ptr(&self) -> *const std::ffi::c_char {
87 self.0.as_ptr().cast()
88 }
89}
90
91#[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 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 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 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}