10Print

A while back, I took a break from responsibilities and played around with generating 10Print and 10Print-like diagrams. For those not in the know, check out the website 10Print.org!

I did my 10Print renders using my own creative coding tool (which may be a future blog post), but today I'll create the renders in the SVG format. We'll be using Rust, the svg crate to generate SVGs, and the rand crate for random number generation.

Variants

Let's take a look at 10Print and some variants.

Original

  1. Consider the canvas as a grid of cells.

  2. For each cell in the canvas, randomly draw a line which is either:

    • From the top left to the bottom right

    • From the bottom left to the top right

use ::;
use ::{::::{::, }, };

/// Draw a line from start (x1, y1) to end (x2, y2).
fn (: (, ), : (, )) ->  {
    ::().("d", ::().().().())
}

fn () -> <(), <dyn ::::>> {
    // 10Print parameters
    let  = 1000;
    let  = 500;
    let  = 20;
    let  =  / ;
    let  = "output.svg";

    // Create the svg document
    let  = (0, 0, , );
    let mut  = ::::().("viewBox", );
    let mut  = ::::::seed_from_u64(8888);

    for  in (0..).( as ) {
        for  in (0..).( as ) {
            // Half the time...
            let  = if .gen::<>() > 0.5 {
                // Draw a top left -> bottom right line
                ((, ), ( + ,  + ));
            } else {
                // Draw a bottom left -> top right line
                ((,  + ), ( + , ));
            };
            .();
        }
    }

    ::(, &)?;
    (())
}

Output:

Pretty neat! With the two simple rules, we get an aesthetically pleasing tiled image. We can also bias the lines towards one diagonal or another by modifying the weight in the random number check:

Top-left to bottom right bias:

// Most of the time...
let  = if rng.gen::<>() > 0.2 {
    // Draw a top left -> bottom right line
    ((x, y), (x + spacing, y + spacing))
} else {

Bottom-left to top-right bias:

// Very rarely...
let  = if rng.gen::<>() > 0.8 {
    // Draw a top left -> bottom right line
    ((x, y), (x + spacing, y + spacing))
} else {

Orthogonal

What if, instead of diagonal lines, we drew straight lines instead?

let  = if rng.gen::<>() > 0.5 {
    ((x, y), (x + spacing, y))
} else {
    ((x, y), (x, y + spacing))
};

Pretty cool! It resembles a very biased and unfun maze.

Weave

This variant is similar to the Orthogonal variant, but with a different offset:

let  = if rng.gen::<>() > 0.5 {
    ((x + spacing / 2, y), (x + spacing / 2, y + spacing))
} else {
    ((x, y + spacing / 2), (x + spacing, y + spacing / 2))
};

Kinda looks like a basket weave, don't you think?

Mondrian-ish

How about we connect the lines in the Weave variant?

let  = if rng.gen::<>() > 0.5 {
    (
        (x + spacing / 2, y - spacing / 2),
        (x + spacing / 2, y + spacing * 3 / 2),
    )
} else {
    (
        (x - spacing / 2, y + spacing / 2),
        (x + spacing * 3 / 2, y + spacing / 2),
    )
};

Budget Piet Mondrian art!

Bark

There's no restriction on the number of separate "cases" we create, either. Here's a version with 3 cases instead of two:

let  = rng.gen::<>();
let  = if  < 0.1 {
    ((x, y), (x + spacing, y + spacing))
} else if  < 0.4 {
    ((x, y + spacing), (x + spacing, y))
} else {
    ((x + spacing, y), (x + spacing, y + spacing))
};

Color

Black and white images are too boring, so let's inject some color into the renders. First, we'll make the line function accept a color:

fn (: (, ), : (, ), : &) -> Path {
    Path::new()
        .set("stroke", )
        .set("d", Data::new().move_to().line_to().close())
}

Then, we modify the calls to draw either a red line or a blue line:

let  = if rand_num > 0.5 {
    // Draw a top left -> bottom right line
    ((x, y), (x + spacing, y + spacing), "red");
} else {
    // Draw a bottom left -> top right line
    ((x, y + spacing), (x + spacing, y), "blue");
}

More 10Print Variants

Here are a few more 10Print variants. Try to create them yourself or be creative and make your own designs!

Note: This one is a recreation of Ian Witham's 10Print variation.

extern crate rand

Utilities for random number generation

Rand provides utilities to generate random numbers, to convert them to useful types and distributions, and some randomness-related algorithms.

Quick Start

// The prelude import enables methods we use below, specifically
// Rng::random, Rng::sample, SliceRandom::shuffle and IndexedRandom::choose.
use rand::prelude::*;

// Get an RNG:
let mut rng = rand::rng();

// Try printing a random unicode code point (probably a bad idea)!
println!("char: '{}'", rng.random::<char>());
// Try printing a random alphanumeric value instead!
println!("alpha: '{}'", rng.sample(rand::distr::Alphanumeric) as char);

// Generate and shuffle a sequence:
let mut nums: Vec<i32> = (1..100).collect();
nums.shuffle(&mut rng);
// And take a random pick (yes, we didn't need to shuffle first!):
let _ = nums.choose(&mut rng);

The Book

For the user guide and further documentation, please read The Rust Rand Book.

rand::rng
pub trait Rng
where
    Self: RngCore,

User-level interface for RNGs

RngCore is the dyn-safe implementation-level interface for Random (Number) Generators. This trait, Rng, provides a user-level interface on RNGs. It is implemented automatically for any R: RngCore.

This trait must usually be brought into scope via use rand::Rng; or use rand::prelude::*;.

Generic usage

The basic pattern is fn foo<R: Rng + ?Sized>(rng: &mut R). Some things are worth noting here:

  • Since Rng: RngCore and every RngCore implements Rng, it makes nodifference whether we use R: Rng or R: RngCore.
  • The + ?Sized un-bounding allows functions to be called directly ontype-erased references; i.e. foo(r) where r: &mut dyn RngCore. Withoutthis it would be necessary to write foo(&mut r).

An alternative pattern is possible: fn foo<R: Rng>(rng: R). This has some trade-offs. It allows the argument to be consumed directly without a &mut (which is how from_rng(rand::rng()) works); also it still works directly on references (including type-erased references). Unfortunately within the function foo it is not known whether rng is a reference type or not, hence many uses of rng require an extra reference, either explicitly (distr.sample(&mut rng)) or implicitly (rng.random()); one may hope the optimiser can remove redundant references later.

Example:

use rand::Rng;

fn foo<R: Rng + ?Sized>(rng: &mut R) -> f32 {
    rng.random()
}
extern crate svg

An SVG composer and parser.

Example: Composing

use svg::Document;
use svg::node::element::Path;
use svg::node::element::path::Data;

let data = Data::new()
    .move_to((10, 10))
    .line_by((0, 50))
    .line_by((50, 0))
    .line_by((0, -50))
    .close();

let path = Path::new()
    .set("fill", "none")
    .set("stroke", "black")
    .set("stroke-width", 3)
    .set("d", data);

let document = Document::new()
    .set("viewBox", (0, 0, 70, 70))
    .add(path);

svg::save("image.svg", &document).unwrap();

Example: Parsing

use svg::node::element::path::{Command, Data};
use svg::node::element::tag::Path;
use svg::parser::Event;

let path = "image.svg";
let mut content = String::new();
for event in svg::open(path, &mut content).unwrap() {
    match event {
        Event::Tag(Path, _, attributes) => {
            let data = attributes.get("d").unwrap();
            let data = Data::parse(data).unwrap();
            for command in data.iter() {
                match command {
                    &Command::Move(..) => { /* … */ },
                    &Command::Line(..) => { /* … */ },
                    _ => {}
                }
            }
        }
        _ => {}
    }
}
svg
pub mod node

The nodes.

svg::node
pub mod element

The element nodes.

svg::node::element
pub mod path

The path element.

svg::node::element::path::data
pub struct Data(Vec<Command>)

A data attribute.

svg::node::element
pub struct Path {
    inner: Element,
}

A path element.

svg::node
pub trait Node
where
    Self: 'static + fmt::Debug + fmt::Display + NodeClone + NodeDefaultHash + Send + Sync,

A node.

codeintel::block_4b6477950f62a4e9
fn line(start: (i32, i32), end: (i32, i32)) -> Path

Draw a line from start (x1, y1) to end (x2, y2).

start: (i32, i32)
i32

The 32-bit signed integer type.

end: (i32, i32)
svg::node::element::Path
pub fn new() -> Self

Create a node.

svg::node::element::Path
pub fn set<T, U>(self, name: T, value: U) -> Self
where
    T: Into<String>,
    U: Into<Value>,

Assign an attribute.

svg::node::element::path::data::Data
pub fn new() -> Self

Create a data attribute.

svg::node::element::path::data::Data
pub fn move_to<T>(self, parameters: T) -> Self
where
    T: Into<Parameters>,

Add an absolute Command::Move command.

svg::node::element::path::data::Data
pub fn line_to<T>(self, parameters: T) -> Self
where
    T: Into<Parameters>,

Add an absolute Command::Line command.

svg::node::element::path::data::Data
pub fn close(self) -> Self

Add a Command::Close command.

codeintel::block_4b6477950f62a4e9
fn main() -> Result<(), Box<dyn std::error::Error>>
core::result
pub enum Result<T, E> {
    Ok( /* … */ ),
    Err( /* … */ ),
}

Result is a type that represents either success (Ok) or failure (Err).

See the module documentation for details.

alloc::boxed
pub struct Box<T, A = Global>(Unique<T>, A)
where
    T: ?Sized,
    A: Allocator,

A pointer type that uniquely owns a heap allocation of type T.

See the module-level documentation for more.

extern crate std

The Rust Standard Library

The Rust Standard Library is the foundation of portable Rust software, a set of minimal and battle-tested shared abstractions for the broader Rust ecosystem. It offers core types, like [Vec<T>] and [Option<T>], library-defined operations on language primitives, standard macros, [I/O] and [multithreading], among many other things.

std is available to all Rust crates by default. Therefore, the standard library can be accessed in use statements through the path std, as in use std::env.

How to read this documentation

If you already know the name of what you are looking for, the fastest way to find it is to use the search button at the top of the page.

Otherwise, you may want to jump to one of these useful sections:

If this is your first time, the documentation for the standard library is written to be casually perused. Clicking on interesting things should generally lead you to interesting places. Still, there are important bits you don’t want to miss, so read on for a tour of the standard library and its documentation!

Once you are familiar with the contents of the standard library you may begin to find the verbosity of the prose distracting. At this stage in your development you may want to press the “ Summary” button near the top of the page to collapse it into a more skimmable view.

While you are looking at the top of the page, also notice the “Source” link. Rust’s API documentation comes with the source code and you are encouraged to read it. The standard library source is generally high quality and a peek behind the curtains is often enlightening.

What is in the standard library documentation?

First of all, The Rust Standard Library is divided into a number of focused modules, all listed further down this page. These modules are the bedrock upon which all of Rust is forged, and they have mighty names like [std::slice] and [std::cmp]. Modules’ documentation typically includes an overview of the module along with examples, and are a smart place to start familiarizing yourself with the library.

Second, implicit methods on primitive types are documented here. This can be a source of confusion for two reasons:

  1. While primitives are implemented by the compiler, the standard libraryimplements methods directly on the primitive types (and it is the onlylibrary that does so), which are documented in the section on primitives.
  2. The standard library exports many modules with the same name as primitive types. These define additional items related to the primitivetype, but not the all-important methods.

So for example there is a page for the primitive type char that lists all the methods that can be called on characters (very useful), and there is a page for the module std::char that documents iterator and error types created by these methods (rarely useful).

Note the documentation for the primitives [str] and [T] (also called ‘slice’). Many method calls on String and [Vec<T>] are actually calls to methods on [str] and [T] respectively, via deref coercions.

Third, the standard library defines [The Rust Prelude], a small collection of items - mostly traits - that are imported into every module of every crate. The traits in the prelude are pervasive, making the prelude documentation a good entry point to learning about the library.

And finally, the standard library exports a number of standard macros, and lists them on this page (technically, not all of the standard macros are defined by the standard library - some are defined by the compiler - but they are documented here the same). Like the prelude, the standard macros are imported by default into all crates.

Contributing changes to the documentation

Check out the Rust contribution guidelines here. The source for this documentation can be found on GitHub in the ‘library/std/’ directory. To contribute changes, make sure you read the guidelines first, then submit pull-requests for your suggested changes.

Contributions are appreciated! If you see a part of the docs that can be improved, submit a PR, or chat with us first on Zulip #docs.

A Tour of The Rust Standard Library

The rest of this crate documentation is dedicated to pointing out notable features of The Rust Standard Library.

Containers and collections

The option and result modules define optional and error-handling types, [Option<T>] and [Result<T, E>]. The iter module defines Rust’s iterator trait, Iterator, which works with the for loop to access collections.

The standard library exposes three common ways to deal with contiguous regions of memory:

  • [Vec<T>] - A heap-allocated vector that is resizable at runtime.
  • [T; N] - An inline array with a fixed size at compile time.
  • [T] - A dynamically sized slice into any other kind of contiguousstorage, whether heap-allocated or not.

Slices can only be handled through some kind of pointer, and as such come in many flavors such as:

  • &[T] - shared slice
  • &mut [T] - mutable slice
  • Box<[T]> - owned slice

[str], a UTF-8 string slice, is a primitive type, and the standard library defines many methods for it. Rust [str]s are typically accessed as immutable references: &str. Use the owned String for building and mutating strings.

For converting to strings use the format macro, and for converting from strings use the [FromStr] trait.

Data may be shared by placing it in a reference-counted box or the [Rc] type, and if further contained in a [Cell] or [RefCell], may be mutated as well as shared. Likewise, in a concurrent setting it is common to pair an atomically-reference-counted box, [Arc], with a [Mutex] to get the same effect.

The collections module defines maps, sets, linked lists and other typical collection types, including the common [HashMap<K, V>].

Platform abstractions and I/O

Besides basic data types, the standard library is largely concerned with abstracting over differences in common platforms, most notably Windows and Unix derivatives.

Common types of I/O, including [files], [TCP], and [UDP], are defined in the io, fs, and net modules.

The thread module contains Rust’s threading abstractions. sync contains further primitive shared memory types, including [atomic], [mpmc] and [mpsc], which contains the channel types for message passing.

Use before and after main()

Many parts of the standard library are expected to work before and after main(); but this is not guaranteed or ensured by tests. It is recommended that you write your own tests and run them on each platform you wish to support. This means that use of std before/after main, especially of features that interact with the OS or global state, is exempted from stability and portability guarantees and instead only provided on a best-effort basis. Nevertheless bug reports are appreciated.

On the other hand core and alloc are most likely to work in such environments with the caveat that any hookable behavior such as panics, oom handling or allocators will also depend on the compatibility of the hooks.

Some features may also behave differently outside main, e.g. stdio could become unbuffered, some panics might turn into aborts, backtraces might not get symbolicated or similar.

Non-exhaustive list of known limitations:

  • after-main use of thread-locals, which also affects additional features:
  • under UNIX, before main, file descriptors 0, 1, and 2 may be unchanged(they are guaranteed to be open during main,and are opened to /dev/null O_RDWR if they weren’t open on program start)
std
pub mod error
core::error
pub trait Error
where
    Self: Debug + Display,

Error is a trait representing the basic expectations for error values, i.e., values of type E in Result<T, E>.

Errors must describe themselves through the Display and Debug traits. Error messages are typically concise lowercase sentences without trailing punctuation:

let err = "NaN".parse::<u32>().unwrap_err();
assert_eq!(err.to_string(), "invalid digit found in string");

Error source

Errors may provide cause information. Error::source is generally used when errors cross “abstraction boundaries”. If one module must report an error that is caused by an error from a lower-level module, it can allow accessing that error via Error::source(). This makes it possible for the high-level module to provide its own errors while also revealing some of the implementation for debugging.

In error types that wrap an underlying error, the underlying error should be either returned by the outer error’s Error::source(), or rendered by the outer error’s Display implementation, but not both.

Example

Implementing the Error trait only requires that Debug and Display are implemented too.

use std::error::Error;
use std::fmt;
use std::path::PathBuf;

#[derive(Debug)]
struct ReadConfigError {
    path: PathBuf
}

impl fmt::Display for ReadConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let path = self.path.display();
        write!(f, "unable to read configuration at {path}")
    }
}

impl Error for ReadConfigError {}
let width: i32
let height: i32
let num_cells: i32
let spacing: i32
let output_file: &str
let viewbox: (i32, i32, i32, i32)
let mut document: SVG
svg
pub type Document = node::element::SVG

A document.

svg::node::element::SVG
pub fn new() -> Self

Create a node.

svg::node::element::SVG
pub fn set<T, U>(self, name: T, value: U) -> Self
where
    T: Into<String>,
    U: Into<Value>,

Assign an attribute.

let mut rng: {unknown}
rand
pub mod rngs

Random number generators and adapters

This crate provides a small selection of non-portable generators. See also Types of generators and Our RNGs in the book.

Generators

This crate provides a small selection of non-portable random number generators:

  • OsRng is a stateless interface over the operating system’s random numbersource. This is typically secure with some form of periodic re-seeding.
  • ThreadRng, provided by crate::rng, is a handle to athread-local generator with periodic seeding from OsRng. Because thisis local, it is typically much faster than OsRng. It should besecure, but see documentation on ThreadRng.
  • StdRng is a CSPRNG chosen for good performance and trust of security(based on reviews, maturity and usage). The current algorithm is ChaCha12,which is well established and rigorously analysed.StdRng is the deterministic generator used by ThreadRng butwithout the periodic reseeding or thread-local management.
  • SmallRng is a relatively simple, insecure generator designed to befast, use little memory, and pass various statistical tests ofrandomness quality.

The algorithms selected for StdRng and SmallRng may change in any release and may be platform-dependent, therefore they are not reproducible.

Additional generators

  • The rdrand crate provides an interface to the RDRAND and RDSEEDinstructions available in modern Intel and AMD CPUs.
  • The rand_jitter crate provides a user-space implementation ofentropy harvesting from CPU timer jitter, but is very slow and hassecurity issues.
  • The rand_chacha crate provides portable implementations ofgenerators derived from the ChaCha family of stream ciphers
  • The rand_pcg crate provides portable implementations of a subsetof the PCG family of small, insecure generators
  • The rand_xoshiro crate provides portable implementations of thexoshiro family of small, insecure generators

For more, search crates with the rng tag.

Traits and functionality

All generators implement [RngCore] and thus also Rng. See also the Random Values chapter in the book.

Secure RNGs may additionally implement the [CryptoRng] trait.

Use the rand_core crate when implementing your own RNGs.

rand::rngs::std
pub struct StdRng(ChaCha12Rng)

A strong, fast (amortized), non-portable RNG

This is the “standard” RNG, a generator with the following properties:

  • Non-portable: any future library version may replace the algorithmand results may be platform-dependent.(For a portable version, use the rand_chacha crate directly.)
  • CSPRNG: statistically good quality of randomness and unpredictable
  • Fast (amortized):the RNG is fast for bulk generation, but the cost of method calls is notconsistent due to usage of an output buffer.

The current algorithm used is the ChaCha block cipher with 12 rounds. Please see this relevant rand issue for the discussion. This may change as new evidence of cipher security and performance becomes available.

Seeding (construction)

This generator implements the SeedableRng trait. Any method may be used, but note that seed_from_u64 is not suitable for usage where security is important. Also note that, even with a fixed seed, output is not portable.

Using a fresh seed direct from the OS is the most secure option:

let rng = StdRng::from_os_rng();

Seeding via rand::rng() may be faster:

let rng = StdRng::from_rng(&mut rand::rng());

Any SeedableRng method may be used, but note that seed_from_u64 is not suitable where security is required. See also Seeding RNGs in the book.

Generation

The generators implements RngCore and thus also Rng. See also the Random Values chapter in the book.

let y: i32
core::iter::traits::iterator::Iterator
pub trait Iterator
pub fn step_by(self, step: usize) -> StepBy<Self>
where
    Self: Sized,

Creates an iterator starting at the same point, but stepping by the given amount at each iteration.

Note 1: The first element of the iterator will always be returned, regardless of the step given.

Note 2: The time at which ignored elements are pulled is not fixed. StepBy behaves like the sequence self.next(), self.nth(step-1), self.nth(step-1), …, but is also free to behave like the sequence advance_n_and_return_first(&mut self, step), advance_n_and_return_first(&mut self, step), … Which way is used may change for some iterators for performance reasons. The second way will advance the iterator earlier and may consume more items.

advance_n_and_return_first is the equivalent of:

fn advance_n_and_return_first<I>(iter: &mut I, n: usize) -> Option<I::Item>
where
    I: Iterator,
{
    let next = iter.next();
    if n > 1 {
        iter.nth(n - 2);
    }
    next
}

Panics

The method will panic if the given step is 0.

Examples

let a = [0, 1, 2, 3, 4, 5];
let mut iter = a.into_iter().step_by(2);

assert_eq!(iter.next(), Some(0));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), None);
usize

The pointer-sized unsigned integer type.

The size of this primitive is how many bytes it takes to reference any location in memory. For example, on a 32 bit target, this is 4 bytes and on a 64 bit target, this is 8 bytes.

let x: i32
let line: ()
f32

A 32-bit floating-point type (specifically, the “binary32” type defined in IEEE 754-2008).

This type can represent a wide range of decimal numbers, like 3.5, 27, -113.75, 0.0078125, 34359738368, 0, -1. So unlike integer types (such as i32), floating-point types can represent non-integer numbers, too.

However, being able to represent this wide range of numbers comes at the cost of precision: floats can only represent some of the real numbers and calculation with floats round to a nearby representable number. For example, 5.0 and 1.0 can be exactly represented as f32, but 1.0 / 5.0 results in 0.20000000298023223876953125 since 0.2 cannot be exactly represented as f32. Note, however, that printing floats with println and friends will often discard insignificant digits: println!("{}", 1.0f32 / 5.0f32) will print 0.2.

Additionally, f32 can represent some special values:

  • −0.0: IEEE 754 floating-point numbers have a bit that indicates their sign, so −0.0 is apossible value. For comparison −0.0 = +0.0, but floating-point operations can carrythe sign bit through arithmetic operations. This means −0.0 × +0.0 produces −0.0 anda negative number rounded to a value smaller than a float can represent also produces −0.0.
  • and−∞: these result from calculationslike 1.0 / 0.0.
  • NaN (not a number): this value results fromcalculations like (-1.0).sqrt(). NaN has some potentially unexpectedbehavior:
    • It is not equal to any float, including itself! This is the reason f32doesn’t implement the Eq trait.
    • It is also neither smaller nor greater than any float, making itimpossible to sort by the default comparison operation, which is thereason f32 doesn’t implement the Ord trait.
    • It is also considered infectious as almost all calculations where oneof the operands is NaN will also result in NaN. The explanations on thispage only explicitly document behavior on NaN operands if this defaultis deviated from.
    • Lastly, there are multiple bit patterns that are considered NaN.Rust does not currently guarantee that the bit patterns of NaN arepreserved over arithmetic operations, and they are not guaranteed to beportable or even fully deterministic! This means that there may be somesurprising results upon inspecting the bit patterns,as the same calculations might produce NaNs with different bit patterns.This also affects the sign of the NaN: checking is_sign_positive or is_sign_negative ona NaN is the most common way to run into these surprising results.(Checking x >= 0.0 or x <= 0.0 avoids those surprises, but also how negative/positivezero are treated.)See the section below for what exactly is guaranteed about the bit pattern of a NaN.

When a primitive operation (addition, subtraction, multiplication, or division) is performed on this type, the result is rounded according to the roundTiesToEven direction defined in IEEE 754-2008. That means:

  • The result is the representable value closest to the true value, if thereis a unique closest representable value.
  • If the true value is exactly half-way between two representable values,the result is the one with an even least-significant binary digit.
  • If the true value’s magnitude is ≥ f32::MAX + 2(f32::MAX_EXPf32::MANTISSA_DIGITS − 1), the result is ∞ or −∞ (preserving thetrue value’s sign).
  • If the result of a sum exactly equals zero, the outcome is +0.0 unlessboth arguments were negative, then it is -0.0. Subtraction a - b isregarded as a sum a + (-b).

For more information on floating-point numbers, see Wikipedia.

See also the std::f32::consts module.

NaN bit patterns

This section defines the possible NaN bit patterns returned by floating-point operations.

The bit pattern of a floating-point NaN value is defined by:

  • a sign bit.
  • a quiet/signaling bit. Rust assumes that the quiet/signaling bit being set to 1 indicates aquiet NaN (QNaN), and a value of 0 indicates a signaling NaN (SNaN). In the following wewill hence just call it the “quiet bit”.
  • a payload, which makes up the rest of the significand (i.e., the mantissa) except for thequiet bit.

The rules for NaN values differ between arithmetic and non-arithmetic (or “bitwise”) operations. The non-arithmetic operations are unary -, abs, copysign, signum, {to,from}_bits, {to,from}_{be,le,ne}_bytes and is_sign_{positive,negative}. These operations are guaranteed to exactly preserve the bit pattern of their input except for possibly changing the sign bit.

The following rules apply when a NaN value is returned from an arithmetic operation:

  • The result has a non-deterministic sign.

  • The quiet bit and payload are non-deterministically chosen from the following set of options:

    • Preferred NaN: The quiet bit is set and the payload is all-zero.
    • Quieting NaN propagation: The quiet bit is set and the payload is copied from any inputoperand that is a NaN. If the inputs and outputs do not have the same payload size (i.e., foras casts), then
      • If the output is smaller than the input, low-order bits of the payload get dropped.
      • If the output is larger than the input, the payload gets filled up with 0s in the low-orderbits.
    • Unchanged NaN propagation: The quiet bit and payload are copied from any input operandthat is a NaN. If the inputs and outputs do not have the same size (i.e., for as casts), thesame rules as for “quieting NaN propagation” apply, with one caveat: if the output is smallerthan the input, dropping the low-order bits may result in a payload of 0; a payload of 0 is notpossible with a signaling NaN (the all-0 significand encodes an infinity) so unchanged NaNpropagation cannot occur with some inputs.
    • Target-specific NaN: The quiet bit is set and the payload is picked from a target-specificset of “extra” possible NaN payloads. The set can depend on the input operand values.See the table below for the concrete NaNs this set contains on various targets.

In particular, if all input NaNs are quiet (or if there are no input NaNs), then the output NaN is definitely quiet. Signaling NaN outputs can only occur if they are provided as an input value. Similarly, if all input NaNs are preferred (or if there are no input NaNs) and the target does not have any “extra” NaN payloads, then the output NaN is guaranteed to be preferred.

The non-deterministic choice happens when the operation is executed; i.e., the result of a NaN-producing floating-point operation is a stable bit pattern (looking at these bits multiple times will yield consistent results), but running the same operation twice with the same inputs can produce different results.

These guarantees are neither stronger nor weaker than those of IEEE 754: IEEE 754 guarantees that an operation never returns a signaling NaN, whereas it is possible for operations like SNAN * 1.0 to return a signaling NaN in Rust. Conversely, IEEE 754 makes no statement at all about which quiet NaN is returned, whereas Rust restricts the set of possible results to the ones listed above.

Unless noted otherwise, the same rules also apply to NaNs returned by other library functions (e.g. min, minimum, max, maximum); other aspects of their semantics and which IEEE 754 operation they correspond to are documented with the respective functions.

When an arithmetic floating-point operation is executed in const context, the same rules apply: no guarantee is made about which of the NaN bit patterns described above will be returned. The result does not have to match what happens when executing the same code at runtime, and the result can vary depending on factors such as compiler version and flags.

Target-specific “extra” NaN values

target_arch Extra payloads possible on this platform
aarch64, arm, arm64ec, loongarch64, powerpc (except when target_abi = "spe"), powerpc64, riscv32, riscv64, s390x, x86, x86_64 None
nvptx64 All payloads
sparc, sparc64 The all-one payload
wasm32, wasm64 If all input NaNs are quiet with all-zero payload: None.
Otherwise: all payloads.

For targets not in this table, all payloads are possible.

Algebraic operators

Algebraic operators of the form a.algebraic_*(b) allow the compiler to optimize floating point operations using all the usual algebraic properties of real numbers – despite the fact that those properties do not hold on floating point numbers. This can give a great performance boost since it may unlock vectorization.

The exact set of optimizations is unspecified but typically allows combining operations, rearranging series of operations based on mathematical properties, converting between division and reciprocal multiplication, and disregarding the sign of zero. This means that the results of elementary operations may have undefined precision, and “non-mathematical” values such as NaN, +/-Inf, or -0.0 may behave in unexpected ways, but these operations will never cause undefined behavior.

Because of the unpredictable nature of compiler optimizations, the same inputs may produce different results even within a single program run. Unsafe code must not rely on any property of the return value for soundness. However, implementations will generally do their best to pick a reasonable tradeoff between performance and accuracy of the result.

For example:

x = a.algebraic_add(b).algebraic_add(c).algebraic_add(d);

May be rewritten as:

x = a + b + c + d; // As written
x = (a + c) + (b + d); // Reordered to shorten critical path and enable vectorization
svg::node::element::SVG
fn append<T>(&mut self, node: T)
where
    T: Into<Box<dyn Node>>,

Append a child node.

svg
pub fn save<T, U>(path: T, document: &U) -> Result<()>
where
    T: AsRef<Path>,
    U: Node,

Save a document.

core::result::Result
Ok(T)

Contains the success value

core::macros::builtin
macro_rules! line

Expands to the line number on which it was invoked.

With column and file, these macros provide debugging information for developers about the location within the source.

The expanded expression has type u32 and is 1-based, so the first line in each file evaluates to 1, the second to 2, etc. This is consistent with error messages by common compilers or popular editors. The returned line is not necessarily the line of the line! invocation itself, but rather the first macro invocation leading up to the invocation of the line! macro.

Examples

let current_line = line!();
println!("defined on line: {current_line}");
let line: {unknown}
let rand_num: {unknown}
codeintel::block_7636ed3a23a75a7c
fn line(start: (i32, i32), end: (i32, i32), color: &str) -> Path
color: &str
str

String slices.

See also the std::str module.

The str type, also called a ‘string slice’, is the most primitive string type. It is usually seen in its borrowed form, &str. It is also the type of string literals, &'static str.

Basic Usage

String literals are string slices:

let hello_world = "Hello, World!";

Here we have declared a string slice initialized with a string literal. String literals have a static lifetime, which means the string hello_world is guaranteed to be valid for the duration of the entire program. We can explicitly specify hello_world’s lifetime as well:

let hello_world: &'static str = "Hello, world!";

Representation

A &str is made up of two components: a pointer to some bytes, and a length. You can look at these with the [as_ptr] and [len] methods:

use std::slice;
use std::str;

let story = "Once upon a time...";

let ptr = story.as_ptr();
let len = story.len();

// story has nineteen bytes
assert_eq!(19, len);

// We can re-build a str out of ptr and len. This is all unsafe because
// we are responsible for making sure the two components are valid:
let s = unsafe {
    // First, we build a &[u8]...
    let slice = slice::from_raw_parts(ptr, len);

    // ... and then convert that slice into a string slice
    str::from_utf8(slice)
};

assert_eq!(s, Ok(story));

Note: This example shows the internals of &str. unsafe should not be used to get a string slice under normal circumstances. Use as_str instead.

Invariant

Rust libraries may assume that string slices are always valid UTF-8.

Constructing a non-UTF-8 string slice is not immediate undefined behavior, but any function called on a string slice may assume that it is valid UTF-8, which means that a non-UTF-8 string slice can lead to undefined behavior down the road.