diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f5cd9887..25e7ecab9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,8 @@ Anchored search APIs are now available in `regex-automata 0.3`. Add new `Captures::extract` method for easier capture group access. * [FEATURE #961](https://github.com/rust-lang/regex/issues/961): Add `regex-lite` crate with smaller binary sizes and faster compile times. +* [FEATURE #1022](https://github.com/rust-lang/regex/pull/1022): +Add `TryFrom` implementations for the `Regex` type. Performance improvements: diff --git a/regex-lite/src/string.rs b/regex-lite/src/string.rs index 358f7a0c7..acf6aa00a 100644 --- a/regex-lite/src/string.rs +++ b/regex-lite/src/string.rs @@ -117,6 +117,24 @@ impl core::str::FromStr for Regex { } } +impl TryFrom<&str> for Regex { + type Error = Error; + + /// Attempts to parse a string into a regular expression + fn try_from(s: &str) -> Result { + Regex::new(s) + } +} + +impl TryFrom for Regex { + type Error = Error; + + /// Attempts to parse a string into a regular expression + fn try_from(s: String) -> Result { + Regex::new(&s) + } +} + /// Core regular expression methods. impl Regex { /// Compiles a regular expression. Once compiled, it can be used repeatedly diff --git a/src/regex/bytes.rs b/src/regex/bytes.rs index fc4238bcd..86437e1c2 100644 --- a/src/regex/bytes.rs +++ b/src/regex/bytes.rs @@ -1,4 +1,4 @@ -use alloc::{borrow::Cow, sync::Arc, vec::Vec}; +use alloc::{borrow::Cow, string::String, sync::Arc, vec::Vec}; use regex_automata::{meta, util::captures, Input, PatternID}; @@ -124,6 +124,24 @@ impl core::str::FromStr for Regex { } } +impl TryFrom<&str> for Regex { + type Error = Error; + + /// Attempts to parse a string into a regular expression + fn try_from(s: &str) -> Result { + Regex::new(s) + } +} + +impl TryFrom for Regex { + type Error = Error; + + /// Attempts to parse a string into a regular expression + fn try_from(s: String) -> Result { + Regex::new(&s) + } +} + /// Core regular expression methods. impl Regex { /// Compiles a regular expression. Once compiled, it can be used repeatedly diff --git a/src/regex/string.rs b/src/regex/string.rs index 438af7beb..e8d625655 100644 --- a/src/regex/string.rs +++ b/src/regex/string.rs @@ -126,6 +126,24 @@ impl core::str::FromStr for Regex { } } +impl TryFrom<&str> for Regex { + type Error = Error; + + /// Attempts to parse a string into a regular expression + fn try_from(s: &str) -> Result { + Regex::new(s) + } +} + +impl TryFrom for Regex { + type Error = Error; + + /// Attempts to parse a string into a regular expression + fn try_from(s: String) -> Result { + Regex::new(&s) + } +} + /// Core regular expression methods. impl Regex { /// Compiles a regular expression. Once compiled, it can be used repeatedly