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!(SchemaName);
109text_newtype!(SchemaFieldName);
110
111#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
113pub enum FieldKind {
114 String,
116 Number,
118 Integer,
120 Boolean,
122 Array,
124 Object,
126 Null,
128 Custom,
130}
131
132impl FieldKind {
133 #[must_use]
135 pub const fn as_str(self) -> &'static str {
136 match self {
137 Self::String => "string",
138 Self::Number => "number",
139 Self::Integer => "integer",
140 Self::Boolean => "boolean",
141 Self::Array => "array",
142 Self::Object => "object",
143 Self::Null => "null",
144 Self::Custom => "custom",
145 }
146 }
147}
148
149impl Default for FieldKind {
150 fn default() -> Self {
151 Self::String
152 }
153}
154
155impl fmt::Display for FieldKind {
156 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
157 formatter.write_str(self.as_str())
158 }
159}
160
161impl FromStr for FieldKind {
162 type Err = ApiPrimitiveError;
163
164 fn from_str(value: &str) -> Result<Self, Self::Err> {
165 let trimmed = value.trim();
166 if trimmed.is_empty() {
167 return Err(ApiPrimitiveError::Empty);
168 }
169 let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
170 match normalized.as_str() {
171 "string" => Ok(Self::String),
172 "number" => Ok(Self::Number),
173 "integer" => Ok(Self::Integer),
174 "boolean" => Ok(Self::Boolean),
175 "array" => Ok(Self::Array),
176 "object" => Ok(Self::Object),
177 "null" => Ok(Self::Null),
178 "custom" => Ok(Self::Custom),
179 _ => Err(ApiPrimitiveError::Unknown),
180 }
181 }
182}
183#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
185pub enum FieldRequirement {
186 Required,
188 Optional,
190}
191
192impl FieldRequirement {
193 #[must_use]
195 pub const fn as_str(self) -> &'static str {
196 match self {
197 Self::Required => "required",
198 Self::Optional => "optional",
199 }
200 }
201}
202
203impl Default for FieldRequirement {
204 fn default() -> Self {
205 Self::Required
206 }
207}
208
209impl fmt::Display for FieldRequirement {
210 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
211 formatter.write_str(self.as_str())
212 }
213}
214
215impl FromStr for FieldRequirement {
216 type Err = ApiPrimitiveError;
217
218 fn from_str(value: &str) -> Result<Self, Self::Err> {
219 let trimmed = value.trim();
220 if trimmed.is_empty() {
221 return Err(ApiPrimitiveError::Empty);
222 }
223 let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
224 match normalized.as_str() {
225 "required" => Ok(Self::Required),
226 "optional" => Ok(Self::Optional),
227 _ => Err(ApiPrimitiveError::Unknown),
228 }
229 }
230}
231#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
233pub enum Nullability {
234 Nullable,
236 NonNullable,
238}
239
240impl Nullability {
241 #[must_use]
243 pub const fn as_str(self) -> &'static str {
244 match self {
245 Self::Nullable => "nullable",
246 Self::NonNullable => "non-nullable",
247 }
248 }
249}
250
251impl Default for Nullability {
252 fn default() -> Self {
253 Self::Nullable
254 }
255}
256
257impl fmt::Display for Nullability {
258 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
259 formatter.write_str(self.as_str())
260 }
261}
262
263impl FromStr for Nullability {
264 type Err = ApiPrimitiveError;
265
266 fn from_str(value: &str) -> Result<Self, Self::Err> {
267 let trimmed = value.trim();
268 if trimmed.is_empty() {
269 return Err(ApiPrimitiveError::Empty);
270 }
271 let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
272 match normalized.as_str() {
273 "nullable" => Ok(Self::Nullable),
274 "non-nullable" => Ok(Self::NonNullable),
275 _ => Err(ApiPrimitiveError::Unknown),
276 }
277 }
278}
279#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
281pub enum SchemaShape {
282 Scalar,
284 Array,
286 Object,
288}
289
290impl SchemaShape {
291 #[must_use]
293 pub const fn as_str(self) -> &'static str {
294 match self {
295 Self::Scalar => "scalar",
296 Self::Array => "array",
297 Self::Object => "object",
298 }
299 }
300}
301
302impl Default for SchemaShape {
303 fn default() -> Self {
304 Self::Scalar
305 }
306}
307
308impl fmt::Display for SchemaShape {
309 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
310 formatter.write_str(self.as_str())
311 }
312}
313
314impl FromStr for SchemaShape {
315 type Err = ApiPrimitiveError;
316
317 fn from_str(value: &str) -> Result<Self, Self::Err> {
318 let trimmed = value.trim();
319 if trimmed.is_empty() {
320 return Err(ApiPrimitiveError::Empty);
321 }
322 let normalized = trimmed.to_ascii_lowercase().replace('_', "-");
323 match normalized.as_str() {
324 "scalar" => Ok(Self::Scalar),
325 "array" => Ok(Self::Array),
326 "object" => Ok(Self::Object),
327 _ => Err(ApiPrimitiveError::Unknown),
328 }
329 }
330}
331
332#[derive(Clone, Debug, Eq, PartialEq)]
334pub struct PrimitiveMetadata {
335 name: SchemaName,
336 kind: FieldKind,
337}
338
339impl PrimitiveMetadata {
340 #[must_use]
342 pub const fn new(name: SchemaName, kind: FieldKind) -> Self {
343 Self { name, kind }
344 }
345
346 #[must_use]
348 pub const fn name(&self) -> &SchemaName {
349 &self.name
350 }
351
352 #[must_use]
354 pub const fn kind(&self) -> FieldKind {
355 self.kind
356 }
357}
358
359#[derive(Clone, Debug, Eq, PartialEq)]
361pub struct SchemaField {
362 name: SchemaFieldName,
363 kind: FieldKind,
364 requirement: FieldRequirement,
365 nullability: Nullability,
366}
367
368impl SchemaField {
369 #[must_use]
371 pub const fn new(name: SchemaFieldName, kind: FieldKind) -> Self {
372 Self {
373 name,
374 kind,
375 requirement: FieldRequirement::Optional,
376 nullability: Nullability::NonNullable,
377 }
378 }
379
380 #[must_use]
382 pub const fn required(mut self) -> Self {
383 self.requirement = FieldRequirement::Required;
384 self
385 }
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391
392 #[test]
393 fn parses_and_displays_text() -> Result<(), ApiPrimitiveError> {
394 let value = SchemaName::new("User")?;
395
396 assert_eq!(value.as_str(), "User");
397 assert_eq!(value.to_string(), "User");
398 assert_eq!("User".parse::<SchemaName>()?, value);
399 Ok(())
400 }
401
402 #[test]
403 fn rejects_empty_text() {
404 assert_eq!(SchemaName::new(""), Err(ApiPrimitiveError::Empty));
405 }
406
407 #[test]
408 fn parses_and_displays_labels() -> Result<(), ApiPrimitiveError> {
409 let kind = "string".parse::<FieldKind>()?;
410
411 assert_eq!(kind, FieldKind::String);
412 assert_eq!(kind.to_string(), "string");
413 Ok(())
414 }
415
416 #[test]
417 fn creates_metadata() -> Result<(), ApiPrimitiveError> {
418 let metadata = PrimitiveMetadata::new(SchemaName::new("User")?, FieldKind::default());
419
420 assert_eq!(metadata.name().as_str(), "User");
421 assert_eq!(metadata.kind(), FieldKind::default());
422 Ok(())
423 }
424}