Skip to main content

openmw_config/config/
genericsetting.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// Copyright (c) 2025 Dave Corley (S3kshun8)
3
4use crate::{GameSetting, GameSettingMeta};
5use std::fmt;
6
7#[derive(Debug, Clone)]
8pub struct GenericSetting {
9    meta: GameSettingMeta,
10    key: String,
11    value: String,
12}
13
14impl GameSetting for GenericSetting {
15    fn meta(&self) -> &GameSettingMeta {
16        &self.meta
17    }
18
19    fn meta_mut(&mut self) -> &mut GameSettingMeta {
20        &mut self.meta
21    }
22}
23
24impl fmt::Display for GenericSetting {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        write!(f, "{}{}={}", self.meta.comment, self.key, self.value)
27    }
28}
29
30impl GenericSetting {
31    #[must_use]
32    pub fn key(&self) -> &str {
33        &self.key
34    }
35
36    #[must_use]
37    pub fn value(&self) -> &str {
38        &self.value
39    }
40
41    /// The file that defined the entry and the comment above it.
42    #[must_use]
43    pub fn meta(&self) -> &GameSettingMeta {
44        &self.meta
45    }
46
47    pub fn new(
48        key: &str,
49        value: &str,
50        source_config: &std::path::Path,
51        comment: &mut String,
52    ) -> Self {
53        Self {
54            meta: GameSettingMeta {
55                source_config: source_config.to_path_buf(),
56                comment: std::mem::take(comment),
57            },
58            key: key.to_string(),
59            value: value.to_string(),
60        }
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67    use std::path::PathBuf;
68
69    #[test]
70    fn test_new_consumes_comment_and_tracks_source() {
71        let source = PathBuf::from("/tmp/openmw.cfg");
72        let mut comment = String::from("# heading\n");
73
74        let setting = GenericSetting::new("unknown-key", "value", &source, &mut comment);
75
76        assert_eq!(setting.meta().source_config, source);
77        assert_eq!(setting.meta().comment, "# heading\n");
78        assert!(comment.is_empty());
79    }
80
81    #[test]
82    fn test_display_emits_comment_and_pair() {
83        let source = PathBuf::from("/tmp/openmw.cfg");
84        let mut comment = String::from("# comment\n");
85
86        let setting = GenericSetting::new("foo", "bar", &source, &mut comment);
87        assert_eq!(setting.to_string(), "# comment\nfoo=bar");
88    }
89}