@ -113,13 +113,20 @@ impl LispExt for Vec<Sexp>
}
// Sexp doesn't use try_from(), so...
/// Extension methods for getting typed values out of S-expression
pub trait TryIntoExt : Sized
{
/// Return this expression as a List (`Vec<Sexp>`) if possible
fn try_into_list ( self ) -> Result < Vec < Sexp > , Error > ;
/// Return this expression as a non-descript atom if possible
fn try_into_atom ( self ) -> Result < Atom , Error > ;
/// Return this expression as a String if possible (atom)
fn try_into_string ( self ) -> Result < String , Error > ;
/// Return this expression as an integer if possible (atom)
fn try_into_int ( self ) -> Result < i64 , Error > ;
/// Return this expression as a float if possible (atom)
fn try_into_float ( self ) -> Result < f64 , Error > ;
}
@ -204,13 +211,21 @@ impl TryIntoExt for Atom
// To avoid some `clone()`s
/// Extension methods for getting typed references out of S-expression
pub trait TryGetExt : Sized
{
/// Try to get this expression as a reference `List` (slice of `Sexpr`).
fn try_get_list ( & self ) -> Result < & [ Sexp ] , Error > ;
/// Try to get this expression as a reference atom.
fn try_get_atom ( & self ) -> Result < & Atom , Error > ;
/// Try to get this expression as a reference string (atom)
fn try_get_string ( & self ) -> Result < & String , Error > ;
/// Try to get this expression as a reference integer (atom)
fn try_get_int ( & self ) -> Result < & i64 , Error > ;
/// Try to get this expression as a reference float (atom)
fn try_get_float ( & self ) -> Result < & f64 , Error > ;
}
@ -253,3 +268,39 @@ impl TryGetExt for Sexp
}
}
}
impl TryGetExt for Atom
{
#[ inline ]
fn try_get_list ( & self ) -> Result < & [ Sexp ] , Error >
{
Err ( Error ::bad_type ( LispType ::List , self ) )
}
#[ inline ]
fn try_get_atom ( & self ) -> Result < & Atom , Error >
{
Ok ( self )
}
fn try_get_string ( & self ) -> Result < & String , Error >
{
match self {
Self ::S ( string ) = > Ok ( string ) ,
other = > Err ( Error ::bad_type ( LispType ::String , other ) ) ,
}
}
fn try_get_int ( & self ) -> Result < & i64 , Error >
{
match self {
Self ::I ( int ) = > Ok ( int ) ,
other = > Err ( Error ::bad_type ( LispType ::Integer , other ) ) ,
}
}
fn try_get_float ( & self ) -> Result < & f64 , Error >
{
match self {
Self ::F ( float ) = > Ok ( float ) ,
other = > Err ( Error ::bad_type ( LispType ::Float , other ) ) ,
}
}
}