kpdb/types/
string_value.rs

1// Copyright (c) 2016-2017 Martijn Rijkeboer <mrr@sru-systems.com>
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use secstr::SecStr;
10
11/// A value for the map with strings.
12#[derive(Clone, Debug, PartialEq)]
13pub enum StringValue {
14    /// Plain string value.
15    Plain(String),
16
17    /// Protected string value.
18    Protected(SecStr),
19}
20
21impl StringValue {
22    /// Create a new string value.
23    ///
24    /// # Examples
25    ///
26    /// ```
27    /// use kpdb::StringValue;
28    ///
29    /// let plain_value = StringValue::new("plain", false);
30    /// let protected_value = StringValue::new("secret", true);
31    /// ```
32    pub fn new<S: Into<String>>(value: S, protected: bool) -> StringValue {
33        if protected {
34            StringValue::Protected(SecStr::from(value.into()))
35        } else {
36            StringValue::Plain(value.into())
37        }
38    }
39}
40
41#[cfg(test)]
42mod tests {
43
44    use super::*;
45    use secstr::SecStr;
46
47    #[test]
48    fn test_new_with_plain_value_returns_correct_string_value() {
49        let value = "FooBar";
50        let expected = StringValue::Plain(String::from(value));
51        let actual = StringValue::new(value, false);
52        assert_eq!(actual, expected);
53    }
54
55    #[test]
56    fn test_new_with_protected_value_returns_correct_string_value() {
57        let value = "FooBar";
58        let expected = StringValue::Protected(SecStr::from(value));
59        let actual = StringValue::new(value, true);
60        assert_eq!(actual, expected);
61    }
62}