1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
//! Low level data types for the peace automation framework.
//!
//! This crate exists because:
//!
//! * `peace_cfg` has a dependency on `peace_resources` for `Resources`, used in
//! `Item::setup`.
//! * `peace_resources` has a dependency on `ItemId`, as uses `TypeMap<ItemId,
//! _>` for the `States` maps.
//!
//! When [peace#67] is implemented, the `progress` module can be moved out
//! of `peace_core` into `peace_cfg`.
//!
//! [peace#67]: https://github.com/azriel91/peace/issues/67
// Re-exports
pub use peace_static_check_macros::{app_name, flow_id, item_id, profile};
pub use crate::{
app_name::{AppName, AppNameInvalidFmt},
apply_check::ApplyCheck,
flow_id::{FlowId, FlowIdInvalidFmt},
item_id::{ItemId, ItemIdInvalidFmt},
profile::{Profile, ProfileInvalidFmt},
};
#[cfg(feature = "output_progress")]
pub mod progress;
mod app_name;
mod apply_check;
mod flow_id;
mod item_id;
mod profile;
/// Implements common behaviour for an ID type.
///
/// The implemented behaviour includes:
///
/// * `IdType::new`
/// * `IdType::new_unchecked`
/// * `IdType::is_valid_id`
/// * `std::ops::Deref`
/// * `std::ops::DerefMut`
/// * `std::fmt::Display`
/// * `std::str::FromStr`
/// * `TryFrom<String>`
/// * `TryFrom<&'static str>`
/// * `peace_fmt::Presentable`
///
/// A separate error type is also generated, which indicates an invalid value
/// when the ID type is instantiated with `new`.
///
/// # Usage
///
/// ```rust
/// use std::borrow::Cow;
///
/// // replace this with your ID type's macro
/// use peace_static_check_macros::my_id_type;
/// use serde::{Deserialize, Serialize};
///
/// // Rename your ID type
/// #[derive(Clone, Debug, Hash, PartialEq, Eq, Deserialize, Serialize)]
/// pub struct MyIdType(Cow<'static, str>);
///
/// crate::id_newtype!(
/// MyIdType, // Name of the ID type
/// MyIdTypeInvalidFmt, // Name of the invalid value error
/// my_id_type, // Name of the static check macro
/// tag, // The `peace_fmt::Presentable` method to style the ID
/// );
/// ```
macro_rules! id_newtype {
($ty_name:ident, $ty_err_name:ident, $macro_name:ident, $presentable_method:ident) => {
impl $ty_name {
#[doc = concat!("Returns a new `", stringify!($ty_name), "` if the given `&str` is valid.")]
///
#[doc = concat!("Most users should use the [`", stringify!($macro_name), "!`] macro as this provides")]
/// compile time checks and returns a `const` value.
///
#[doc = concat!("[`", stringify!($macro_name), "!`]: peace_static_check_macros::profile")]
pub fn new(s: &'static str) -> Result<Self, $ty_err_name> {
Self::try_from(s)
}
#[doc = concat!("Returns a new `", stringify!($ty_name), "`.")]
///
#[doc = concat!("Most users should use the [`", stringify!($macro_name), "!`] macro as this provides")]
/// compile time checks and returns a `const` value.
///
#[doc = concat!("[`", stringify!($macro_name), "!`]: peace_static_check_macros::profile")]
#[doc(hidden)]
pub const fn new_unchecked(s: &'static str) -> Self {
Self(std::borrow::Cow::Borrowed(s))
}
/// Returns whether the provided `&str` is a valid station identifier.
pub fn is_valid_id(proposed_id: &str) -> bool {
let mut chars = proposed_id.chars();
let first_char = chars.next();
let first_char_valid = first_char
.map(|c| c.is_ascii_alphabetic() || c == '_')
.unwrap_or(false);
let remainder_chars_valid =
chars.all(|c| c.is_ascii_alphabetic() || c == '_' || c.is_ascii_digit());
first_char_valid && remainder_chars_valid
}
}
impl std::ops::Deref for $ty_name {
type Target = std::borrow::Cow<'static, str>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::fmt::Display for $ty_name {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[peace_fmt::async_trait(?Send)]
impl peace_fmt::Presentable for $ty_name {
async fn present<'output, PR>(&self, presenter: &mut PR) -> Result<(), PR::Error>
where
PR: peace_fmt::Presenter<'output>
{
presenter.$presentable_method(self).await
}
}
impl TryFrom<String> for $ty_name {
type Error = $ty_err_name<'static>;
fn try_from(s: String) -> Result<$ty_name, $ty_err_name<'static>> {
if Self::is_valid_id(&s) {
Ok($ty_name(std::borrow::Cow::Owned(s)))
} else {
let s = std::borrow::Cow::Owned(s);
Err($ty_err_name::new(s))
}
}
}
impl TryFrom<&'static str> for $ty_name {
type Error = $ty_err_name<'static>;
fn try_from(s: &'static str) -> Result<$ty_name, $ty_err_name<'static>> {
if Self::is_valid_id(s) {
Ok($ty_name(std::borrow::Cow::Borrowed(s)))
} else {
let s = std::borrow::Cow::Borrowed(s);
Err($ty_err_name::new(s))
}
}
}
impl std::str::FromStr for $ty_name {
type Err = $ty_err_name<'static>;
fn from_str(s: &str) -> Result<$ty_name, $ty_err_name<'static>> {
if Self::is_valid_id(s) {
Ok($ty_name(std::borrow::Cow::Owned(String::from(s))))
} else {
let s = std::borrow::Cow::Owned(String::from(s));
Err($ty_err_name::new(s))
}
}
}
#[doc = concat!("Error indicating `", stringify!($ty_name), "` provided is not in the correct format.")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct $ty_err_name<'s> {
/// String that was provided for the `$ty_name`.
value: std::borrow::Cow<'s, str>,
}
impl<'s> $ty_err_name<'s> {
#[doc = concat!("Returns a new `", stringify!($ty_err_name), "` error.")]
pub fn new(value: std::borrow::Cow<'s, str>) -> Self {
Self { value }
}
#[doc = concat!("Returns the value that failed to be parsed as a [`", stringify!($ty_name), "`].")]
pub fn value(&self) -> &std::borrow::Cow<'s, str> {
&self.value
}
}
impl<'s> std::fmt::Display for $ty_err_name<'s> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"`{value}` is not a valid `{ty_name}`.\n\
`{ty_name}`s must begin with a letter or underscore, and contain only letters, numbers, or underscores.",
ty_name = stringify!($ty_name),
value = self.value
)
}
}
impl<'s> std::error::Error for $ty_err_name<'s> {}
};
}
pub(crate) use id_newtype;