up_set 0.1.0

Set values, or update them using a closure
Documentation
  • Coverage
  • 80%
    4 out of 5 items documented2 out of 5 items with examples
  • Size
  • Source code size: 14.5 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 928.28 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 11s Average build duration of successful builds.
  • all releases: 11s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • nik-rev

up_set

A #![no_std], no dependencies crate which allows you to write functions that either set the value or update it using a closure.

use up_set::UpSet;

#[derive(Debug, Eq, PartialEq)]
struct Point {
    x: u32,
    y: u32,
}

// `M` is a generic marker to guide Rust's type inference
// system to choose the correct implementation of `UpSet`
// for either `u32` or `Fn(u32) -> u32`
impl Point {
    fn x<M, U: UpSet<u32, M>>(mut self, x: U) -> Self {
        self.x = x.up_set(self.x);
        self
    }
    fn y<M, U: UpSet<u32, M>>(mut self, y: U) -> Self {
        self.y = y.up_set(self.y);
        self
    }
}

assert_eq!(
    Point { x: 10, y: 10 }.x(20).y(|y| y + 50),
    Point {
        // `x` was set to a specific value
        x: 20,
        // `width` was updated
        y: 60,
    }
);

assert_eq!(
    Point { x: 10, y: 10 }.x(|x| x + 20).y(50),
    Point {
        // `x` was updated
        x: 30,
        // `y` was set to a specific value
        y: 50,
    }
);

The benefit of this approach over using a pub field is that you can chain many updates together:

Rectangle {
    x: 55,
    y: 40,
    height: 100,
    width: 100,
}
.x(40)
.y(|y| y + 35)
.width(100)
.height(|h| h - 20)