This library implements the flip-flop operator from Perl and Ruby as a Rust macro.

Overview

flip_flop.rs

This library implements the flip-flop operator from Perl and Ruby as a Rust macro.

Changelog

  • April 1, 2024: Version 1.0.0.

Usage

The flip_flop! macro accepts two boolean expressions wrapped in parentheses and separated by either 2 dots (..) or 3 dots (...):

flip_flop!((x == 5)..(x == 10))
// or
flip_flop!((x == 5)...(x == 10))

The macro returns true from when the left expression is true until the right expression is true by maintaining a hidden bool state.

The difference between .. and ... is that with ..., the right expression is also evaluated when the left expression first becomes true, which makes it possible for the flip-flop internal state to be reset in the same iteration. This behavior matches that of Perl.

The internal state of the operator is stored in a static AtomicBool and is therefore shared among threads, mirroring the behavior of Perl.

Example

The print statement in the following code is executed from when i == 5 becomes true until i == 10 becomes true.

use flip_flop::flip_flop;

fn main() {
    for i in 0..20 {
        // Prints 5, 6, 7, 8, 9, 10.
        if flip_flop!((i == 5)..(i == 10)) {
            println!("{i}")
        }
    }
}

Output:

5
6
7
8
9
10

Extracting Sequence Example

The following code extracts all sequences starting with 1 followed by any numbers until finding a 2.

use flip_flop::flip_flop;

fn main() {
    let xs = [0, 1, 2, 0, 0, 1, 0, 2, 0, 0, 0, 0, 2, 2, 2, 0, 1, 1, 2, 0];

    let ys = xs
        .into_iter()
        .filter(|&x| flip_flop!((x == 1)..(x == 2)))
        .collect::<Vec<_>>();

    println!("Original: {:?}", xs);
    println!("Filtered: {:?}", ys);
}

Output:

Original: [0, 1, 2, 0, 0, 1, 0, 2, 0, 0, 0, 0, 2, 2, 2, 0, 1, 1, 2, 0]
Filtered: [1, 2, 1, 0, 2, 1, 1, 2]

FizzBuzz Example

This is the classic FizzBuzz problem implemented using the flip-flop operator. Source.

use flip_flop::flip_flop;

// https://juliansimioni.com/blog/deconstructing-fizz-buzz-with-flip-flops-in-ruby
fn main() {
    let (mut a, mut b, mut c) = (false, false, false);

    for i in 1..=100 {
        #[rustfmt::skip]
        println!(
            "{}\r{}{}",
            i,
            if flip_flop!(({a = !a; a})..({a = !a; a})) { "" } else { "Fizz" },
            if flip_flop!(({b = !b; b})...(!flip_flop!(({c = !c; c})..({c = !c; c})))) { "" } else { "Buzz" },
        );
    }
}

Output (after removing text hidden by \r):

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
…

Bugs

The behavior of this crate should match that of Perl and Ruby, but there may be edge cases that are not handled correctly. If you find any, please open an issue (or a pull request)!

License

This project is licensed under either of

at your option.

You might also like...
High performance Rust ECS library
High performance Rust ECS library

Legion aims to be a feature rich high performance Entity component system (ECS) library for Rust game projects with minimal boilerplate. Getting Start

Rust library to create a Good Game Easily

ggez What is this? ggez is a Rust library to create a Good Game Easily. The current version is 0.6.0-rc0. This is a RELEASE CANDIDATE version, which m

Rust bindings for libtcod 1.6.3 (the Doryen library/roguelike toolkit)

Warning: Not Maintained This project is no longer actively developed or maintained. Please accept our apologies. Open pull requests may still get merg

a rust library to find near-duplicate video files

Video Duplicate Finder vid_dup_finder finds near-duplicate video files on disk. It detects videos whose frames look similar, and where the videos are

A Rust library for blitting 2D sprites
A Rust library for blitting 2D sprites

blit A Rust library for blitting 2D sprites Documentation Usage Add this to your Cargo.toml:

FPS library for gdnative written in Rust.

gd_rusty_fps FPS library for gdnative written in Rust. This projects aims to create easy to use .dll library to be used with godot engine for FPS game

A low-level library for OpenGL context creation, written in pure Rust.

glutin - OpenGL, UTilities and INput A low-level library for OpenGL context creation, written in pure Rust. [dependencies] glutin = "0.28.0" Documenta

A low-level library for OpenGL context creation, written in pure Rust.

glutin - OpenGL, UTilities and INput A low-level library for OpenGL context creation, written in pure Rust. [dependencies] glutin = "0.28.0" Documenta

Pleco is a chess Engine & Library derived from Stockfish, written entirely in Rust

Pleco Pleco is a chess Engine & Library derived from Stockfish, written entirely in Rust. This project is split into two crates, pleco, which contains

Owner
Utkarsh Kukreti
Utkarsh Kukreti
Implements the Smart Contract for the Unity Proposal.

cw-unity-prop A CosmWasm Smart Contract to implement the Juno Unity Prop. For information on verifying the on-chain smart contract, see VERIFYING.md.

Junø 5 Apr 27, 2022
A convenient on-screen message print macro for bevy.

Bevy Debug Text Overlay A proof of concept for adding a very convenient text overlay macro to the bevy game engine. This is derived from the code I us

Nicola Papale 15 Oct 8, 2022
This is the core library with the full abstraction and implementation of the Minecraft protocol and logic. (Currently WIP)

MineRust (WIP) This is the core library with the full abstraction and implementation of the Minecraft protocol and logic. This project is currently WI

MineRust Project Suite 2 Nov 20, 2022
A Rust wrapper and bindings of Allegro 5 game programming library

RustAllegro A thin Rust wrapper of Allegro 5. Game loop example extern crate allegro; extern crate allegro_font; use allegro::*; use allegro_font::*;

null 80 Dec 31, 2022
A Rust library for reading asset files and resource packs for any version of Minecraft

minecraft-assets A Rust library for reading asset files and resource packs for any version of Minecraft. Example use minecraft_assets::api::AssetPack;

Ben Reeves 7 Aug 14, 2022
Rust library to download and run Minecraft instances.

Rust library to download and run Minecraft instances. Build the code To build the library, the do the following command: carbo build Run the example Y

Louis Bailleau 3 Oct 19, 2022
A simple and minimal game engine library built in rust.

Neptune A brand new free, open-source minimal and compact game engine built in rust. Design Goals We plan to make Neptune a small and minimal engine,

Levitate 17 Jan 25, 2023
Scion is a tiny 2D game library built on top of wgpu, winit and legion.

Scion is a 2D game library made in rust. Please note that this project is in its first milestones and is subject to change according to convience need

Jérémy Thulliez 143 Dec 25, 2022
Tiny cross-platform webview library for C/C++/Golang. Uses WebKit (Gtk/Cocoa) and Edge (Windows)

webview A tiny cross-platform webview library for C/C++/Golang to build modern cross-platform GUIs. Also, there are Rust bindings, Python bindings, Ni

webview 10.8k Jan 9, 2023
Plotting library for the Bevy game engine with a focus on esthetics and interactivity

Plotting library for the Bevy game engine with a focus on esthetics and interactivity. It can handle both data points (see the "minimal", "markers", a

Eli 40 Dec 25, 2022