Skip to content
amberframeworkPublic

About

Amber's pure-Crystal parsing library: linear-time regex, gzip/zlib/DEFLATE, XML and UTF-8, under work budgets and deadlines

Topics

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Mica: reads untrusted bytes, never guesses. Mica, the Amber crew's reader, at a lectern in a library, beside her character mark. A loupe sweeps across a request line and lights up the date a regex matches.

Pure Crystal · No PCRE2, no libz, no libxml2 · Linear-time search · Work budgets and deadlines · v0.3.0 · MIT

Mica is Amber's pure-Crystal parsing library.
Regex, gzip, zlib, DEFLATE, XML and UTF-8, with a work budget and a deadline on every parse.


Install

dependencies:
  mica:
    github: amberframework/mica
    version: 0.3.0
require "mica"

Note

0.3.0 has Mica::Regex, Mica::XML, Mica::YAML, DEFLATE (Mica::Deflate, Mica::Zlib, Mica::Gzip), Mica::Brotli, Mica::Encoding, and the HTTP/2 frame codec and HPACK (Mica::HTTP2, Mica::HPACK).

Two ways to use it

1. Mica's own API, on any Crystal compiler

limits = Mica::Regex::SearchLimits::REQUEST
date = Mica::Regex::Expression.new("(?<year>\\d{4})-(?<month>\\d{2})",
  compile_limits: Mica::Regex::CompileLimits::TRUSTED_PATTERN)
date.match("due 2026-11", limits: limits).try(&.["year"]) # => "2026"

# Compiled while the app builds: read-only tables, no allocation per search.
SLUG = Mica::Regex.static(/\A[a-z0-9]+(?:-[a-z0-9]+)*\z/)
SLUG.matches?("pure-crystal-parsing") # => true

body = Mica::Gzip.decode(gzipped, limits: Mica::Deflate::DecodeLimits::REQUEST_BODY, timeout: 2.seconds)
document = Mica::XML.parse(File.read("feed.xml"))

Mica::Regex::Expression follows stdlib Regex method for method, plus the limits. Guides: Regex · Inflate · HTTP/2 and HPACK · YAML · XML.

2. Crystal's own Regex on Mica, with crystal-alpha

crystal-alpha build -Duse_mica src/app.cr

With -Duse_mica, Crystal's own Regex (regex literals, $~, String#match, gsub, scan, split) runs on Mica with no code changes, and the binary links no PCRE2. It arrived in crimson-knight/crystal#17 (merged).

Important

This is opt-in today. PCRE2 stays the default without the flag, and stock Crystal does not have -Duse_mica: it needs the crystal-alpha compiler.

What Mica leaves out, and the rewrite

Mica's searches run in time linear in the input, so it refuses the constructs that need backtracking. Mica::Regex raises UnsupportedConstructError naming the construct and its byte; under -Duse_mica, a regex literal that uses one is a compile error.

Instead of Write Then, in Crystal
Backreference (\w+) \1 (\w+) (\w+) match[1] == match[2]
Lookahead \d+(?= USD) (\d+) USD use match[1]
Lookbehind (?<=\$)\d+ \$(\d+) use match[1]
Negative lookahead \A(?!admin\z)\w+\z \A\w+\z && name != "admin"
Atomic group (?>a+), possessive a++ a+ nothing: Mica never backtracks

The full list (recursion, conditionals, \K, verbs, newline conventions) is in Excluded constructs.

Speed

Mica::Regex against PCRE2 with JIT, geometric means over 479 cases. Compiled at run time: warm search 2.4× as fast (29.85 µs vs 72.39 µs), compile 1.7× as fast, cold first search 3.0× as fast, process-cold 2.3× as fast. Mica::Regex.static over 412 cases: warm search 2.0×, compile 24×, cold first search 11×, process-cold 6.2× as fast. The 26 patterns Amber apps run, process-cold, against PCRE2 with JIT: routes 2.5× as fast, templates 2.6×, Markdown 2.8×, logs 2.6×, CSV 2.7×, contacts 2.1×, identifiers 2.9×. All 104 Amber cases: 2.6× as fast (210.91 µs vs 552.64 µs). Hostile patterns finish. Over 112 ReDoS cases Mica::Regex is 8.8× as fast on warm search (330.1 ns vs 2.91 µs) and hits no limit, where PCRE2 with JIT stopped on a limit 28 times and timed out once. All 13 ReDoS families finish inside 1,000 ms, with linear growth.
See it run: the ReDoS corpus in a terminal
Terminal output of bench/regex/run.sh on the ReDoS corpus. At 262,144 and 1,048,576 input units, pcre2-jit lines end in 'JIT stack limit reached' or 'match limit exceeded', while every mica line reads ok with its warm, compile and process-cold times.

bench/regex/run.sh --quick --corpora redos --engines pcre2-jit,mica, run on 2026-11-22 at main (25b5280). PCRE2-JIT stops on its stack or match limit; Mica finishes all 143 cases.

Inflate against system zlib 1.2.12, geometric means over 93 cases. One-shot: 1.09× as fast, 74 of 93 cases at or above zlib. Streaming with 64 KiB buffers: 1.12× as fast, 92 of 93 cases at or above zlib.

Regex numbers come from the full harness at commit f0bb0f6, the code tagged v0.2.0; Inflate numbers from the Z3 run at 8c1f61e (2026-11-22), every case listed in docs/benchmarks.md. How they are measured, and how to rerun them: docs/benchmarks.md.

How a search runs

flowchart TD
    source(["Pattern text"]) --> parser["Parser<br/>Crystal dialect, PCRE2 syntax"]
    parser -- "backreference, lookaround ..." --> refused{{"UnsupportedConstructError<br/>names the construct and byte"}}
    parser --> limits["Compile limits<br/>size preflight"]
    limits --> hir["Hir<br/>Unicode 17 classes, case folding"]
    hir --> compiler["Compiler<br/>byte-level NFA program"]
    static(["Mica::Regex.static<br/>tables built at app build time"]) --> plan
    compiler --> plan{"Search plan<br/>picked per search"}
    plan --> fast["Required bytes<br/>literal prefilters"]
    plan --> dfa["One-pass DFA<br/>lazy DFAs, forward and reverse"]
    plan --> nfa["Pike VM<br/>bounded backtracker"]
    fast --> found(["Match"])
    dfa --> found
    nfa --> found
    budget[["Work budget + deadline<br/>charged on every step"]] -.-> fast
    budget -.-> dfa
    budget -.-> nfa
    classDef step fill:#FFFDF9,stroke:#D9AD7E,color:#211914
    classDef brass fill:#FFC777,stroke:#A93D08,color:#211914
    classDef stop fill:#F47A16,stroke:#A93D08,color:#211914
    class parser,limits,hir,compiler,fast,dfa,nfa step
    class source,static,found,plan brass
    class refused,budget stop
Loading

Every engine is linear in the input; the plan only picks the fastest one that fits the pattern and the question asked.

Formats

Module Reads Guide
Mica::Regex Regular expressions in Crystal's PCRE2 syntax, linear-time docs/regex.md
Mica::Gzip, Mica::Zlib, Mica::Deflate gzip (RFC 1952, multi-member), zlib (RFC 1950), raw DEFLATE (RFC 1951); one-shot and streaming, decoding under limits and encoding at levels 0 to 9 docs/compression.md
Mica::HTTP2, Mica::HPACK HTTP/2 frames (RFC 9113: the client preface and the 10 frame types, sans-IO, parsed and serialized) and HPACK header compression (RFC 7541: decoder under limits, deterministic encoder). On main, ships in the next release docs/http2.md
Mica::YAML YAML 1.2 (402 of 402 yaml-test-suite cases) and a libyaml 0.2.5 dialect: pull parser, node API with aliases and merge keys, emitter. On main, ships in the next release docs/yaml.md
Mica::XML XML 1.0 and 1.1 with Namespaces: streaming reader, DOM, builder, XPath 1.0 docs/xml.md
Mica::Decimal128, Mica::Currency, Mica::Money Exact decimals of up to 38 digits (12.30 stays 12.30), every ISO 4217 currency, and money that splits without losing a cent; no libgmp. On main, ships in the next release docs/decimal.md
Mica::Core Strict UTF-8, UTF-16/UTF-32/ISO-8859-1 transcoding, positions, limits, work budgets docs/ADDING_A_FORMAT.md

More formats (JSON, CBOR, HTTP/1.1, URIs, multipart, CSV, TOML, Markdown) plug into the same core.

Exact money

Mica::Decimal128 is an exact decimal of up to 38 digits in a 128-bit integer and a scale, and Mica::Money pairs it with an ISO 4217 currency. Nothing rounds unless you name the rounding, nothing overflows silently, and a split never loses a cent:

require "mica/decimal"

price = Mica::Decimal128.parse("19.99")
tax = (price * Mica::Decimal128.parse("0.0825")).round(2, :ties_away) # => 1.65
Mica::Money.new(price + tax, "USD").to_s                              # => "21.64 USD"
Mica::Money.new("100.00", "USD").split(3).map(&.to_s)                 # => ["33.34 USD", "33.33 USD", "33.33 USD"]
Mica::Decimal128.parse("0.1") + Mica::Decimal128.parse("0.2") == Mica::Decimal128.parse("0.3") # => true

Arithmetic, comparison and rounding allocate nothing and run many times faster than BigDecimal, with 0 differences from it over 1,000,000 random operations. JSON, YAML and BigDecimal conversions are opt-in. Details and timings: docs/decimal.md.

Safe by default

Mica is built for bytes from strangers: request bodies, uploads, storage listings.

  • Work budgets. Every parse and search counts its work and stops at its allowance, so no input can buy superlinear time.
  • Deadlines. A timeout adds a wall-clock limit, checked as the work runs.
  • Limits. Output size, decompression ratio, entity expansion, nesting depth and pattern size are capped before the bytes they guard are written.
  • No fetching. Mica never reads the network or the file system while parsing.
  • No C parsers. A Mica program links only libgc, libiconv and libSystem, which Crystal itself needs (scripts/check_linkage.sh).

Tip

Each format ships presets for the common jobs, such as SearchLimits::REQUEST and DecodeLimits::REQUEST_BODY. Start from one and tighten it.

Found a way past a limit? Please report it privately: SECURITY.md.

Questions

Why no backreferences or lookaround?

They need backtracking, and backtracking is what lets one hostile input stall a server (ReDoS). Mica keeps every search linear instead. Each construct has a short rewrite above, usually one capture group and one comparison in Crystal.

Does my app still link PCRE2?

With Mica's own API, Mica adds no PCRE2, but Crystal's stdlib Regex still uses it wherever your code or your shards do. Build with crystal-alpha and -Duse_mica to move all of it onto Mica and drop the library.

I use stdlib XML. How much changes?

Mostly the name: XML becomes Mica::XML. Parsing is strict (the first error raises), and nodes are small structs. The differences are listed in docs/xml.md.

Is Inflate as fast as zlib?

On the geometric mean, yes: against system zlib 1.2.12 over 93 cases, one-shot decoding is 1.09× as fast and streaming 1.12× as fast. Not yet on every case: 19 one-shot cases are still slower, the slowest http/json_1m.json as raw DEFLATE (1.21× slower); one streaming case is 1.01× slower. The list is in docs/benchmarks.md.

Development

shards-alpha install --frozen
crystal-alpha build $(find spec -name '*_spec.cr' | sort) -o bin/specs && bin/specs
crystal-alpha tool format --check
scripts/check_linkage.sh     # no PCRE2, libz, libyaml, libxml2 or libgmp in a Mica program
bench/regex/run.sh --quick   # Mica::Regex against PCRE2
bench/deflate/run.sh --quick # Inflate against zlib
bench/yaml/run.sh            # Mica::YAML against libyaml

Fuzzing, conformance suites and the XML benchmarks: docs/xml.md, docs/regex.md, docs/compression.md, docs/yaml.md and docs/benchmarks.md. Requirement ids in spec/requirements/*.tsv map each standard's sections to the specs that cover them.

Something off? Open an issue. Questions go to SUPPORT.md.

License

MIT. src/mica/xml/composing_characters.cr is generated from the Unicode 17.0.0 character data that ships with the Crystal standard library, under the Unicode License v3.


Amber Framework

Part of the Amber framework. Built and maintained by

AgentC Consulting

About

Amber's pure-Crystal parsing library: linear-time regex, gzip/zlib/DEFLATE, XML and UTF-8, under work budgets and deadlines

Topics

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages