• Stars
    star
    950
  • Rank 46,203 (Top 1.0 %)
  • Language
    Rust
  • License
    The Unlicense
  • Created almost 9 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A fast implementation of Aho-Corasick in Rust.

aho-corasick

A library for finding occurrences of many patterns at once with SIMD acceleration in some cases. This library provides multiple pattern search principally through an implementation of the Aho-Corasick algorithm, which builds a finite state machine for executing searches in linear time. Features include case insensitive matching, overlapping matches, fast searching via SIMD and optional full DFA construction and search & replace in streams.

Build status crates.io

Dual-licensed under MIT or the UNLICENSE.

Documentation

https://docs.rs/aho-corasick

Usage

Run cargo add aho-corasick to automatically add this crate as a dependency in your Cargo.toml file.

Example: basic searching

This example shows how to search for occurrences of multiple patterns simultaneously. Each match includes the pattern that matched along with the byte offsets of the match.

use aho_corasick::{AhoCorasick, PatternID};

let patterns = &["apple", "maple", "Snapple"];
let haystack = "Nobody likes maple in their apple flavored Snapple.";

let ac = AhoCorasick::new(patterns).unwrap();
let mut matches = vec![];
for mat in ac.find_iter(haystack) {
    matches.push((mat.pattern(), mat.start(), mat.end()));
}
assert_eq!(matches, vec![
    (PatternID::must(1), 13, 18),
    (PatternID::must(0), 28, 33),
    (PatternID::must(2), 43, 50),
]);

Example: ASCII case insensitivity

This is like the previous example, but matches Snapple case insensitively using AhoCorasickBuilder:

use aho_corasick::{AhoCorasick, PatternID};

let patterns = &["apple", "maple", "snapple"];
let haystack = "Nobody likes maple in their apple flavored Snapple.";

let ac = AhoCorasick::builder()
    .ascii_case_insensitive(true)
    .build(patterns)
    .unwrap();
let mut matches = vec![];
for mat in ac.find_iter(haystack) {
    matches.push((mat.pattern(), mat.start(), mat.end()));
}
assert_eq!(matches, vec![
    (PatternID::must(1), 13, 18),
    (PatternID::must(0), 28, 33),
    (PatternID::must(2), 43, 50),
]);

Example: replacing matches in a stream

This example shows how to execute a search and replace on a stream without loading the entire stream into memory first.

use aho_corasick::AhoCorasick;

let patterns = &["fox", "brown", "quick"];
let replace_with = &["sloth", "grey", "slow"];

// In a real example, these might be `std::fs::File`s instead. All you need to
// do is supply a pair of `std::io::Read` and `std::io::Write` implementations.
let rdr = "The quick brown fox.";
let mut wtr = vec![];

let ac = AhoCorasick::new(patterns).unwrap();
ac.stream_replace_all(rdr.as_bytes(), &mut wtr, replace_with)
    .expect("stream_replace_all failed");
assert_eq!(b"The slow grey sloth.".to_vec(), wtr);

Example: finding the leftmost first match

In the textbook description of Aho-Corasick, its formulation is typically structured such that it reports all possible matches, even when they overlap with another. In many cases, overlapping matches may not be desired, such as the case of finding all successive non-overlapping matches like you might with a standard regular expression.

Unfortunately the "obvious" way to modify the Aho-Corasick algorithm to do this doesn't always work in the expected way, since it will report matches as soon as they are seen. For example, consider matching the regex Samwise|Sam against the text Samwise. Most regex engines (that are Perl-like, or non-POSIX) will report Samwise as a match, but the standard Aho-Corasick algorithm modified for reporting non-overlapping matches will report Sam.

A novel contribution of this library is the ability to change the match semantics of Aho-Corasick (without additional search time overhead) such that Samwise is reported instead. For example, here's the standard approach:

use aho_corasick::AhoCorasick;

let patterns = &["Samwise", "Sam"];
let haystack = "Samwise";

let ac = AhoCorasick::new(patterns).unwrap();
let mat = ac.find(haystack).expect("should have a match");
assert_eq!("Sam", &haystack[mat.start()..mat.end()]);

And now here's the leftmost-first version, which matches how a Perl-like regex will work:

use aho_corasick::{AhoCorasick, MatchKind};

let patterns = &["Samwise", "Sam"];
let haystack = "Samwise";

let ac = AhoCorasick::builder()
    .match_kind(MatchKind::LeftmostFirst)
    .build(patterns)
    .unwrap();
let mat = ac.find(haystack).expect("should have a match");
assert_eq!("Samwise", &haystack[mat.start()..mat.end()]);

In addition to leftmost-first semantics, this library also supports leftmost-longest semantics, which match the POSIX behavior of a regular expression alternation. See MatchKind in the docs for more details.

Minimum Rust version policy

This crate's minimum supported rustc version is 1.60.0.

The current policy is that the minimum Rust version required to use this crate can be increased in minor version updates. For example, if crate 1.0 requires Rust 1.20.0, then crate 1.0.z for all values of z will also require Rust 1.20.0 or newer. However, crate 1.y for y > 0 may require a newer minimum version of Rust.

In general, this crate will be conservative with respect to the minimum supported version of Rust.

FFI bindings

More Repositories

1

ripgrep

ripgrep recursively searches directories for a regex pattern while respecting your gitignore
Rust
45,030
star
2

xsv

A fast CSV command line toolkit written in Rust.
Rust
10,084
star
3

toml

TOML parser for Golang with reflection.
Go
4,407
star
4

quickcheck

Automated property based testing for Rust (with shrinking).
Rust
2,269
star
5

erd

Translates a plain text description of a relational database schema to a graphical entity-relationship diagram.
Haskell
1,757
star
6

fst

Represent large sets and maps compactly with finite state transducers.
Rust
1,712
star
7

rust-csv

A CSV parser for Rust, with Serde support.
Rust
1,603
star
8

nflgame

An API to retrieve and read NFL Game Center JSON data. It can work with real-time data, which can be used for fantasy football.
Python
1,257
star
9

walkdir

Rust library for walking directories recursively.
Rust
1,179
star
10

nfldb

A library to manage and update NFL data in a relational database.
Python
1,067
star
11

wingo

A fully-featured window manager written in Go.
Go
958
star
12

byteorder

Rust library for reading/writing numbers in big-endian and little-endian.
Rust
927
star
13

memchr

Optimized string search routines for Rust.
Rust
758
star
14

bstr

A string type for Rust that is not required to be valid UTF-8.
Rust
744
star
15

xgb

The X Go Binding is a low-level API to communicate with the X server. It is modeled on XCB and supports many X extensions.
Go
472
star
16

advent-of-code

Rust solutions to AoC 2018
Rust
469
star
17

termcolor

Cross platform terminal colors for Rust.
Rust
446
star
18

rust-snappy

Snappy compression implemented in Rust (including the Snappy frame format).
Rust
432
star
19

go-sumtype

A simple utility for running exhaustiveness checks on Go "sum types."
Go
409
star
20

chan

Multi-producer, multi-consumer concurrent channel for Rust.
Rust
392
star
21

regex-automata

A low level regular expression library that uses deterministic finite automata.
Rust
354
star
22

cargo-benchcmp

A small utility to compare Rust micro-benchmarks.
Rust
337
star
23

suffix

Fast suffix arrays for Rust (with Unicode support).
Rust
254
star
24

rure-go

Go bindings to Rust's regex engine.
Go
246
star
25

tabwriter

Elastic tabstops for Rust.
Rust
244
star
26

imdb-rename

A command line tool to rename media files based on titles from IMDb.
Rust
221
star
27

critcmp

A command line tool for comparing benchmarks run by Criterion.
Rust
198
star
28

rebar

A biased barometer for gauging the relative speed of some regex engines on a curated set of tasks.
Python
197
star
29

ty

Easy parametric polymorphism at run time using completely unidiomatic Go.
Go
197
star
30

xgbutil

A utility library to make use of the X Go Binding easier. (Implements EWMH and ICCCM specs, key binding support, etc.)
Go
191
star
31

pytyle3

An updated (and much faster) version of pytyle that uses xpybutil and is compatible with Openbox Multihead.
Python
181
star
32

dotfiles

My configuration files and personal collection of scripts.
Vim Script
141
star
33

rsc-regexp

Translations of a simple C program to Rust.
Rust
133
star
34

rust-cbor

CBOR (binary JSON) for Rust with automatic type based decoding and encoding.
Rust
127
star
35

chan-signal

Respond to OS signals with channels.
Rust
126
star
36

goim

Goim is a robust command line utility to maintain and query the Internet Movie Database (IMDb).
Go
117
star
37

clibs

A smattering of miscellaneous C libraries. Includes sane argument parsing, a thread-safe multi-producer/multi-consumer queue, and implementation of common data structures (hashmaps, vectors and linked lists).
C
98
star
38

same-file

Cross platform Rust library for checking whether two file paths are the same file.
Rust
98
star
39

nflvid

An experimental library to map play meta data to footage of that play.
Python
90
star
40

ucd-generate

A command line tool to generate Unicode tables as source code.
Rust
90
star
41

rust-stats

Basic statistical functions on streams for Rust.
Rust
86
star
42

migration

Package migration for Golang automatically handles versioning of a database schema by applying a series of migrations supplied by the client.
Go
79
star
43

xpybutil

An incomplete xcb-util port plus some extras
Python
62
star
44

graphics-go

Automatically exported from code.google.com/p/graphics-go
Go
59
star
45

winapi-util

Safe wrappers for various Windows specific APIs.
Rust
57
star
46

rust-pcre2

High level Rust bindings to PCRE2.
C
51
star
47

rust-sorts

Implementations of common sorting algorithms in Rust with comprehensive tests and benchmarks.
Rust
51
star
48

blog

My blog.
Rust
50
star
49

openbox-multihead

Openbox with patches for enhanced multihead support.
C
46
star
50

nakala

A low level embedded information retrieval system.
Rust
45
star
51

nflfan

View your fantasy teams with nfldb using a web interface.
JavaScript
43
star
52

utf8-ranges

Convert contiguous ranges of Unicode codepoints to UTF-8 byte ranges.
Rust
43
star
53

rtmpdump-ksv

rtmpdump with ksv's patch. Intended to track upstream git://git.ffmpeg.org/rtmpdump as well.
C
40
star
54

globset

A globbing library for Rust.
Rust
39
star
55

regexp

A regular expression library implemented in Rust.
Rust
37
star
56

xdg

A Go package for reading config and data files according to the XDG Base Directory specification.
Go
35
star
57

locker

A simple Golang package for conveniently using named read/write locks. Useful for synchronizing access to session based storage in web applications.
Go
34
star
58

nflcmd

A collection of command line utilities for viewing NFL statistics and rankings with nfldb.
Python
30
star
59

notes

A collection of small notes that aren't appropriate for my blog.
30
star
60

mempool

A fast thread safe memory pool for reusing allocations.
Rust
29
star
61

gribble

A command oriented language whose environment is defined through Go struct types by reflection.
Go
28
star
62

vcr

A simple wrapper tool around ffmpeg to capture video from a VCR.
Rust
27
star
63

encoding_rs_io

Streaming I/O adapters for the encoding_rs crate.
Rust
22
star
64

rust-cmail

A simple command line utility for periodically sending email containing the output of long-running commands.
Rust
21
star
65

cluster

A simple API for managing a network cluster with smart peer discovery.
Go
19
star
66

pager-multihead

A pager that supports per-monitor desktops (compatible with Openbox Multihead and Wingo)
Python
15
star
67

rg-cratesio-typosquat

The source code of the 'rg' crate. It is an intentional typo-squat that redirects folks to 'ripgrep'.
Rust
15
star
68

imgv

An image viewer for Linux written in Go.
Go
14
star
69

cablastp

Performs BLAST on compressed proteomic data.
Go
14
star
70

rust-error-handling-case-study

Code for the case study in my blog post: http://blog.burntsushi.net/rust-error-handling
Rust
14
star
71

cmd

A convenience library for executing commands in Go, including executing commands in parallel with a pool.
Go
14
star
72

cmail

cmail runs a command and sends the output to your email address at certain intervals.
Go
12
star
73

fanfoot

View your fantasy football leagues and get text alerts when one of your players scores.
Python
12
star
74

burntsushi-blog

A small Go application for my old blog.
CSS
12
star
75

gohead

An xrandr wrapper script to manage multi-monitor configurations. With hooks.
Go
12
star
76

intern

A simple package for interning strings, with a focus on efficiently representing dense pairwise data.
Go
11
star
77

crev-proofs

My crev reviews.
10
star
78

pytyle1

A lightweight X11 tool for simulating tiling in a stacking window manager.
Python
9
star
79

rucd

WIP
Rust
8
star
80

qcsv

An API to read and analyze CSV files by inferring types for each column of data.
Python
8
star
81

cif

A golang package for reading and writing data in the Crystallographic Information File (CIF) format. It mostly conforms to the CIF 1.1 specification.
Go
8
star
82

pyndow

A window manager written in Python
Python
8
star
83

csql

Package csql provides convenience functions for use with the types and functions defined in the standard library `database/sql` package.
Go
6
star
84

freetype-go

A fork of freetype-go with bounding box calculations.
Go
6
star
85

sqlsess

Simple database backed session management. Integrates with Gorilla's sessions package.
Go
6
star
86

go-wayland-simple-shm

C
5
star
87

sqlauth

A simple Golang package that provides database backed user authentication with bcrypt.
Vim Script
4
star
88

lcmweb

A Go web application for coding documents with the Linguistic Category Model.
JavaScript
4
star
89

bcbgo

Computational biology tools for the BCB group at Tufts University.
Go
4
star
90

fex

A framework for specifying and executing experiments.
Haskell
3
star
91

present

My presentations.
HTML
3
star
92

memchr-2.6-mov-regression

Rust
3
star
93

genecentric

A tool to generate between-pathway modules and perform GO enrichment on them.
Python
3
star
94

rust-docs

A silly repo for managing my Rust crate documentation.
Python
3
star
95

pcre2-mirror

A git mirror for PCRE2's SVN repository at svn://vcs.exim.org/pcre2/code
2
star
96

xpyb

A clone of xorg-xpyb.
C
2
star
97

burntsushi-homepage

A small PHP web application for my old homepage.
PHP
2
star
98

window-marker

Use vim-like marks on windows.
Python
2
star
99

sudoku

An attempt at a sudoku solver in Haskell.
Haskell
1
star
100

play

Testing stuff.
1
star