Module rust_examples::typing[][src]

Expand description

This module shows some examples of how Rust’s type system can be used to write safe yet efficient code.

There are three implementations of the problem of implementing float comparison. The problem is that according to the IEEE standard f64 is only PartialOrd and not Ord since some floats cannot be compared (e.g. nan).

However, we can restrict our comparison to positive floats. The memory representation of each positive float in IEEE standard format can be interpreted as u32. Integer representations of positive floats are then monotonic and thus have efficient Ordering.

The three examples presented here then address the two remaining problems:

  1. How to ensure that given f64 is positive
  2. How to safely compare floats when f64::to_int_unchecked is unsafe

Note that one would typically realize these as implementations of PartialOrd or Ord but we keep it simple and implement the comparison as plain function.

Also note that std actually defines a safe memory interpretation f64::to_bits so this example is somewhat artificial.

Last few examples describe the top and bottom type realized in Rust’s type system.

Structs

This example presents several constructs which represent an empty set of values.

Opaque wrapper around f64 which adds static semantics that the float has positive value.

Structure that defines single field which has the type of the top type in Rust.

Structure that defines single field which has the type of the unit type in Rust.

Functions

Improved comparison function for positive f64s.

Naive positive f64 comparison function.

Safe and efficient version of comparison of two Positive floats.