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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
mod private
{
use crate::*;
// qqq : group
use std::collections::HashMap;
// use wtools::error::Result;
use std::{ fmt::Formatter, rc::Rc };
// use wtools::anyhow::anyhow;
/// Command Args
///
/// Used to contain subjects of a command and allow the user to retrieve them in comfortable way.
///
/// # Example:
///
/// ```
/// use wca::{ Args, Value };
///
/// let args = Args( vec![ Value::String( "Hello, World!".to_string() ) ] );
///
/// let first_arg : &str = args.get_owned( 0 ).unwrap();
/// assert_eq!( "Hello, World!", first_arg );
///
/// let first_arg : &str = args[ 0 ].clone().into();
/// assert_eq!( "Hello, World!", first_arg );
/// ```
///
/// ## Use case
/// ```
/// # use wca::{ Routine, Handler, VerifiedCommand };
/// let routine = Routine::from( Handler::from
/// (
/// | o : VerifiedCommand |
/// {
/// let first_arg : i32 = o.args.get_owned( 0 ).unwrap();
/// }
/// ) );
/// ```
#[ derive( Debug, Clone ) ]
pub struct Args( pub Vec< Value > );
impl Args
{
/// Returns owned casted value by its index
///
/// ```
/// # use wca::{ Args, Value };
///
/// let args = Args( vec![ Value::String( "Hello, World!".to_string() ) ] );
///
/// let first_arg : &str = args.get_owned( 0 ).unwrap();
/// assert_eq!( "Hello, World!", first_arg );
///
/// let first_arg : &str = args[ 0 ].clone().into();
/// assert_eq!( "Hello, World!", first_arg );
/// ```
pub fn get_owned< T : From< Value > >( &self, index : usize ) -> Option< T >
{
self.0.get( index ).map( | arg | arg.to_owned().into() )
}
}
impl core::ops::Deref for Args
{
type Target = Vec< Value >;
fn deref( &self ) -> &Self::Target
{
&self.0
}
}
/// Command Properties
///
/// Used to contain properties of a command and allow the user to retrieve them in comfortable way.
///
/// # Example:
///
/// ```
/// use wca::{ Props, Value };
///
/// let props = Props( [ ( "hello".to_string(), Value::String( "World!".to_string() ) ) ].into() );
/// let hello_prop : &str = props.get_owned( "hello" ).unwrap();
///
/// assert_eq!( "World!", hello_prop );
/// ```
///
/// ## Use case
/// ```
/// # use wca::{ Routine, Handler, Props, VerifiedCommand };
/// let routine = Routine::from( Handler::from
/// (
/// | o : VerifiedCommand |
/// {
/// let key_option : i32 = o.props.get_owned( "key" ).unwrap();
/// }
/// ) );
/// ```
#[ derive( Debug, Clone ) ]
pub struct Props( pub HashMap< String, Value > );
impl Props
{
/// Returns owned casted value by its key
///
/// ```
/// # use wca::{ Props, Value };
///
/// let props = Props( [ ( "hello".to_string(), Value::String( "World!".to_string() ) ) ].into() );
/// let hello_prop : &str = props.get_owned( "hello" ).unwrap();
///
/// assert_eq!( "World!", hello_prop );
/// ```
pub fn get_owned< K : AsRef< str >, T : From< Value > >( &self, key : K ) -> Option< T >
{
self.0.get( key.as_ref() ).map( | arg | arg.to_owned().into() )
}
}
impl core::ops::Deref for Props
{
type Target = HashMap< String, Value > ;
fn deref( &self ) -> &Self::Target
{
&self.0
}
}
// aaa : make 0-arguments, 1-argument, 2-arguments, 3 arguments versions
// aaa : done. now it works with the following variants:
// fn(), fn(args), fn(props), fn(args, props), fn(context), fn(context, args), fn(context, props), fn(context, args, props)
// qqq : why not public?
type RoutineWithoutContextFn = dyn Fn( VerifiedCommand ) -> error::untyped::Result< () >;
type RoutineWithContextFn = dyn Fn( Context, VerifiedCommand ) -> error::untyped::Result< () >;
///
/// Routine handle.
///
/// ```
/// # use wca::{ Handler, Routine };
/// let routine = Routine::from( Handler::from
/// (
/// ||
/// {
/// // Do what you need to do
/// }
/// ) );
/// ```
///
/// ```
/// # use wca::{ Handler, Routine, VerifiedCommand };
/// let routine = Routine::from( Handler::from
/// (
/// | o : VerifiedCommand |
/// {
/// // Do what you need to do
/// }
/// ) );
/// ```
///
/// ```
/// # use wca::{ Handler, Routine };
/// let routine = Routine::from( Handler::from
/// (
/// | ctx, o |
/// {
/// // Do what you need to do
/// }
/// ) );
pub struct Handler< I, O >( Box< dyn Fn( I ) -> O > );
impl< I, O > std::fmt::Debug for Handler< I, O >
{
fn fmt( &self, f : &mut Formatter< '_ > ) -> std::fmt::Result
{
f.debug_struct( "Handler" ).finish_non_exhaustive()
}
}
// without context
impl< F, R > From< F > for Handler< (), R >
where
R : IntoResult + 'static,
F : Fn() -> R + 'static,
{
fn from( value : F ) -> Self
{
Self( Box::new( move | () | value() ) )
}
}
impl< F, R > From< F > for Handler< VerifiedCommand, R >
where
R : IntoResult + 'static,
F : Fn( VerifiedCommand ) -> R + 'static,
{
fn from( value : F ) -> Self
{
Self( Box::new( value ) )
}
}
// with context
impl< F, R > From< F > for Handler< Context, R >
where
R : IntoResult + 'static,
F : Fn( Context ) -> R + 'static,
{
fn from( value : F ) -> Self
{
Self( Box::new( value ) )
}
}
impl< F, R > From< F > for Handler< ( Context, VerifiedCommand ), R >
where
R : IntoResult + 'static,
F : Fn( Context, VerifiedCommand ) -> R + 'static,
{
fn from( value : F ) -> Self
{
Self( Box::new( move |( ctx, a )| value( ctx, a ) ) )
}
}
impl< I, O > From< Handler< I, O > > for Routine
where
I : 'static,
O : IntoResult + 'static,
Routine : From< Box< dyn Fn( I ) -> error::untyped::Result< () > > >,
{
fn from( value : Handler< I, O > ) -> Self
{
Routine::from( Box::new( move | x | value.0( x ).into_result() ) )
}
}
/// Represents different types of routines.
///
/// - `WithoutContext`: A routine that does not require any context.
/// - `WithContext`: A routine that requires a context.
// qqq : for Bohdan : instead of array of Enums, lets better have 5 different arrays of different Routine and no enum
// to use statical dispatch
#[ derive( Clone ) ]
pub enum Routine
{
/// Routine without context
WithoutContext( Rc< RoutineWithoutContextFn > ),
/// Routine with context
WithContext( Rc< RoutineWithContextFn > ),
}
impl std::fmt::Debug for Routine
{
fn fmt( &self, f : &mut Formatter< '_ > ) -> std::fmt::Result
{
match self
{
Routine::WithoutContext( _ ) => f.debug_struct( "Routine::WithoutContext" ).finish_non_exhaustive(),
Routine::WithContext( _ ) => f.debug_struct( "Routine::WithContext" ).finish_non_exhaustive(),
}
}
}
// without context
impl From< Box< dyn Fn( () ) -> error::untyped::Result< () > > > for Routine
{
fn from( value : Box< dyn Fn( () ) -> error::untyped::Result< () > > ) -> Self
{
Self::WithoutContext( Rc::new( move | _ | { value( () )?; Ok( () ) } ) )
}
}
impl From< Box< dyn Fn( VerifiedCommand ) -> error::untyped::Result< () > > > for Routine
{
fn from( value : Box< dyn Fn( VerifiedCommand ) -> error::untyped::Result< () > > ) -> Self
{
Self::WithoutContext( Rc::new( move | a | { value( a )?; Ok( () ) } ) )
}
}
// with context
impl From< Box< dyn Fn( Context ) -> error::untyped::Result< () > > > for Routine
{
fn from( value : Box< dyn Fn( Context ) -> error::untyped::Result< () > > ) -> Self
{
Self::WithContext( Rc::new( move | ctx, _ | { value( ctx )?; Ok( () ) } ) )
}
}
impl From< Box< dyn Fn(( Context, VerifiedCommand )) -> error::untyped::Result< () > > > for Routine
{
fn from( value : Box< dyn Fn(( Context, VerifiedCommand )) -> error::untyped::Result< () > > ) -> Self
{
Self::WithContext( Rc::new( move | ctx, a | { value(( ctx, a ))?; Ok( () ) } ) )
}
}
// aaa : why Rc is necessary? why not just box?
// aaa : to be able to clone Routines
impl PartialEq for Routine
{
fn eq( &self, other : &Self ) -> bool
{
// We can't compare closures. Because every closure has a separate type, even if they're identical.
// Therefore, we check that the two Rc's point to the same closure (allocation).
#[ allow( clippy::vtable_address_comparisons ) ]
match ( self, other )
{
( Routine::WithContext( this ), Routine::WithContext( other ) ) => Rc::ptr_eq( this, other ),
( Routine::WithoutContext( this ), Routine::WithoutContext( other ) ) => Rc::ptr_eq( this, other ),
_ => false
}
}
}
impl Eq for Routine {}
trait IntoResult
{
fn into_result( self ) -> error::untyped::Result< () >;
}
// xxx
impl IntoResult for std::convert::Infallible { fn into_result( self ) -> error::untyped::Result< () > { Ok( () ) } }
impl IntoResult for () { fn into_result( self ) -> error::untyped::Result< () > { Ok( () ) } }
impl< E : std::fmt::Debug > IntoResult
for error::untyped::Result< (), E >
{
fn into_result( self ) -> error::untyped::Result< () >
{
self.map_err( | e | error::untyped::format_err!( "{e:?}" ))
// xxx : qqq : ?
}
}
}
//
crate::mod_interface!
{
exposed use Routine;
exposed use Handler;
exposed use Args;
exposed use Props;
}