justcode_core/
config.rs

1//! Configuration for encoding and decoding behavior.
2
3/// Configuration options for justcode encoding/decoding.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub struct Config {
6    /// Maximum size limit for deserialization (prevents memory exhaustion attacks).
7    /// If `None`, no limit is enforced.
8    pub limit: Option<usize>,
9    /// Use variable-length integer encoding for lengths and enum variants.
10    /// When enabled, small values use fewer bytes.
11    pub variable_int_encoding: bool,
12}
13
14impl Config {
15    /// Create a new configuration with default settings.
16    pub fn new() -> Self {
17        Self {
18            limit: None,
19            variable_int_encoding: true,
20        }
21    }
22
23    /// Set a maximum size limit for deserialization.
24    ///
25    /// This helps prevent memory exhaustion attacks by limiting
26    /// the amount of memory that can be allocated during decoding.
27    pub fn with_limit(mut self, limit: usize) -> Self {
28        self.limit = Some(limit);
29        self
30    }
31
32    /// Enable or disable variable-length integer encoding.
33    ///
34    /// When enabled, small integers and lengths are encoded using
35    /// fewer bytes (varint encoding). This is enabled by default.
36    pub fn with_variable_int_encoding(mut self, enabled: bool) -> Self {
37        self.variable_int_encoding = enabled;
38        self
39    }
40}
41
42impl Default for Config {
43    fn default() -> Self {
44        Self::new()
45    }
46}
47
48/// Standard configuration (same as default).
49///
50/// This is equivalent to `Config::new()` and provides:
51/// - Variable-length integer encoding enabled
52/// - No size limit (use `with_limit()` if needed for untrusted input)
53pub fn standard() -> Config {
54    Config::new()
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn test_config_default() {
63        let config = Config::default();
64        assert_eq!(config.variable_int_encoding, true);
65        assert_eq!(config.limit, None);
66    }
67
68    #[test]
69    fn test_config_with_limit() {
70        let config = Config::new().with_limit(1024);
71        assert_eq!(config.limit, Some(1024));
72    }
73
74    #[test]
75    fn test_config_with_variable_int_encoding() {
76        let config = Config::new().with_variable_int_encoding(false);
77        assert_eq!(config.variable_int_encoding, false);
78    }
79
80    #[test]
81    fn test_standard_config() {
82        let config = standard();
83        assert_eq!(config.variable_int_encoding, true);
84        assert_eq!(config.limit, None);
85    }
86
87    #[test]
88    fn test_config_chaining() {
89        let config = Config::new()
90            .with_limit(1024)
91            .with_variable_int_encoding(false);
92        assert_eq!(config.limit, Some(1024));
93        assert_eq!(config.variable_int_encoding, false);
94    }
95}
96