use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;
const MAX_LEN: usize = 32;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct OperationSubType(Cow<'static, str>);
impl OperationSubType {
pub const STEP: OperationSubType = Self(Cow::Borrowed(crate::step::STEP_SUB_TYPE));
pub const WAIT: OperationSubType = Self(Cow::Borrowed(crate::wait::WAIT_SUB_TYPE));
pub const CALLBACK: OperationSubType = Self(Cow::Borrowed(crate::callback::CALLBACK_SUB_TYPE));
pub const RUN_IN_CHILD_CONTEXT: OperationSubType =
Self(Cow::Borrowed(crate::child::CHILD_SUB_TYPE));
pub const MAP: OperationSubType = Self(Cow::Borrowed(crate::map_parallel::MAP_SUB_TYPE));
pub const MAP_ITERATION: OperationSubType =
Self(Cow::Borrowed(crate::map_parallel::MAP_ITERATION_SUB_TYPE));
pub const PARALLEL: OperationSubType =
Self(Cow::Borrowed(crate::map_parallel::PARALLEL_SUB_TYPE));
pub const PARALLEL_BRANCH: OperationSubType =
Self(Cow::Borrowed(crate::map_parallel::PARALLEL_BRANCH_SUB_TYPE));
pub const WAIT_FOR_CALLBACK: OperationSubType =
Self(Cow::Borrowed(crate::callback::WFCB_SUB_TYPE));
pub const WAIT_FOR_CONDITION: OperationSubType =
Self(Cow::Borrowed(crate::wait_for_condition::WFC_SUB_TYPE));
pub const CHAINED_INVOKE: OperationSubType =
Self(Cow::Borrowed(crate::invoke::CHAINED_INVOKE_SUB_TYPE));
pub fn new(value: impl Into<String>) -> Result<OperationSubType, InvalidOperationSubType> {
let value = value.into();
let valid = (1..=MAX_LEN).contains(&value.len())
&& value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
if valid {
Ok(Self(Cow::Owned(value)))
} else {
Err(InvalidOperationSubType { value })
}
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl FromStr for OperationSubType {
type Err = InvalidOperationSubType;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::new(s)
}
}
impl TryFrom<&str> for OperationSubType {
type Error = InvalidOperationSubType;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl TryFrom<String> for OperationSubType {
type Error = InvalidOperationSubType;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl AsRef<str> for OperationSubType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for OperationSubType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct InvalidOperationSubType {
value: String,
}
impl InvalidOperationSubType {
pub fn value(&self) -> &str {
&self.value
}
}
impl fmt::Display for InvalidOperationSubType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"invalid subtype {:?}: must be 1 to 32 characters from A-Z, a-z, 0-9, hyphen and underscore",
self.value
)
}
}
impl std::error::Error for InvalidOperationSubType {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sub_type_new_cases() {
let a32 = "a".repeat(32);
let a33 = "a".repeat(33);
let ok: [(String, Option<OperationSubType>); 3] = [
("Payment-1_x".to_owned(), None),
(a32, None),
("Step".to_owned(), Some(OperationSubType::STEP)),
];
for (value, expected) in ok {
let parsed = OperationSubType::new(value.as_str()).expect("a valid value is accepted");
assert_eq!(parsed.as_str(), value);
if let Some(expected) = expected {
assert_eq!(parsed, expected);
}
}
let bad = [
String::new(),
a33,
"a b".to_owned(),
"a.b".to_owned(),
"é".to_owned(),
"ok\n".to_owned(),
];
for value in bad {
let err = OperationSubType::new(value.as_str())
.expect_err(&format!("{value:?} must be rejected"));
assert_eq!(err.value(), value);
}
let row1 = String::from("Payment-1_x");
let expected = OperationSubType::new(row1.as_str()).unwrap();
assert_eq!(
row1.as_str().parse::<OperationSubType>(),
Ok(expected.clone())
);
assert_eq!(
OperationSubType::try_from(row1.as_str()),
Ok(expected.clone())
);
assert_eq!(OperationSubType::try_from(row1.clone()), Ok(expected));
let row4 = String::new();
assert_eq!(
row4.as_str()
.parse::<OperationSubType>()
.unwrap_err()
.value(),
""
);
assert_eq!(
OperationSubType::try_from(row4.as_str())
.unwrap_err()
.value(),
""
);
assert_eq!(OperationSubType::try_from(row4).unwrap_err().value(), "");
}
#[test]
fn built_in_constants_match_js_names() {
let cases = [
(OperationSubType::STEP, "Step"),
(OperationSubType::WAIT, "Wait"),
(OperationSubType::CALLBACK, "Callback"),
(OperationSubType::RUN_IN_CHILD_CONTEXT, "RunInChildContext"),
(OperationSubType::MAP, "Map"),
(OperationSubType::MAP_ITERATION, "MapIteration"),
(OperationSubType::PARALLEL, "Parallel"),
(OperationSubType::PARALLEL_BRANCH, "ParallelBranch"),
(OperationSubType::WAIT_FOR_CALLBACK, "WaitForCallback"),
(OperationSubType::WAIT_FOR_CONDITION, "WaitForCondition"),
(OperationSubType::CHAINED_INVOKE, "ChainedInvoke"),
];
for (constant, name) in cases {
assert_eq!(constant.as_str(), name);
assert_eq!(constant.as_ref(), name);
assert_eq!(constant.to_string(), name);
assert_eq!(OperationSubType::new(name), Ok(constant));
}
}
#[test]
fn invalid_sub_type_display_names_the_rule() {
let err = OperationSubType::new("a b").unwrap_err();
assert_eq!(
err.to_string(),
"invalid subtype \"a b\": must be 1 to 32 characters from A-Z, a-z, 0-9, hyphen and underscore"
);
let err = OperationSubType::new("ok\n").unwrap_err();
assert!(
err.to_string().starts_with("invalid subtype \"ok\\n\": "),
"{err}"
);
}
}