We do a lot of queries for fields having a specific prefix. The only way(?) to do this in MongoDB is using a regex. To do this for an arbitrary input string it needs to be escaped.
Possible alternative is to use regex-syntax/regex-lite's escape function. These don't escape the NUL byte which is needed for bson::Regex's CString pattern. Furthermore the regex syntax in these are not the same as PCRE2 that is used by MongoDB, so there is no guarantee that escape will always work.
Proposed solution:
// Either a free-standing function:
pub fn regex_escape(s: &str) -> CString;
// or a function on `bson::Regex`:
impl Regex {
pub fn escape(s: &str) -> CString;
}
To actually achieve the prefix match easily it should also be possible to concatenate two CString:
fn prefix_regex(s: &str) -> bson::Regex {
let mut pattern = CString::from(cstr!("^"));
pattern += regex_escape(s);
bson::Regex {
pattern,
options: CString::new(),
}
}
We do a lot of queries for fields having a specific prefix. The only way(?) to do this in MongoDB is using a regex. To do this for an arbitrary input string it needs to be escaped.
Possible alternative is to use
regex-syntax/regex-lite'sescapefunction. These don't escape theNULbyte which is needed forbson::Regex'sCStringpattern. Furthermore the regex syntax in these are not the same as PCRE2 that is used by MongoDB, so there is no guarantee that escape will always work.Proposed solution:
To actually achieve the prefix match easily it should also be possible to concatenate two
CString: