4 releases (2 stable)

1.0.1 Jan 18, 2022
1.0.0 Oct 23, 2021
0.1.0-rc2 Oct 23, 2021

#1991 in Procedural macros

Download history 13796/week @ 2023-12-06 12951/week @ 2023-12-13 6058/week @ 2023-12-20 4361/week @ 2023-12-27 9131/week @ 2024-01-03 10380/week @ 2024-01-10 15390/week @ 2024-01-17 15220/week @ 2024-01-24 10649/week @ 2024-01-31 10699/week @ 2024-02-07 11761/week @ 2024-02-14 14320/week @ 2024-02-21 11130/week @ 2024-02-28 14865/week @ 2024-03-06 16731/week @ 2024-03-13 12151/week @ 2024-03-20

57,051 downloads per month
Used in 36 crates (via ext-trait)

Zlib OR MIT OR Apache-2.0

7KB
155 lines

::ext-trait

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 ext_trait;
    
    #[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 ext_trait;
    
    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 ext_trait;
    
    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!


lib.rs:

Crate not intended for direct use. Use https:://docs.rs/ext-trait instead.

Dependencies

~1.5MB
~34K SLoC