use super::ConfigError;
use crate::{KeyFile, RepoMode};
pub trait Value: Sized {
fn parse(raw: &str) -> Result<Self, ValueError>;
fn format(&self) -> String;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValueError {
kind: Kind,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Kind {
NotBoolean,
NotInteger,
KeyFile(String),
Invalid(String),
Malformed {
part: &'static str,
text: String,
why: String,
},
}
impl ValueError {
pub fn new(reason: impl Into<String>) -> ValueError {
ValueError {
kind: Kind::Invalid(reason.into()),
}
}
pub fn malformed_item(text: impl Into<String>, why: impl Into<String>) -> ValueError {
ValueError {
kind: Kind::Malformed {
part: "item",
text: text.into(),
why: why.into(),
},
}
}
pub fn malformed_value(text: impl Into<String>, why: impl Into<String>) -> ValueError {
ValueError {
kind: Kind::Malformed {
part: "value",
text: text.into(),
why: why.into(),
},
}
}
}
impl std::fmt::Display for ValueError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
Kind::NotBoolean => f.write_str("is not a boolean"),
Kind::NotInteger => f.write_str("is not an integer"),
Kind::KeyFile(text) | Kind::Invalid(text) => f.write_str(text),
Kind::Malformed { part, text, why } => write!(f, "malformed {part} '{text}': {why}"),
}
}
}
impl std::error::Error for ValueError {}
#[doc(hidden)]
pub fn value_error(group: &str, key: &str, raw: &str, err: ValueError) -> ConfigError {
match err.kind {
Kind::NotBoolean => ConfigError::Core(crate::Error::KeyFile(format!(
"value '{raw}' for {group}.{key} is not a boolean"
))),
Kind::NotInteger => ConfigError::Core(crate::Error::KeyFile(format!(
"value '{raw}' for {group}.{key} is not an integer"
))),
Kind::KeyFile(text) => ConfigError::Core(crate::Error::KeyFile(text)),
Kind::Invalid(reason) => ConfigError::InvalidFormat(format!("[{group}] {key} {reason}")),
Kind::Malformed { part, text, why } => {
ConfigError::InvalidFormat(format!("malformed [{group}] {key} {part} '{text}': {why}"))
}
}
}
fn keyfile_error(err: crate::Error) -> ValueError {
match err {
crate::Error::KeyFile(text) => ValueError {
kind: Kind::KeyFile(text),
},
other => ValueError {
kind: Kind::KeyFile(other.to_string()),
},
}
}
pub fn decode_string(raw: &str) -> Result<String, ValueError> {
KeyFile::decode_string(raw).map_err(keyfile_error)
}
pub fn encode_string(value: &str) -> String {
KeyFile::encode_string(value)
}
pub fn decode_bool(raw: &str) -> Result<bool, ValueError> {
KeyFile::decode_bool(raw).ok_or(ValueError {
kind: Kind::NotBoolean,
})
}
pub fn encode_bool(value: bool) -> String {
if value { "true" } else { "false" }.to_owned()
}
pub fn decode_integer(raw: &str) -> Result<i64, ValueError> {
KeyFile::decode_integer(raw).ok_or(ValueError {
kind: Kind::NotInteger,
})
}
pub fn encode_integer(value: i64) -> String {
value.to_string()
}
pub fn decode_string_list(raw: &str) -> Result<Vec<String>, ValueError> {
KeyFile::decode_string_list(raw).map_err(keyfile_error)
}
pub fn encode_string_list(items: &[impl AsRef<str>]) -> String {
KeyFile::encode_string_list(items)
}
impl Value for bool {
fn parse(raw: &str) -> Result<bool, ValueError> {
decode_bool(raw)
}
fn format(&self) -> String {
encode_bool(*self)
}
}
impl Value for i64 {
fn parse(raw: &str) -> Result<i64, ValueError> {
decode_integer(raw)
}
fn format(&self) -> String {
encode_integer(*self)
}
}
macro_rules! value_through_i64 {
($($int:ty),*) => {$(
impl Value for $int {
fn parse(raw: &str) -> Result<$int, ValueError> {
let n = decode_integer(raw)?;
<$int>::try_from(n).map_err(|_| {
ValueError::new(format!(
"{n} is out of the range {}-{}",
<$int>::MIN,
<$int>::MAX
))
})
}
fn format(&self) -> String {
self.to_string()
}
}
)*};
}
value_through_i64!(i8, i16, i32, u8, u16, u32);
impl Value for u64 {
fn parse(raw: &str) -> Result<u64, ValueError> {
let n = match decode_integer(raw) {
Ok(n) => n,
Err(err) if raw.starts_with('+') => return Err(err),
Err(err) => return raw.parse::<u64>().map_err(|_| err),
};
u64::try_from(n).map_err(|_| {
ValueError::new(format!("{n} is out of the range {}-{}", u64::MIN, u64::MAX))
})
}
fn format(&self) -> String {
self.to_string()
}
}
impl Value for String {
fn parse(raw: &str) -> Result<String, ValueError> {
decode_string(raw)
}
fn format(&self) -> String {
encode_string(self)
}
}
impl Value for Vec<String> {
fn parse(raw: &str) -> Result<Vec<String>, ValueError> {
decode_string_list(raw)
}
fn format(&self) -> String {
encode_string_list(self)
}
}
impl Value for RepoMode {
fn parse(raw: &str) -> Result<RepoMode, ValueError> {
let value = decode_string(raw)?;
RepoMode::from_mode_str(&value)
.ok_or_else(|| ValueError::new(format!("'{value}' names no repository mode")))
}
fn format(&self) -> String {
self.as_mode_str().to_owned()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn round_trips<V: Value + PartialEq + std::fmt::Debug>(value: V) {
let text = value.format();
assert_eq!(V::parse(&text), Ok(value), "{text:?}");
}
#[test]
fn helpers_decode_and_encode() {
assert_eq!(decode_string(r"a\sb\;c").unwrap(), "a b;c");
assert_eq!(
decode_string(r"\q").unwrap_err().to_string(),
r"invalid escape '\q'"
);
assert_eq!(encode_string(" a;b"), r"\s\sa;b");
assert_eq!(decode_bool("1"), Ok(true));
assert_eq!(decode_bool("0"), Ok(false));
assert_eq!(
decode_bool("yes").unwrap_err().to_string(),
"is not a boolean"
);
assert_eq!(encode_bool(true), "true");
assert_eq!(encode_bool(false), "false");
assert_eq!(decode_integer("-5"), Ok(-5));
assert_eq!(
decode_integer("+5").unwrap_err().to_string(),
"is not an integer"
);
assert_eq!(encode_integer(-5), "-5");
assert_eq!(
decode_string_list(r"a;b\;c;").unwrap(),
["a".to_owned(), "b;c".to_owned()]
);
assert_eq!(
decode_string_list("a\\").unwrap_err().to_string(),
"value ends with a lone backslash"
);
assert_eq!(encode_string_list(&["a", "b;c", " d"]), r"a;b\;c;\sd;");
}
#[test]
fn value_error_renders_with_the_group_and_the_key() {
let render = |err| value_error("core", "fsync", "x", err).to_string();
assert_eq!(
render(decode_bool("x").unwrap_err()),
"keyfile: value 'x' for core.fsync is not a boolean"
);
assert_eq!(
render(decode_integer("x").unwrap_err()),
"keyfile: value 'x' for core.fsync is not an integer"
);
assert_eq!(
render(decode_string(r"\q").unwrap_err()),
r"keyfile: invalid escape '\q'"
);
assert_eq!(
render(ValueError::new("is empty")),
"invalid format: [core] fsync is empty"
);
}
#[test]
fn bool_integer_and_text_values() {
assert_eq!(bool::parse("1"), Ok(true));
assert!(bool::parse("yes").is_err());
round_trips(true);
round_trips(false);
assert_eq!(i64::parse("-9223372036854775808"), Ok(i64::MIN));
round_trips(i64::MIN);
round_trips(i64::MAX);
assert_eq!(u8::parse("255"), Ok(255));
assert_eq!(
u8::parse("256").unwrap_err().to_string(),
"256 is out of the range 0-255"
);
assert_eq!(
i8::parse("-129").unwrap_err().to_string(),
"-129 is out of the range -128-127"
);
assert_eq!(
u32::parse("-1").unwrap_err().to_string(),
"-1 is out of the range 0-4294967295"
);
round_trips(7u16);
round_trips(-7i32);
assert_eq!(String::parse(r"\sa"), Ok(" a".to_owned()));
round_trips(" a\\b\nc;".to_owned());
round_trips(String::new());
assert_eq!(
Vec::<String>::parse("a;b;"),
Ok(vec!["a".to_owned(), "b".to_owned()])
);
round_trips(vec!["a;b".to_owned(), " c".to_owned(), String::new()]);
round_trips(Vec::<String>::new());
}
#[test]
fn u64_reads_its_full_range() {
let above = u64::try_from(i64::MAX).unwrap() + 1;
assert_eq!(u64::parse("9223372036854775808"), Ok(above));
assert_eq!(u64::parse("18446744073709551615"), Ok(u64::MAX));
for value in [0, u64::try_from(i64::MAX).unwrap(), above, u64::MAX] {
round_trips(value);
}
assert_eq!(
u64::parse("-1").unwrap_err().to_string(),
"-1 is out of the range 0-18446744073709551615"
);
for bad in [
"+1",
"+18446744073709551615",
"18446744073709551616",
"x",
"",
] {
assert_eq!(
u64::parse(bad).unwrap_err().to_string(),
"is not an integer",
"{bad:?}"
);
}
}
#[test]
fn mode_values() {
assert_eq!(RepoMode::parse("archive"), Ok(RepoMode::Archive));
assert_eq!(RepoMode::Archive.format(), "archive-z2");
assert_eq!(
RepoMode::parse("bogus").unwrap_err().to_string(),
"'bogus' names no repository mode"
);
for mode in [
RepoMode::Bare,
RepoMode::BareUser,
RepoMode::BareUserOnly,
RepoMode::BareSplitXattrs,
RepoMode::Archive,
RepoMode::BareUserShared,
RepoMode::BareUserPrivate,
] {
round_trips(mode);
}
}
#[test]
fn malformed_errors_render_with_the_group_and_the_key() {
let render = |err| value_error("ex-ostrya server", "listen", "x", err).to_string();
assert_eq!(
render(ValueError::malformed_item("x", "why")),
"invalid format: malformed [ex-ostrya server] listen item 'x': why"
);
assert_eq!(
render(ValueError::malformed_value("x", "why")),
"invalid format: malformed [ex-ostrya server] listen value 'x': why"
);
assert_eq!(
ValueError::malformed_item("x", "why").to_string(),
"malformed item 'x': why"
);
assert_eq!(
ValueError::malformed_value("x", "why").to_string(),
"malformed value 'x': why"
);
}
}