#empty

if_empty

Replace if/else checks for emptyness with a simple method call

3 releases (breaking)

0.3.0 Jul 30, 2021
0.2.0 Jun 19, 2021
0.1.0 Jun 19, 2021

#14 in #empty

Download history 28/week @ 2024-07-28 11/week @ 2024-09-22 3/week @ 2024-09-29

180 downloads per month
Used in glog

MPL-2.0 license

12KB
165 lines

IfEmpty

CI Status

A crate to use for defensive programming where context specific defaults are needed.

Motivation

While using an Option is preferrably in most circumstances there are situations where a function call doesn't return a Option and the Default of a type isn't helpful either.

You now have the option to wrap this special function call or write something along these lines:

let foo = {
    let b = bar();
    if b.is_empty() {
        Bar {
            // set the default values for your context here
        }
    } else {
        b
    }
};

Using this crate you can reduce this down to:

let foo = bar().if_empty(Bar { /* ... */ });

Implementing this for your own type

In order to take advantage of this feature you have to implement this behavior for your types:


use if_empty::*;

struct Foo {
    val: bool,
}

impl IfEmpty for Foo {
    fn if_empty(self, value: Foo) -> Foo {
        if self.is_empty() {
            value
        } else {
            self
        }
    }
}

See derive_macro for how to use the #[derive] macro.

Provided types

The crate provides this functionality for String, OsString, &str and &OsStr.

Dependencies

~1.5MB
~37K SLoC