The cumulative sibling of `Result` and `Either`.

Overview

validated

The cumulative sibling of Result and Either.

The Validated type has special FromIterator instances that enable all errors in a sequence to be reported, not just the first one.

Motivation

We might think of Iterator::collect as being for consolidating the result of some chained iteration into a concrete container, like Vec.

let v = vec![1,2,3];
assert_eq!(vec![2,4,6], v.into_iter().map(|n| n * 2).collect::<Vec<u32>>());

But collect isn't limited to this; it can be used to "fold" down into any type you like, provided that it implements FromIterator. Consider the effects of such an impl for Result:

let v: Vec<u32> = vec![1, 2, 3];
let r: Result<Vec<u32>, &str> = v
    .into_iter()
    .map(|n| if n % 2 == 0 { Err("Oh no!") } else { Ok(n * 2) })
    .collect();
assert_eq!(Err("Oh no!"), r);

The Result has been "interweaved" and pulled back out. Critically, this collect call short-circuits; n * 2 is never called for 3, since the map "fails" at 2. This is useful when we require a sequence of IO actions to all succeed and we wish to cancel remaining operations as soon as any error occurs.

But what if we don't want to short circuit? What if we want a report of all the errors that occurred?

Cumulative Errors and Validated

Consider three cases where we'd want a report of all errors, not just the first one:

  1. Form input validation.
  2. Type checking.
  3. Concurrent IO.

In the first case, if a user makes several input mistakes, it's the best experience for them if all errors are reported at once so that they can make their corrections in a single pass.

In the second case, knowing only the first detected type error might not actually be the site of the real issue. We need everything that's broken to be reported so we can make the best decision of what to fix.

In the third case, it may be that halting your entire concurrent job upon detection of a single failure isn't appropriate. You might instead want everything to finish as it can, and then collect a bundle of errors at the end.

The Validated type accomodates these use cases; it is a "cumulative Result".

, &str> = Fail(NonEmpty::from(("No!", vec!["Ack!"]))); assert_eq!(r, v.into_iter().collect()); ">
use validated::Validated::{self, Good, Fail};
use nonempty::NonEmpty;

let v = vec![Good(1), Validated::fail("No!"), Good(3), Validated::fail("Ack!")];
let r: Validated<Vec<u32>, &str> = Fail(NonEmpty::from(("No!", vec!["Ack!"])));
assert_eq!(r, v.into_iter().collect());

Use of NonEmpty

In the spirit of "make illegal states unrepresentable", the Fail variant of Validated contains a NonEmpty, a non-empty Vec. NonEmpty can do everything that Vec can do, plus some additional benefits. In the case of this crate, this representation forbids the otherwise meaningless Fail(vec![]).

In other words, if you have a Validated, you either have a concrete T, or at least one E.

Features

  • rayon: Enable FromParallelIterator instances for Validated.

Resources

License: MIT

You might also like...
The simplest way to de-Google your life and business: Inbox, Calendar, Files, Contacts & much more
The simplest way to de-Google your life and business: Inbox, Calendar, Files, Contacts & much more

Bloom The all-in-one private workspace Try it for free! You no longer trust tech monopolies with your data? You are done with your privacy invaded by

MeiliSearch is a powerful, fast, open-source, easy to use and deploy search engine
MeiliSearch is a powerful, fast, open-source, easy to use and deploy search engine

MeiliSearch is a powerful, fast, open-source, easy to use and deploy search engine. Both searching and indexing are highly customizable. Features such as typo-tolerance, filters, and synonyms are provided out-of-the-box. For more information about features go to our documentation.

A job queue built on sqlx and PostgreSQL.

sqlxmq A job queue built on sqlx and PostgreSQL. This library allows a CRUD application to run background jobs without complicating its deployment. Th

Modify fonts to remove bitmap and disable gridfit for Windows font rendering.

Since Windows 10 version 1703 (Creators Update), its built-in TrueType renderer now supports vertical anti-aliasing. Despite there are only 30 levels of grayscale shade, it dramatically improves text rendering, especially for CJK languages. Sadly, it is only enabled for selected fonts at selected sizes.

An example project demonstrating integration with Rust for the ESP32-S2 and ESP32-C3 microcontrollers.

Rust ESP32 Example An example project demonstrating integration with Rust for the ESP32-S2 and ESP32-C3 microcontrollers.

Small and simple stateful applications, designed to facilitate the monitoring of unwanted behaviors of the same.

Violet Violet é um pequeno e simples monitorador de aplicação, voltado para receber eventos de erro e estado. Instalação simples: Dependencias: Docker

Vue, React, Solid, Angular, Svelte, and Liquid From JS Objects.

Vue, React, Solid, Angular, Svelte, and Liquid From JS Objects.

Meteor Client Installer - Installer to automate the install of Fabric and Meteor Client
Meteor Client Installer - Installer to automate the install of Fabric and Meteor Client

This is an installer that automates the install of Meteor and Fabric

dm-jitaux is a Rust-based JIT compiler using modified auxtools, dmasm and Inkwell LLVM wrapper for boosting Byond DM performance without any hassle!

dm-jitaux is a Rust-based JIT compiler using modified auxtools, dmasm and Inkwell LLVM wrapper for boosting Byond DM performance without any hassle (such as rewriting/refactroing your DM code).

Releases(v0.1.1)
Owner
Colin Woodbury
I write Rust, Haskell, and Go. 現在カナダで開発。
Colin Woodbury
CLI tool that make it easier to perform multiple lighthouse runs towards a single target and output the result in a "plotable" format.

Lighthouse Groupie CLI tool that make it easier to perform multiple lighthouse runs towards a single target and output the result in a "plotable" form

Polestar 1 Jan 12, 2022
A (mostly) drop-in replacement for Rust's Result that provides backtrace support

Errant A (mostly) drop-in replacement for Rust's Result that provides backtrace support. Please note that Errant is still very early in development an

Joshua Barretto 17 Dec 26, 2022
A Rust proc-macro crate which derives functions to compile and parse back enums and structs to and from a bytecode representation

Bytecode A simple way to derive bytecode for you Enums and Structs. What is this This is a crate that provides a proc macro which will derive bytecode

null 4 Sep 3, 2022
A library and tool for automata and formal languages, inspired by JFLAP

Sugarcubes is a library and application for automata and formal languages. It is inspired by JFLAP, and is intended to eventually to be an alternative to JFLAP.

Henry Sloan 22 Nov 2, 2022
A stupid macro that compiles and executes Rust and spits the output directly into your Rust code

inline-rust This is a stupid macro inspired by inline-python that compiles and executes Rust and spits the output directly into your Rust code. There

William 19 Nov 29, 2022
This is a Discord bot written in Rust to translate to and from the Bottom Encoding Standard using bottom-rs and Serenity.

bottom-bot This is a Discord bot written in Rust to translate to and from the Bottom Encoding Standard using bottom-rs and Serenity. Ever had this pro

Bottom Software Foundation 11 Dec 10, 2022
An implementation of Code Generation and Factoring for Fast Evaluation of Low-order Spherical Harmonic Products and Squares

sh_product An implementation of Code Generation and Factoring for Fast Evaluation of Low-order Spherical Harmonic Products and Squares (paper by John

Simon Brown 7 Dec 2, 2022
lightweight and customizable rust s-expression (s-expr) parser and printer

s-expr Rust library for S-expression like parsing and printing parser keeps track of spans, and representation (e.g. number base) number and decimal d

Vincent Hanquez 5 Oct 26, 2022
Crates Registry is a tool for serving and publishing crates and serving rustup installation in offline networks.

Crates Registry Description Crates Registry is a tool for serving and publishing crates and serving rustup installation in offline networks. (like Ver

TalYRoni 5 Jul 6, 2023
Simplify temporary email management and interaction, including message retrieval and attachment downloads, using Rust.

Tempmail The Tempmail simplifies temporary email management and interaction, including message retrieval and attachment downloads, using the Rust prog

Dilshad 6 Sep 21, 2023