gix_config_value/
boolean.rs1use std::{borrow::Cow, ffi::OsString, fmt::Display};
2
3use bstr::{BStr, BString, ByteSlice};
4
5use crate::{Boolean, Error};
6
7fn bool_err(input: impl Into<BString>) -> Error {
8 Error::new(
9 "Booleans need to be 'no', 'off', 'false', '' or 'yes', 'on', 'true' or any number",
10 input,
11 )
12}
13
14impl TryFrom<OsString> for Boolean {
15 type Error = Error;
16
17 fn try_from(value: OsString) -> Result<Self, Self::Error> {
18 let value = gix_path::os_str_into_bstr(&value)
19 .map_err(|_| Error::new("Illformed UTF-8", std::path::Path::new(&value).display().to_string()))?;
20 Self::try_from(value)
21 }
22}
23
24impl TryFrom<&BStr> for Boolean {
34 type Error = Error;
35
36 fn try_from(value: &BStr) -> Result<Self, Self::Error> {
37 if parse_true(value) {
38 Ok(Boolean(true))
39 } else if parse_false(value) {
40 Ok(Boolean(false))
41 } else {
42 use std::str::FromStr;
43 if let Some(integer) = value.to_str().ok().and_then(|s| i64::from_str(s).ok()) {
44 Ok(Boolean(integer != 0))
45 } else {
46 Err(bool_err(value))
47 }
48 }
49 }
50}
51
52impl TryFrom<&str> for Boolean {
53 type Error = Error;
54
55 fn try_from(value: &str) -> Result<Self, Self::Error> {
56 Self::try_from(BStr::new(value))
57 }
58}
59
60impl Boolean {
61 pub fn is_true(self) -> bool {
65 self.0
66 }
67}
68
69impl TryFrom<Cow<'_, BStr>> for Boolean {
70 type Error = Error;
71 fn try_from(c: Cow<'_, BStr>) -> Result<Self, Self::Error> {
72 Self::try_from(c.as_ref())
73 }
74}
75
76impl TryFrom<BString> for Boolean {
77 type Error = Error;
78 fn try_from(value: BString) -> Result<Self, Self::Error> {
79 Self::try_from(BStr::new(&value))
80 }
81}
82
83impl Display for Boolean {
84 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85 self.0.fmt(f)
86 }
87}
88
89impl From<Boolean> for bool {
90 fn from(b: Boolean) -> Self {
91 b.0
92 }
93}
94
95#[cfg(feature = "serde")]
96impl serde::Serialize for Boolean {
97 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
98 where
99 S: serde::Serializer,
100 {
101 serializer.serialize_bool(self.0)
102 }
103}
104
105fn parse_true(value: &BStr) -> bool {
106 value.eq_ignore_ascii_case(b"yes") || value.eq_ignore_ascii_case(b"on") || value.eq_ignore_ascii_case(b"true")
107}
108
109fn parse_false(value: &BStr) -> bool {
110 value.eq_ignore_ascii_case(b"no")
111 || value.eq_ignore_ascii_case(b"off")
112 || value.eq_ignore_ascii_case(b"false")
113 || value.is_empty()
114}