#extension #trait #custom #method #impl

extension-traits

Annotation to easily define ad-hoc / one-shot extension traits

2 stable releases

1.0.1 Jan 18, 2022

#7 in #custom

Download history 1880/week @ 2023-02-02 1903/week @ 2023-02-09 3338/week @ 2023-02-16 2505/week @ 2023-02-23 3466/week @ 2023-03-02 4501/week @ 2023-03-09 5737/week @ 2023-03-16 3259/week @ 2023-03-23 5384/week @ 2023-03-30 4063/week @ 2023-04-06 5523/week @ 2023-04-13 6322/week @ 2023-04-20 4561/week @ 2023-04-27 5485/week @ 2023-05-04 7666/week @ 2023-05-11 7157/week @ 2023-05-18

26,419 downloads per month
Used in 19 crates (3 directly)

Zlib OR MIT OR Apache-2.0

15KB
53 lines

::extension-traits

Annotation to easily define ad-hoc / one-shot extension traits.

Repository Latest version Documentation MSRV unsafe forbidden License CI

Examples

  • Also

    #[macro_use]
    extern crate extension_traits;
    
    #[extension(trait Also)]
    impl<T> T {
        fn also (mut self, f: impl FnOnce(&mut Self))
          -> Self
        {
            f(&mut self);
            self
        }
    }
    
    fn main ()
    {
        use ::std::{collections::HashMap, ops::Not};
    
        let /* immut */ map = HashMap::with_capacity(2).also(|m| {
            m.insert("foo", 42);
            m.insert("bar", 27);
        });
        assert!(map.contains_key("foo"));
        assert!(map.contains_key("bar"));
        assert!(map.contains_key("baz").not());
    }
    
  • WithPath

    #[macro_use]
    extern crate extension_traits;
    
    use ::std::{error::Error, path::{Path, PathBuf}};
    
    #[extension(trait WithPath)]
    impl PathBuf {
        fn with (mut self, segment: impl AsRef<Path>)
          -> PathBuf
        {
            self.push(segment);
            self
        }
    }
    
    fn main ()
      -> Result<(), Box<dyn Error>>
    {
        let some_dir = PathBuf::from(::std::env::var("MY_LIB_SOME_DIR")?);
        // Contrary to chaining `.join()`, this reuses the memory!
        let some_subdir = some_dir.with("some").with("sub").with("dir");
        //
        Ok(())
    }
    
  • Context

    #[macro_use]
    extern crate extension_traits;
    
    use ::std::{error::Error, fmt::Display};
    
    #[extension(trait Context)]
    impl<Ok, Err : Display> Result<Ok, Err> {
        fn context (self, prefix: impl Display)
          -> Result<Ok, String>
        {
            self.map_err(|err| format!("{}: {}", prefix, err))
        }
    }
    
    fn main ()
      -> Result<(), Box<dyn Error>>
    {
        let file_contents =
            ::std::fs::read_to_string("some/file")
                .context("Error when opening some/file")?
        ;
        //
        Ok(())
    }
    

Similar to https://docs.rs/extension-trait, but for the following:

Features

  • Supports generics (see Context)

  • search/grep 'trait TraitName'-friendly!

Dependencies

~0.9–1.2MB
~30K SLoC