macro microtype-macro

Proc macro for generating microtypes

14 releases

0.2.6 Nov 1, 2022
0.2.5 Aug 22, 2022
0.1.6 Feb 3, 2022
0.1.5 Jan 1, 2022
0.1.4 Dec 27, 2021
Download history 144/week @ 2024-07-29 133/week @ 2024-08-05 27/week @ 2024-08-12 61/week @ 2024-08-19 48/week @ 2024-08-26 28/week @ 2024-09-02 82/week @ 2024-09-09 101/week @ 2024-09-16 104/week @ 2024-09-23 141/week @ 2024-09-30 38/week @ 2024-10-07 91/week @ 2024-10-14 52/week @ 2024-10-21 54/week @ 2024-10-28 87/week @ 2024-11-04 33/week @ 2024-11-11

231 downloads per month
Used in 2 crates (via microtype)

MIT license

34KB
919 lines

microtype

Boilerplate-free microtypes

What/Why/How?

Microtypes (also known as "newtypes") are thin wrappers around primitive types, that differentiate between 2 otherwise identical types, based on their usage/meaning. Since they are distinct types, they can't be substituted for one another. This helps to reduce logic bugs, by catching incorrect use of data at compile time.

For example, consider the following:

fn handle_order(user_id: String, order_id: String) {
  // ...
} 

fn main() {
  let user_id = ...;
  let order_id = ...;
  handle_order(order_id, user_id);
}

In this small example, it's fairly easy to see that there's a bug here: order_id and user_id are in the wrong order. However, as projects grow it becomes harder to spot. More generally, human beings aren't very good at detecting errors like this, so we should try to offload this work onto the compiler.

Let's take a look at that but with microtypes instead:

// microtype definitions
microtype! {
  String {
    UserId
  }

  String {
    OrderId
  }
}

// or use the shorthand for declaring multiple microtypes
// microtype! {
//   String {
//     UserId
//     OrderId
//   }
// }

fn handle_order(user_id: UserId, order_id: OrderId) {
  // ...
} 

fn main() {
  let user_id: UserId = ...;
  let order_id: OrderId = ...;
  handle_order(order_id, user_id);  // Error, mismatched types
}

Great! It doesn't compile. By introducing microtypes, we've moved this run-time error into a compile-time error.

For more details and examples, check out the docs

Contributing

Any and all contributions are always welcome! Feel free to raise an issue/submit a PR, etc.


lib.rs:

proc-macro crate for microtype

Dependencies

~1.5MB
~37K SLoC