schemars_derive/
regex_syntax.rs

1#![allow(clippy::all)]
2// Copied from regex_syntax crate to avoid pulling in the whole crate just for a utility function
3// https://github.com/rust-lang/regex/blob/431c4e4867e1eb33eb39b23ed47c9934b2672f8f/regex-syntax/src/lib.rs
4//
5// Copyright (c) 2014 The Rust Project Developers
6//
7// Permission is hereby granted, free of charge, to any
8// person obtaining a copy of this software and associated
9// documentation files (the "Software"), to deal in the
10// Software without restriction, including without
11// limitation the rights to use, copy, modify, merge,
12// publish, distribute, sublicense, and/or sell copies of
13// the Software, and to permit persons to whom the Software
14// is furnished to do so, subject to the following
15// conditions:
16//
17// The above copyright notice and this permission notice
18// shall be included in all copies or substantial portions
19// of the Software.
20//
21// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
22// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
23// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
24// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
25// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
26// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
28// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
29// DEALINGS IN THE SOFTWARE.
30
31pub fn escape(text: &str) -> String {
32    let mut quoted = String::new();
33    escape_into(text, &mut quoted);
34    quoted
35}
36
37fn escape_into(text: &str, buf: &mut String) {
38    buf.reserve(text.len());
39    for c in text.chars() {
40        if is_meta_character(c) {
41            buf.push('\\');
42        }
43        buf.push(c);
44    }
45}
46
47fn is_meta_character(c: char) -> bool {
48    match c {
49        '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '|' | '[' | ']' | '{' | '}' | '^' | '$'
50        | '#' | '&' | '-' | '~' => true,
51        _ => false,
52    }
53}