winget_types/installer/
command.rs1use core::{fmt, str::FromStr};
2
3use compact_str::CompactString;
4use thiserror::Error;
5
6#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8#[cfg_attr(feature = "serde", serde(try_from = "CompactString"))]
9#[repr(transparent)]
10pub struct Command(CompactString);
11
12#[derive(Debug, Error, Eq, PartialEq)]
13pub enum CommandError {
14 #[error("Command must not be empty")]
15 Empty,
16 #[error(
17 "Command must not have more than {} characters but has {_0}",
18 Command::MAX_CHAR_LENGTH
19 )]
20 TooLong(usize),
21}
22
23impl Command {
24 pub const MAX_CHAR_LENGTH: usize = 40;
25
26 pub fn new<T: AsRef<str> + Into<CompactString>>(command: T) -> Result<Self, CommandError> {
47 let command_str = command.as_ref();
48
49 if command_str.is_empty() {
50 return Err(CommandError::Empty);
51 }
52
53 let char_count = command_str.chars().count();
54 if char_count > Self::MAX_CHAR_LENGTH {
55 return Err(CommandError::TooLong(char_count));
56 }
57
58 Ok(Self(command.into()))
59 }
60
61 #[must_use]
68 #[inline]
69 pub unsafe fn new_unchecked<T: Into<CompactString>>(command: T) -> Self {
70 Self(command.into())
71 }
72
73 #[must_use]
75 #[inline]
76 pub fn as_str(&self) -> &str {
77 self.0.as_str()
78 }
79}
80
81impl AsRef<str> for Command {
82 #[inline]
83 fn as_ref(&self) -> &str {
84 self.as_str()
85 }
86}
87
88impl fmt::Display for Command {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 self.0.fmt(f)
91 }
92}
93
94impl FromStr for Command {
95 type Err = CommandError;
96
97 #[inline]
98 fn from_str(s: &str) -> Result<Self, Self::Err> {
99 Self::new(s)
100 }
101}
102
103impl TryFrom<CompactString> for Command {
104 type Error = CommandError;
105
106 #[inline]
107 fn try_from(value: CompactString) -> Result<Self, Self::Error> {
108 Self::new(value)
109 }
110}