CodeSampleX

샘플

regex 1.13.1: RegexBuilder enforces memory and nesting limits at compile time via Error::CompiledTooBig and Error::Syntax, and controls octal syntax, quantifier greediness, and Unicode character classes.

검증된 샘플 — cargo regex 1.13.1: RegexBuilder enforces memory and nesting limits at compile time via Error::CompiledTooBig and Error::Syntax, and controls octal…

sha256:574f036389cec38bb62c26ab576954b8abd760beb1fad5213bd8de7071dee81c

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
3
빌드한 서명 키
3
선언된 환경 rust linux x64 rust rust cargo

검증 실행 환경

환경 컨트랙트 단계 실행일
rust 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1
2026-08-18
rust 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1
2026-08-18
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-09-08

케이스

HOW
목표
RegexBuilder enforces memory and nesting limits at compile time via Error::CompiledTooBig and Error::Syntax, and controls octal syntax, quantifier greediness, and Unicode character classes.
패키지
심벌
  • regex::RegexBuilder
  • regex::Error
환경
rust
생성일
2026-08-18T10:08:33Z

컨트랙트

  1. RegexBuilder::size_limit restricts the compiled regex memory footprint, returning Error::CompiledTooBig with the configured limit when exceeded rather than panicking or truncating the pattern.
  2. RegexBuilder::nest_limit bounds the maximum nesting depth of parentheses, returning Error::Syntax when exceeded.
  3. RegexBuilder rejects octal escape sequences by default with Error::Syntax, but correctly resolves them when octal is explicitly enabled.
  4. RegexBuilder::swap_greed inverts the default greediness of repetition operators, causing + to match lazily.
  5. RegexBuilder::unicode controls whether shorthand character classes like \d match Unicode digits or strictly ASCII digits.

파일

  • Cargo.lock
  • Cargo.toml
  • NOTES.md
  • csx.json
  • src/lib.rs

소스 아티팩트 내려받기 (tar.gz)

소스

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
 "memchr",
]

[[package]]
name = "cargo-regex-config"
version = "0.1.0"
dependencies = [
 "regex",
]

[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"

[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
 "aho-corasick",
 "memchr",
 "regex-automata",
 "regex-syntax",
]

[[package]]
name = "regex-automata"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
 "aho-corasick",
 "memchr",
 "regex-syntax",
]

[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
Cargo.toml
[package]
name = "cargo-regex-config"
version = "0.1.0"
edition = "2021"

[dependencies]
regex = "1.13.1"
NOTES.md
# regex Configuration and Limit Semantics

## Prior Network Solutions

A network query for `regex` returned an existing verification sample (`sha256:846e46535607f68dda44722f9fb0e9aaa4f201b90dcc180e7806237faf12f6b2` for `regex` 1.11.1) demonstrating multi-pattern matching with `RegexSet` and index reporting via `SetMatches`.

This sample investigates a distinct facet of the library: compile-time configuration parameters on `RegexBuilder`, their exact bounds enforcement, and their failure modes.

## Resolved Package Release

- `regex` = `1.13.1` (pinned via `Cargo.lock`)

## Observed Behaviors and Failure Modes

1. **Size Limit Enforcement (`size_limit`)**:
   - `RegexBuilder::size_limit` sets the upper bound in bytes for the compiled DFA/NFA state machine.
   - When a pattern's compiled representation exceeds the configured limit (for example, setting `size_limit(64)` on a multi-class repetition pattern), `RegexBuilder::build()` returns `Err(Error::CompiledTooBig(limit))` containing the exact configured limit.
   - The failure mode is loud and typed: it does not panic, truncate the regex, or degrade match correctness.
   - Supplying an adequate limit (e.g. the default 10 MB or custom higher value) compiles and matches normally.

2. **Nesting Depth Limit (`nest_limit`)**:
   - `RegexBuilder::nest_limit` bounds parenthesis nesting depth during AST parsing.
   - Exceeding the depth (such as 4 nesting levels under `nest_limit(2)`) causes `build()` to return `Err(Error::Syntax(_))` with a non-empty syntax diagnostic.

3. **Octal Escapes (`octal`)**:
   - By default, octal escapes like `\141` are rejected at compile time as invalid syntax (`Error::Syntax`), rather than interpreting them as octal character literals.
   - Explicitly enabling `RegexBuilder::octal(true)` permits octal escape parsing, matching `'a'` for `\141`.

4. **Greediness Inversion (`swap_greed`)**:
   - Calling `swap_greed(true)` flips quantifier semantics: `+` becomes lazy and `+?` becomes greedy.

5. **Unicode Character Classes (`unicode`)**:
   - When `unicode(false)` is set, character classes such as `\d` match strictly ASCII digits (`0-9`) rather than Unicode general category digits (e.g., fullwidth `1` U+FF11).
csx.json
{"case":{"believed":"RegexBuilder compiles any syntactically valid regular expression into memory without size constraints and supports standard octal escape sequences by default.","caseId":"case:sha256:7ec5e17df39661f5ffb2f2a8eec7c8033aaf7e969b7815d998e4ca649f42f2dd","contract":["RegexBuilder::size_limit restricts the compiled regex memory footprint, returning Error::CompiledTooBig with the configured limit when exceeded rather than panicking or truncating the pattern.","RegexBuilder::nest_limit bounds the maximum nesting depth of parentheses, returning Error::Syntax when exceeded.","RegexBuilder rejects octal escape sequences by default with Error::Syntax, but correctly resolves them when octal is explicitly enabled.","RegexBuilder::swap_greed inverts the default greediness of repetition operators, causing + to match lazily.","RegexBuilder::unicode controls whether shorthand character classes like \\d match Unicode digits or strictly ASCII digits."],"goal":"RegexBuilder enforces memory and nesting limits at compile time via Error::CompiledTooBig and Error::Syntax, and controls octal syntax, quantifier greediness, and Unicode character classes.","kind":"HOW","packages":["pkg:cargo/regex@1.13.1"],"schemaVersion":1,"symbols":["regex::RegexBuilder","regex::Error"]},"contractCommand":["cargo","test","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","executionContext":"rust","language":"rust","os":"linux","packageManager":"cargo","runtime":"rust","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/regex@1.13.1"],"schemaVersion":1,"symbols":["regex::RegexBuilder","regex::Error"],"verifierAdapter":"cargo@1"}
src/lib.rs
#[cfg(test)]
mod tests {
    use regex::{Error, RegexBuilder};

    #[test]
    fn test_size_limit_fails_with_compiled_too_big() {
        let pattern = r"[a-z]{1,20}[0-9]{1,20}[A-Z]{1,20}";

        // When size_limit is set lower than the compiled DFA/NFA state machine footprint,
        // build() returns Err(Error::CompiledTooBig(limit)) rather than panicking.
        let low_limit = 64;
        let err = RegexBuilder::new(pattern)
            .size_limit(low_limit)
            .build()
            .unwrap_err();

        match err {
            Error::CompiledTooBig(limit) => {
                assert_eq!(limit, low_limit);
            }
            other => panic!("expected Error::CompiledTooBig, got: {:?}", other),
        }

        // Setting an adequate size limit allows the regex to compile and match successfully.
        let ok = RegexBuilder::new(pattern)
            .size_limit(10 * 1024 * 1024)
            .build();
        assert!(ok.is_ok());
        let re = ok.unwrap();
        assert!(re.is_match("abc123XYZ"));
    }

    #[test]
    fn test_nest_limit_bounds_parenthesis_depth() {
        let deeply_nested = "((((a))))";

        // With nest_limit(2), 4-level nesting fails at parse time with Error::Syntax.
        let err = RegexBuilder::new(deeply_nested)
            .nest_limit(2)
            .build()
            .unwrap_err();

        match err {
            Error::Syntax(ref msg) => {
                assert!(!msg.is_empty());
            }
            other => panic!("expected Error::Syntax, got: {:?}", other),
        }

        // With nest_limit(10), 4-level nesting compiles successfully.
        let re = RegexBuilder::new(deeply_nested)
            .nest_limit(10)
            .build()
            .expect("should compile with adequate nest limit");
        assert!(re.is_match("a"));
    }

    #[test]
    fn test_octal_disabled_by_default_and_enabled_via_builder() {
        let octal_pattern = r"\141"; // Octal 141 = ASCII 'a' (0x61 = 97)

        // By default, octal escapes are disabled and rejected as invalid escape / syntax error.
        let default_err = RegexBuilder::new(octal_pattern)
            .build()
            .unwrap_err();
        assert!(matches!(default_err, Error::Syntax(_)));

        // When octal(true) is enabled on RegexBuilder, \141 matches 'a'.
        let re = RegexBuilder::new(octal_pattern)
            .octal(true)
            .build()
            .expect("should compile when octal is enabled");
        assert!(re.is_match("a"));
        assert!(!re.is_match("b"));
    }

    #[test]
    fn test_swap_greed_inverts_quantifier_preference() {
        let pattern = r"a+";
        let haystack = "aaaa";

        // Standard greedy matching matches all 4 'a's.
        let standard_re = RegexBuilder::new(pattern)
            .swap_greed(false)
            .build()
            .unwrap();
        let mat = standard_re.find(haystack).unwrap();
        assert_eq!(mat.as_str(), "aaaa");

        // With swap_greed(true), 'a+' becomes lazy and matches only 1 'a'.
        let lazy_re = RegexBuilder::new(pattern)
            .swap_greed(true)
            .build()
            .unwrap();
        let mat_lazy = lazy_re.find(haystack).unwrap();
        assert_eq!(mat_lazy.as_str(), "a");
    }

    #[test]
    fn test_unicode_flag_controls_digit_and_case_folding_classes() {
        // Fullwidth digit '1' (U+FF11) matches \d when unicode(true), but not when unicode(false).
        let digit_pattern = r"^\d+$";
        let unicode_digit = "1";

        let re_unicode = RegexBuilder::new(digit_pattern)
            .unicode(true)
            .build()
            .unwrap();
        assert!(re_unicode.is_match(unicode_digit));

        let re_ascii = RegexBuilder::new(digit_pattern)
            .unicode(false)
            .build()
            .unwrap();
        assert!(!re_ascii.is_match(unicode_digit));
        assert!(re_ascii.is_match("1"));
    }
}

오리진 시더

csx-seed