Skip to main content

wdl_format/config/
max_line_length.rs

1//! Configuration for max line length formatting.
2
3use serde::Deserialize;
4use serde::Serialize;
5
6/// Error while creating a max line length configuration.
7#[derive(thiserror::Error, Debug)]
8pub enum MaxLineLengthError {
9    /// Supplied number outside allowed range.
10    #[error(
11        "`{0}` is outside the allowed range for the max line length ({min}-{max})",
12        min = MIN_MAX_LINE_LENGTH,
13        max = MAX_MAX_LINE_LENGTH
14    )]
15    OutsideAllowedRange(usize),
16}
17
18/// The default maximum line length.
19pub const DEFAULT_MAX_LINE_LENGTH: usize = 90;
20/// The minimum maximum line length.
21pub const MIN_MAX_LINE_LENGTH: usize = 60;
22/// The maximum maximum line length.
23pub const MAX_MAX_LINE_LENGTH: usize = 240;
24/// The max line length sentinel value meaning "no maximum".
25const SENTINEL: &str = "none";
26
27/// The maximum line length.
28#[derive(Clone, Copy, Debug, Eq, PartialEq)]
29pub struct MaxLineLength(Option<usize>);
30
31impl MaxLineLength {
32    /// Attempts to create a new `MaxLineLength` with the provided value.
33    pub fn try_new(value: Option<usize>) -> Result<Self, MaxLineLengthError> {
34        match value {
35            None => Ok(Self(None)),
36            Some(value) if (MIN_MAX_LINE_LENGTH..=MAX_MAX_LINE_LENGTH).contains(&value) => {
37                Ok(Self(Some(value)))
38            }
39            Some(value) => Err(MaxLineLengthError::OutsideAllowedRange(value)),
40        }
41    }
42
43    /// Gets the maximum line length. A value of `None` indicates no maximum.
44    pub fn get(&self) -> Option<usize> {
45        self.0
46    }
47}
48
49impl Default for MaxLineLength {
50    fn default() -> Self {
51        Self(Some(DEFAULT_MAX_LINE_LENGTH))
52    }
53}
54
55impl Serialize for MaxLineLength {
56    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
57    where
58        S: serde::Serializer,
59    {
60        match self {
61            MaxLineLength(None) => SENTINEL.serialize(serializer),
62            MaxLineLength(Some(n)) => n.serialize(serializer),
63        }
64    }
65}
66
67impl<'de> Deserialize<'de> for MaxLineLength {
68    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
69    where
70        D: serde::Deserializer<'de>,
71    {
72        #[derive(Deserialize)]
73        #[serde(untagged)]
74        enum Value {
75            Num(usize),
76            Str(String),
77            Null,
78        }
79
80        match Value::deserialize(deserializer)? {
81            Value::Num(n) => MaxLineLength::try_new(Some(n)).map_err(serde::de::Error::custom),
82            Value::Str(s) if s == SENTINEL => Ok(MaxLineLength(None)),
83            Value::Str(s) => Err(serde::de::Error::custom(format!(
84                "expected a number or \"{SENTINEL}\", got \"{s}\""
85            ))),
86            Value::Null => Ok(MaxLineLength(None)),
87        }
88    }
89}