1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum ApiPrimitiveError {
10 Empty,
12 Invalid,
14 Unknown,
16}
17
18impl fmt::Display for ApiPrimitiveError {
19 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
20 match self {
21 Self::Empty => formatter.write_str("API primitive value cannot be empty"),
22 Self::Invalid => formatter.write_str("invalid API primitive value"),
23 Self::Unknown => formatter.write_str("unknown API primitive label"),
24 }
25 }
26}
27
28impl Error for ApiPrimitiveError {}
29
30fn validate_api_text(value: &str) -> Result<&str, ApiPrimitiveError> {
31 let trimmed = value.trim();
32 if trimmed.is_empty() {
33 return Err(ApiPrimitiveError::Empty);
34 }
35 if trimmed.chars().any(char::is_control) {
36 return Err(ApiPrimitiveError::Invalid);
37 }
38 Ok(trimmed)
39}
40
41macro_rules! text_newtype {
42 ($name:ident) => {
43 #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
44 pub struct $name(String);
45
46 impl $name {
47 pub fn new(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
53 validate_api_text(value.as_ref()).map(|value| Self(value.to_owned()))
54 }
55
56 pub fn parse(value: impl AsRef<str>) -> Result<Self, ApiPrimitiveError> {
62 Self::new(value)
63 }
64
65 #[must_use]
67 pub fn as_str(&self) -> &str {
68 &self.0
69 }
70
71 #[must_use]
73 pub fn into_string(self) -> String {
74 self.0
75 }
76 }
77
78 impl AsRef<str> for $name {
79 fn as_ref(&self) -> &str {
80 self.as_str()
81 }
82 }
83
84 impl fmt::Display for $name {
85 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86 formatter.write_str(self.as_str())
87 }
88 }
89
90 impl FromStr for $name {
91 type Err = ApiPrimitiveError;
92
93 fn from_str(value: &str) -> Result<Self, Self::Err> {
94 Self::new(value)
95 }
96 }
97
98 impl TryFrom<&str> for $name {
99 type Error = ApiPrimitiveError;
100
101 fn try_from(value: &str) -> Result<Self, Self::Error> {
102 Self::new(value)
103 }
104 }
105 };
106}
107
108text_newtype!(OpaqueCursor);
109text_newtype!(BeforeCursor);
110text_newtype!(AfterCursor);
111text_newtype!(NextCursor);
112text_newtype!(PreviousCursor);
113
114#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
116pub enum CursorDirection {
117 Forward,
119 Backward,
121}
122
123impl CursorDirection {
124 #[must_use]
126 pub const fn as_str(self) -> &'static str {
127 match self {
128 Self::Forward => "forward",
129 Self::Backward => "backward",
130 }
131 }
132}
133
134impl Default for CursorDirection {
135 fn default() -> Self {
136 Self::Forward
137 }
138}
139
140impl fmt::Display for CursorDirection {
141 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
142 formatter.write_str(self.as_str())
143 }
144}
145
146impl FromStr for CursorDirection {
147 type Err = ApiPrimitiveError;
148
149 fn from_str(value: &str) -> Result<Self, Self::Err> {
150 let trimmed = value.trim();
151 if trimmed.is_empty() {
152 return Err(ApiPrimitiveError::Empty);
153 }
154 let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
155 match normalized.as_str() {
156 "forward" => Ok(Self::Forward),
157 "backward" => Ok(Self::Backward),
158 _ => Err(ApiPrimitiveError::Unknown),
159 }
160 }
161}
162
163#[derive(Clone, Debug, Eq, PartialEq)]
165pub struct PrimitiveMetadata {
166 name: OpaqueCursor,
167 kind: CursorDirection,
168}
169
170impl PrimitiveMetadata {
171 #[must_use]
173 pub const fn new(name: OpaqueCursor, kind: CursorDirection) -> Self {
174 Self { name, kind }
175 }
176
177 #[must_use]
179 pub const fn name(&self) -> &OpaqueCursor {
180 &self.name
181 }
182
183 #[must_use]
185 pub const fn kind(&self) -> CursorDirection {
186 self.kind
187 }
188}
189
190#[cfg(test)]
191mod tests {
192 use super::*;
193
194 #[test]
195 fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
196 let value = OpaqueCursor::new("opaque-cursor")?;
197
198 assert_eq!(value.as_str(), "opaque-cursor");
199 assert_eq!(value.to_string(), "opaque-cursor");
200 assert_eq!("opaque-cursor".parse::<OpaqueCursor>()?, value);
201 Ok(())
202 }
203
204 #[test]
205 fn rejects_empty_text() {
206 assert_eq!(OpaqueCursor::new(""), Err(ApiPrimitiveError::Empty));
207 }
208
209 #[test]
210 fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
211 let kind = "forward".parse::<CursorDirection>()?;
212
213 assert_eq!(kind, CursorDirection::Forward);
214 assert_eq!(kind.to_string(), "forward");
215 Ok(())
216 }
217
218 #[test]
219 fn creates_metadata() -> Result<(), ApiPrimitiveError> {
220 let metadata = PrimitiveMetadata::new(
221 OpaqueCursor::new("opaque-cursor")?,
222 CursorDirection::default(),
223 );
224
225 assert_eq!(metadata.name().as_str(), "opaque-cursor");
226 assert_eq!(metadata.kind(), CursorDirection::default());
227 Ok(())
228 }
229}