Crate butcher

Source
Expand description

§Butcher

An easy way to interact with Cowed structs and enums.

This crate provides the following functionalities for data wrapped in Cow:

§Destructuring/pattern matching

The Butcher trait can be used when it is necessary to destruture something wrapped in a Cow. Below is a simple example:

use std::borrow::Cow;
use butcher::Butcher;

#[derive(Butcher, Clone)]
struct MyNumberList {
    val: u32,
    next: Option<Box<MyNumberList>>,
}

fn destructure_list_elem(i: Cow<MyNumberList>) -> (Cow<u32>, Cow<Option<Box<MyNumberList>>>) {
    let ButcheredMyNumberList { val, next } = Butcher::butcher(i);

    (val, next)
}

This also allows pattern matching, as demonstrated in the following example:

use butcher::Butcher;
use std::borrow::Cow;

#[derive(Butcher, Clone)]
enum WebEvent {
    PageLoad,
    KeyPress(char),
    Paste(String),
    // or c-like structures.
    Click { x: i64, y: i64 },
}

fn print_action(i: Cow<WebEvent>) {
    match WebEvent::butcher(i) {
        ButcheredWebEvent::PageLoad => { /* ... */ },
        ButcheredWebEvent::KeyPress(key) => { /* ... */ },
        ButcheredWebEvent::Paste(pasted) => { /* ... */ },
        ButcheredWebEvent::Click { x, y } => { /* ... */ },
    }
}

The Butcher procedural macro can be derived for structs and for enums.

§Iteration

Here is a demonstration of how to iterate over an object wrapped in a Cow:

use std::borrow::Cow;
use butcher::iterator::{CowIter, IntoCowIterator};

fn print_numbers(elems: Cow<[u32]>) {
    let mut iter = elems.into_cow_iter();

    for element in iter {
        // The type of element is Cow<u32>
        println!("{:?}", element);
    }
}

See the documentation of CowIter for more information.

§Flattening

In some situations, the Butcher proc macro can generate tricky fields, such as nested Cow. The FlattenCow trait aims to remove such flattening.

§Removing an indirection level

The AsDerefCow trait allows to transform a given Cow<T> into a Cow<<T as Deref>::Target>. This can be usefull when it is needed to transform a Cow<String> into Cow<str>.

Modules§

as_deref
Allows to dereference the content of a Cow, lowering the level of indirection.
deriving_butcher_enum
Quick introduction to butchering on enums
deriving_butcher_struct
Quick introduction to butchering on structs
flatten
A trait that allows to flatten Cow<Cow<T>> to Cow<T>.
iterator
An iterator over data wrapped in Cow.
methods
Different ways to butcher a field.

Traits§

Butcher

Derive Macros§

Butcher
Derives the Butcher trait for a structure or an enum.