Giter VIP home page Giter VIP logo

unfmt's Introduction

unfmt

crates.io license ci docs

unfmt is a compile-time pattern matching library that reverses the interpolation process of format!.

You can think of it as an extremely lightweight regular expression engine without the runtime pattern-compilation cost.

Installation

cargo add -D unfmt

Usage

let value = "My name is Rho.";

// Unnamed captures are returned as tuples.
assert_eq!(
    unformat!("My {} is {}.", value),
    Some(("name", "Rho"))
);

// You can put indices as well; just make sure ALL captures use indices
// otherwise it's not well defined.
assert_eq!(
    unformat!("My {1} is {0}.", value),
    Some(("Rho", "name"))
);

// You can also name captures using variables, but make sure you check the
// return is not None.
let mut subject = None;
let mut object = None;
assert_eq!(
    unformat!("My {subject} is {object}.", value),
    Some(())
);
assert_eq!((subject, object), (Some("name"), Some("Rho")));

// If you want to ensure the entire string matches, you can add `true` to the end of the macro.
assert_eq!(unformat!("{1} is {0}", value, true), None);

// If a type implements `FromStr`, you can use it as a type argument. This
// is written as `{:Type}`.
assert_eq!(
    unformat!("Listening on {:url::Url}", "Listening on http://localhost:3000"),
    Some((url::Url::from_str("http://localhost:3000").unwrap(),))
);

In general, captures are written as {<index-or-variable>:<type>}. Multiple captures in a row (i.e. {}{}) are not supported as they aren't well-defined.

Limitations

  • There is no backtracking.

unfmt's People

Contributors

renovate[bot] avatar jun-sheaf avatar dependabot[bot] avatar release-please[bot] avatar thecaralice avatar

Stargazers

Lubomir Anastasov avatar Andrei N. Onea avatar Najman Husaini avatar  avatar Geoffrey Mureithi avatar Amjad Alsharafi avatar Rob Ede avatar Stanislav Tkach avatar cjw avatar Oleksii Karpenko avatar Crypto-Spartan avatar  avatar Paul Young avatar  avatar Aleksandr Liashenko avatar Gil Shoshan avatar Chrs Msln avatar Byeongjee Kang avatar Weiss avatar Jocelyn Boullier avatar  avatar Kernkraft avatar  avatar  avatar multisn8 avatar Hai-Hsin avatar Caspar Krieger avatar sqyyy avatar Kyosuke Fujimoto avatar  avatar Christopher avatar Egor Lynov avatar Maksim Muruev avatar  avatar orociic avatar  avatar Rafał Krzyważnia avatar Jordan Moore avatar Martin Mareš avatar Adam Thibert avatar Miki Oracle avatar Nonne avatar Laurent Quérel avatar david avatar WukongRework.exe BROKE avatar Ted Feng avatar  avatar Erich Gubler avatar Wyatt Stanke avatar Noah avatar Kristoffer Plagborg Bak Sørensen avatar Noah Gude avatar matthiasg avatar Omid Rad avatar  avatar  avatar Miaxos avatar Mathieu Lala avatar yibit avatar David Brochero avatar Yannick Wagner avatar Dan Kolsoi avatar Kevin Li avatar ik5 avatar Benno Straub avatar  avatar Wyatt Herkamp avatar Vlad Frolov avatar Andrew Wheeler(Genusis) avatar Félix Saparelli avatar V. Can Keklik avatar Jörg Singer avatar mario avatar Ryo Hirayama avatar  avatar Romain Ruetschi avatar Jip J. Dekker avatar A.M. Smith avatar  avatar Grégoire Henry avatar Michael Cheng avatar Manuel Holtgrewe avatar Michael Velbaum avatar Sebastian Thiel avatar Wenxuan avatar Michael Diamond avatar Muhammad Ragib Hasin avatar Felix G. Knorr avatar LIU JIE avatar Yashodhan avatar Souvik avatar Liam avatar Thomas Buckley-Houston avatar Ivan Krivosheev avatar Scott Wey avatar  avatar Rano | Ranadeep avatar Ivan Anishchuk avatar  avatar Diana avatar

Watchers

 avatar  avatar

unfmt's Issues

Parsing the whole string

AFAICS the macro searches for a match anywhere in the string provided, which allows "x{}y" to match not only "xAy" but also things like "BxAyC". Is it possible to disable that behaviour, like using ^$ with regex?

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

cargo
Cargo.toml
  • bstr 1.9.1
unfmt_macros/Cargo.toml
  • bstr 1.9.1
  • syn 2.0.60
  • quote 1.0.36
  • proc-macro2 1.0.81
github-actions
.github/workflows/ci.yaml
  • actions/checkout 692973e3d937129bcbf40652eb9f2f61becf3332
  • taiki-e/install-action a03b7590b9c92f2296cfa3e064ecfe4089c032be
  • actions/checkout 692973e3d937129bcbf40652eb9f2f61becf3332
  • taiki-e/install-action a03b7590b9c92f2296cfa3e064ecfe4089c032be
  • actions/checkout 692973e3d937129bcbf40652eb9f2f61becf3332
  • taiki-e/install-action a03b7590b9c92f2296cfa3e064ecfe4089c032be
  • romeovs/lcov-reporter-action 87a815f34ec27a5826abba44ce09bbc688da58fd
.github/workflows/publish.yaml
  • actions/checkout 692973e3d937129bcbf40652eb9f2f61becf3332
regex
.github/workflows/ci.yaml
  • cargo-deny 0.14.24
  • cargo-udeps 0.1.48
  • cargo-hack 0.6.28
  • cargo-hack 0.6.28
  • cargo-llvm-cov 0.6.10
  • cargo-hack 0.6.28

  • Check this box to trigger a request for Renovate to run again on this repository

"unexpected end of input, expected boolean literal" when `unformat!` call takes multiple lines

I am trying to use this to parse some log files and in the following example:

            if let Some((_, _, now)) = unformat!("{} {} Time is now {:f64}", line) {
                t = now;
            } else if let Some((_, _, tag, p)) = unformat!("{} {} {} took {:usize}us", line) {
                timings.entry(tag.to_string()).or_default().push((t, p));
            } else if let Some((_, _, not_picked, picked, assigned, freebots)) = unformat!(
                "{} {} Number of Tasks: {:usize} + {:usize} = {:usize} + {:usize}",
                line,
            ) {
                nbr.push((t, not_picked, picked, assigned, freebots))
            }

I get the above error on the last call where you can see the parameters are spread over multiple lines.

crate does not re-export `bstr`, therefore requires users to add this dependency

hey, on my machine this example

use unfmt::unformat;

fn main() {
    unformat!("hello", world);
}

in Cargo.toml:

[dependencies]
unfmt = { git = "https://github.com/mathematic-inc/unfmt.git" }

...results in

error[E0432]: unresolved import `bstr`

I believe this is because the macro expansion includes use ::bstr::{ByteSlice, BStr};.
this means a user would need to add bstr as a dependency - see this Stack Overflow question.

afaik, there are ways to deal with this, such as re-exporting.

The return type is inconsistent in case of a singular capture

  • unformat!("foo", input) returns an Option<()>
  • unformat!("foo{:u8}bar") returns an Option<u8>
  • unformat!("foo{:u8}bar{:u8}baz") returns an Option<(u8, u8)>
  • unformat!("foo{:u8}bar{:u8}baz{:u8}qux") returns an Option<(u8, u8, u8)>
  • unformat!("foo{:u8}bar{:u8}baz{:u8}qux{:u8}quux") returns an Option<(u8, u8, u8, u8)>

IMHO the second one should return Option<(u8,)> for consistency instead

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.