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
20impl fmt::Display for GenericSetting {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        write!(f, "{}{}={}", self.meta.comment, self.key, self.value)
23    }
24}
25
26impl GenericSetting {
27    #[must_use]
28    pub fn key(&self) -> &str {
29        &self.key
30    }
31
32    #[must_use]
33    pub fn value(&self) -> &str {
34        &self.value
35    }
36
37    pub fn new(
38        key: &str,
39        value: &str,
40        source_config: &std::path::Path,
41        comment: &mut String,
42    ) -> Self {
43        Self {
44            meta: GameSettingMeta {
45                source_config: source_config.to_path_buf(),
46                comment: std::mem::take(comment),
47            },
48            key: key.to_string(),
49            value: value.to_string(),
50        }
51    }
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57    use std::path::PathBuf;
58
59    #[test]
60    fn test_new_consumes_comment_and_tracks_source() {
61        let source = PathBuf::from("/tmp/openmw.cfg");
62        let mut comment = String::from("# heading\n");
63
64        let setting = GenericSetting::new("unknown-key", "value", &source, &mut comment);
65
66        assert_eq!(setting.meta().source_config, source);
67        assert_eq!(setting.meta().comment, "# heading\n");
68        assert!(comment.is_empty());
69    }
70
71    #[test]
72    fn test_display_emits_comment_and_pair() {
73        let source = PathBuf::from("/tmp/openmw.cfg");
74        let mut comment = String::from("# comment\n");
75
76        let setting = GenericSetting::new("foo", "bar", &source, &mut comment);
77        assert_eq!(setting.to_string(), "# comment\nfoo=bar");
78    }
79}