1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
use std::{fmt, os::raw::c_int};
use rb_sys::{
rb_reg_backref_number, rb_reg_last_match, rb_reg_match_last, rb_reg_match_post,
rb_reg_match_pre, rb_reg_nth_defined, rb_reg_nth_match, ruby_value_type, VALUE,
};
use crate::{
error::{protect, Error},
into_value::IntoValue,
object::Object,
r_string::{IntoRString, RString},
try_convert::TryConvert,
value::{
private::{self, ReprValue as _},
NonZeroValue, ReprValue, Value,
},
Ruby,
};
/// A Value pointer to a RMatch struct, Ruby's internal representation of the
/// MatchData returned from a regex match.
///
/// See the [`ReprValue`] and [`Object`] traits for additional methods
/// available on this type.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct RMatch(NonZeroValue);
impl RMatch {
/// Return `Some(RMatch)` if `val` is a `RMatch`, `None` otherwise.
///
/// # Examples
///
/// ```
/// use magnus::{eval, RMatch};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert!(RMatch::from_value(eval(r#""foo".match(/o/)"#).unwrap()).is_some());
/// assert!(RMatch::from_value(eval(r#""o""#).unwrap()).is_none());
/// ```
#[inline]
pub fn from_value(val: Value) -> Option<Self> {
unsafe {
(val.rb_type() == ruby_value_type::RUBY_T_MATCH)
.then(|| Self(NonZeroValue::new_unchecked(val)))
}
}
#[inline]
pub(crate) unsafe fn from_rb_value_unchecked(val: VALUE) -> Self {
Self(NonZeroValue::new_unchecked(Value::new(val)))
}
/// Returns whether the `n`th capture group is set.
///
/// Returns `Some(true)` when there is an `n`th capture and it has a value.
/// Returns `Some(false)` when there is an `n`th capture but it is empty.
/// Returns `None` when there is no `n`th capture.
///
/// This function is similar to [`nth_match`](Self::nth_match), but can be
/// used to avoid allocating a Ruby string if the value of the capture is
/// not needed.
///
/// # Examples
///
/// ```
/// use magnus::{backref_get, RRegexp};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let regexp = RRegexp::new(".([a-z])([a-z]*)([0-9])?", Default::default()).unwrap();
/// regexp.reg_match("ex").unwrap();
/// let match_data = backref_get().unwrap();
/// // 0th group is the whole match
/// assert_eq!(match_data.nth_defined(0), Some(true));
/// // the `([a-z])` group
/// assert_eq!(match_data.nth_defined(1), Some(true));
/// // the `([a-z]*)` group
/// assert_eq!(match_data.nth_defined(2), Some(true));
/// // the `([0-9])?` group
/// assert_eq!(match_data.nth_defined(3), Some(false));
/// // no 4th group
/// assert_eq!(match_data.nth_defined(4), None);
/// ```
pub fn nth_defined(self, n: isize) -> Option<bool> {
let value = unsafe { Value::new(rb_reg_nth_defined(n as c_int, self.as_rb_value())) };
Option::<bool>::try_convert(value).unwrap() // infallible
}
/// Returns the string captured by the `n`th capture group.
///
/// Returns `None` when there is no `n`th capture.
///
/// # Examples
///
/// ```
/// use magnus::{backref_get, RRegexp};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let regexp = RRegexp::new(".([a-z])([a-z]*)([0-9])?", Default::default()).unwrap();
/// regexp.reg_match("ex").unwrap();
/// let match_data = backref_get().unwrap();
/// // 0th group is the whole match
/// assert_eq!(
/// match_data.nth_match(0).map(|s| s.to_string().unwrap()),
/// Some(String::from("ex"))
/// );
/// // the `([a-z])` group
/// assert_eq!(
/// match_data.nth_match(1).map(|s| s.to_string().unwrap()),
/// Some(String::from("x"))
/// );
/// // the `([a-z]*)` group
/// assert_eq!(
/// match_data.nth_match(2).map(|s| s.to_string().unwrap()),
/// Some(String::from(""))
/// );
/// // the `([0-9])?` group
/// assert_eq!(
/// match_data.nth_match(3).map(|s| s.to_string().unwrap()),
/// None
/// );
/// // no 4th group
/// assert_eq!(
/// match_data.nth_match(4).map(|s| s.to_string().unwrap()),
/// None
/// );
/// ```
pub fn nth_match(self, n: isize) -> Option<RString> {
let value = unsafe { Value::new(rb_reg_nth_match(n as c_int, self.as_rb_value())) };
(!value.is_nil()).then(|| unsafe { RString::from_rb_value_unchecked(value.as_rb_value()) })
}
/// Returns the index for the named capture group.
///
/// Returns `Err` if there's is no named capture group with the given name.
///
/// # Examples
///
/// ```
/// use magnus::{backref_get, RRegexp};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let regexp = RRegexp::new("Hello, (?<subject>.*)!", Default::default()).unwrap();
/// regexp.reg_match("Hello, World!").unwrap();
/// let match_data = backref_get().unwrap();
/// assert_eq!(match_data.backref_number("subject").unwrap(), 1);
/// assert!(match_data.backref_number("foo").is_err());
/// ```
pub fn backref_number<T>(self, name: T) -> Result<usize, Error>
where
T: IntoRString,
{
let handle = Ruby::get_with(self);
let name = name.into_r_string_with(&handle);
let mut n = 0;
protect(|| unsafe {
n = rb_reg_backref_number(self.as_rb_value(), name.as_rb_value()) as usize;
handle.qnil()
})?;
Ok(n)
}
/// Returns the string matched.
///
/// # Examples
///
/// ```
/// use magnus::{backref_get, RRegexp};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let regexp = RRegexp::new("b(.)r", Default::default()).unwrap();
/// regexp.reg_match("foo bar baz").unwrap();
///
/// let match_data = backref_get().unwrap();
/// assert_eq!(match_data.matched().to_string().unwrap(), "bar");
/// ```
pub fn matched(self) -> RString {
unsafe { RString::from_rb_value_unchecked(rb_reg_last_match(self.as_rb_value())) }
}
/// Returns the string before the segment matched.
///
/// # Examples
///
/// ```
/// use magnus::{backref_get, RRegexp};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let regexp = RRegexp::new("b(.)r", Default::default()).unwrap();
/// regexp.reg_match("foo bar baz").unwrap();
///
/// let match_data = backref_get().unwrap();
/// assert_eq!(match_data.pre().to_string().unwrap(), "foo ");
/// ```
pub fn pre(self) -> RString {
unsafe { RString::from_rb_value_unchecked(rb_reg_match_pre(self.as_rb_value())) }
}
/// Returns the string after the segment matched.
///
/// # Examples
///
/// ```
/// use magnus::{backref_get, RRegexp};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let regexp = RRegexp::new("b(.)r", Default::default()).unwrap();
/// regexp.reg_match("foo bar baz").unwrap();
///
/// let match_data = backref_get().unwrap();
/// assert_eq!(match_data.post().to_string().unwrap(), " baz");
/// ```
pub fn post(self) -> RString {
unsafe { RString::from_rb_value_unchecked(rb_reg_match_post(self.as_rb_value())) }
}
/// Returns the last capture.
///
/// Returns `None` if there are no capture groups.
///
/// # Examples
///
/// ```
/// use magnus::{backref_get, RRegexp};
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// let regexp = RRegexp::new("(.)oo b(.)r ba(.)", Default::default()).unwrap();
/// regexp.reg_match("foo bar baz").unwrap();
///
/// let match_data = backref_get().unwrap();
/// assert_eq!(match_data.last().unwrap().to_string().unwrap(), "z");
/// ```
pub fn last(self) -> Option<RString> {
let value = unsafe { Value::new(rb_reg_match_last(self.as_rb_value())) };
(!value.is_nil()).then(|| unsafe { RString::from_rb_value_unchecked(value.as_rb_value()) })
}
}
impl fmt::Display for RMatch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", unsafe { self.to_s_infallible() })
}
}
impl fmt::Debug for RMatch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.inspect())
}
}
impl IntoValue for RMatch {
#[inline]
fn into_value_with(self, _: &Ruby) -> Value {
self.0.get()
}
}
impl Object for RMatch {}
unsafe impl private::ReprValue for RMatch {}
impl ReprValue for RMatch {}
impl TryConvert for RMatch {
fn try_convert(val: Value) -> Result<Self, Error> {
Self::from_value(val).ok_or_else(|| {
Error::new(
Ruby::get_with(val).exception_type_error(),
format!("no implicit conversion of {} into MatchData", unsafe {
val.classname()
},),
)
})
}
}