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.

docs.rs
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(..) => { /* … */ },
                    _ => {}
                }
            }
        }
        _ => {}
    }
}
docs.rs
svg
pub mod node

The nodes.

docs.rs
svg::node
pub mod element

The element nodes.

docs.rs
svg::node::element
pub mod path

The path element.

docs.rs
svg::node::element::path::data
pub struct Data(/* … */);

A data attribute.

docs.rs
svg::node::element
pub struct Path { /* … */ }

A path element.

docs.rs
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
end: (i32, i32)
docs.rs
svg::node::element::Path
pub fn new() -> Self

Create a node.

docs.rs
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.

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

Create a data attribute.

docs.rs
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.

docs.rs
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.

docs.rs
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>>
docs.rs
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.

docs.rs
alloc::boxed
pub struct Box<T, A = Global>(/* … */)
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 #t-libs.

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 strs 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)
docs.rs
std
pub mod error

Interfaces for working with Errors.

Error Handling In Rust

The Rust language provides two complementary systems for constructing / representing, reporting, propagating, reacting to, and discarding errors. These responsibilities are collectively known as “error handling.” The components of the first system, the panic runtime and interfaces, are most commonly used to represent bugs that have been detected in your program. The components of the second system, Result, the error traits, and user defined types, are used to represent anticipated runtime failure modes of your program.

The Panic Interfaces

The following are the primary interfaces of the panic system and the responsibilities they cover:

The following are the primary interfaces of the error system and the responsibilities they cover:

  • Result (Propagating, Reacting)
  • The Error trait (Reporting)
  • User defined types (Constructing / Representing)
  • match and downcast (Reacting)
  • The question mark operator (?) (Propagating)
  • The partially stable Try traits (Propagating, Constructing)
  • Termination (Reporting)

Converting Errors into Panics

The panic and error systems are not entirely distinct. Oftentimes errors that are anticipated runtime failures in an API might instead represent bugs to a caller. For these situations the standard library provides APIs for constructing panics with an Error as its source.

These functions are equivalent, they either return the inner value if the Result is Ok or panic if the Result is Err printing the inner error as the source. The only difference between them is that with expect you provide a panic error message to be printed alongside the source, whereas unwrap has a default message indicating only that you unwrapped an Err.

Of the two, expect is generally preferred since its msg field allows you to convey your intent and assumptions which makes tracking down the source of a panic easier. unwrap on the other hand can still be a good fit in situations where you can trivially show that a piece of code will never panic, such as "127.0.0.1".parse::<std::net::IpAddr>().unwrap() or early prototyping.

Common Message Styles

There are two common styles for how people word expect messages. Using the message to present information to users encountering a panic (“expect as error message”) or using the message to present information to developers debugging the panic (“expect as precondition”).

In the former case the expect message is used to describe the error that has occurred which is considered a bug. Consider the following example:

// Read environment variable, panic if it is not present
let path = std::env::var("IMPORTANT_PATH").unwrap();

In the “expect as error message” style we would use expect to describe that the environment variable was not set when it should have been:

let path = std::env::var("IMPORTANT_PATH")
    .expect("env variable `IMPORTANT_PATH` is not set");

In the “expect as precondition” style, we would instead describe the reason we expect the Result should be Ok. With this style we would prefer to write:

let path = std::env::var("IMPORTANT_PATH")
    .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`");

The “expect as error message” style does not work as well with the default output of the std panic hooks, and often ends up repeating information that is already communicated by the source error being unwrapped:

thread 'main' panicked at src/main.rs:4:6:
env variable `IMPORTANT_PATH` is not set: NotPresent

In this example we end up mentioning that an env variable is not set, followed by our source message that says the env is not present, the only additional information we’re communicating is the name of the environment variable being checked.

The “expect as precondition” style instead focuses on source code readability, making it easier to understand what must have gone wrong in situations where panics are being used to represent bugs exclusively. Also, by framing our expect in terms of what “SHOULD” have happened to prevent the source error, we end up introducing new information that is independent from our source error.

thread 'main' panicked at src/main.rs:4:6:
env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`: NotPresent

In this example we are communicating not only the name of the environment variable that should have been set, but also an explanation for why it should have been set, and we let the source error display as a clear contradiction to our expectation.

Hint: If you’re having trouble remembering how to phrase expect-as-precondition style error messages remember to focus on the word “should” as in “env variable should be set by blah” or “the given binary should be available and executable by the current user”.

docs.rs
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
core::ops::arith
impl Div for i32
fn div(self, other: i32) -> i32

Performs the / operation.

Example

assert_eq!(12 / 2, 6);
let output_file: &str
let viewbox: (i32, i32, i32, i32)
let mut document: SVG
docs.rs
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}
docs.rs
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.

docs.rs
rand::rngs::std
pub struct StdRng(/* … */);

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
docs.rs
core::ops::range
pub struct Range<Idx> {
    pub start: Idx,
    pub end: Idx,
}

A (half-open) range bounded inclusively below and exclusively above (start..end).

The range start..end contains all values with start <= x < end. It is empty if start >= end.

Examples

The start..end syntax is a Range:

assert_eq!((3..5), std::ops::Range { start: 3, end: 5 });
assert_eq!(3 + 4 + 5, (3..6).sum());
let arr = [0, 1, 2, 3, 4];
assert_eq!(arr[ ..  ], [0, 1, 2, 3, 4]);
assert_eq!(arr[ .. 3], [0, 1, 2      ]);
assert_eq!(arr[ ..=3], [0, 1, 2, 3   ]);
assert_eq!(arr[1..  ], [   1, 2, 3, 4]);
assert_eq!(arr[1.. 3], [   1, 2      ]); // This is a `Range`
assert_eq!(arr[1..=3], [   1, 2, 3   ]);
docs.rs
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
let x: i32
let line: ()
f32
docs.rs
core::cmp::PartialOrd
pub trait PartialOrd<Rhs = Self>
pub fn gt(&self, other: &Rhs) -> bool
where
    // Bounds from trait:
    Self: PartialEq<Rhs> + PointeeSized,
    Rhs: PointeeSized,

Tests greater than (for self and other) and is used by the > operator.

Examples

assert_eq!(1.0 > 1.0, false);
assert_eq!(1.0 > 2.0, false);
assert_eq!(2.0 > 1.0, true);
core::ops::arith
impl Add for i32
fn add(self, other: i32) -> i32

Performs the + operation.

Example

assert_eq!(12 + 1, 13);
svg::node::element::SVG
impl Node for SVG
fn append<T>(&mut self, node: T)
where
    T: Into<Box<dyn Node>>,

Append a child node.

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

Save a document.

docs.rs
core::result::Result
impl<T, E> ops::Try for Result<T, E>
fn branch(self) -> ControlFlow<Self::Residual, Self::Output>

Used in ? to decide whether the operator should produce a value (because this returned ControlFlow::Continue) or propagate a value back to the caller (because this returned ControlFlow::Break).

Examples

#![feature(try_trait_v2)]
use std::ops::{ControlFlow, Try};

assert_eq!(Ok::<_, String>(3).branch(), ControlFlow::Continue(3));
assert_eq!(Err::<String, _>(3).branch(), ControlFlow::Break(Err(3)));

assert_eq!(Some(3).branch(), ControlFlow::Continue(3));
assert_eq!(None::<String>.branch(), ControlFlow::Break(None));

assert_eq!(ControlFlow::<String, _>::Continue(3).branch(), ControlFlow::Continue(3));
assert_eq!(
    ControlFlow::<_, String>::Break(3).branch(),
    ControlFlow::Break(ControlFlow::Break(3)),
);
core::result::Result
Ok(T)

Contains the success value

docs.rs
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}");
docs.rs
core::ops::arith::Add
pub trait Add<Rhs = Self>
pub fn add(self, rhs: Rhs) -> Self::Output

Performs the + operation.

Example

assert_eq!(12 + 1, 13);
let line: {unknown}
docs.rs
core::ops::arith::Div
pub trait Div<Rhs = Self>
pub fn div(self, rhs: Rhs) -> Self::Output

Performs the / operation.

Example

assert_eq!(12 / 2, 6);
docs.rs
core::ops::arith::Sub
pub trait Sub<Rhs = Self>
pub fn sub(self, rhs: Rhs) -> Self::Output

Performs the - operation.

Example

assert_eq!(12 - 1, 11);
docs.rs
core::ops::arith::Mul
pub trait Mul<Rhs = Self>
pub fn mul(self, rhs: Rhs) -> Self::Output

Performs the * operation.

Example

assert_eq!(12 * 2, 24);
let rand_num: {unknown}
docs.rs
core::cmp::PartialOrd
pub trait PartialOrd<Rhs = Self>
pub fn lt(&self, other: &Rhs) -> bool
where
    // Bounds from trait:
    Self: PartialEq<Rhs> + PointeeSized,
    Rhs: PointeeSized,

Tests less than (for self and other) and is used by the < operator.

Examples

assert_eq!(1.0 < 1.0, false);
assert_eq!(1.0 < 2.0, true);
assert_eq!(2.0 < 1.0, false);
codeintel::block_7636ed3a23a75a7c
fn line(start: (i32, i32), end: (i32, i32), color: &str) -> Path
color: &str
str