maxmind-db-rust 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,10 @@
1
- use magnus::{error::Error, prelude::*, RArray, RString, Value};
1
+ use crate::convert::{try_convert_array, try_convert_optional};
2
+ use magnus::{
3
+ error::{Error, ErrorType},
4
+ prelude::*,
5
+ rb_sys::AsRawValue,
6
+ Float, Integer, RArray, RComplex, RString, Symbol, Value,
7
+ };
2
8
  use maxminddb::PathElement;
3
9
  use rustc_hash::FxHasher;
4
10
  use std::{
@@ -21,7 +27,7 @@ pub(crate) struct CachedPath {
21
27
  }
22
28
 
23
29
  pub(crate) fn path_array(path: Value, ruby: &magnus::Ruby) -> Result<RArray, Error> {
24
- RArray::try_convert(path).map_err(|_| {
30
+ try_convert_array(path, ruby)?.ok_or_else(|| {
25
31
  Error::new(
26
32
  ruby.exception_arg_error(),
27
33
  "Path must be an Array of String and Integer elements",
@@ -29,56 +35,27 @@ pub(crate) fn path_array(path: Value, ruby: &magnus::Ruby) -> Result<RArray, Err
29
35
  })
30
36
  }
31
37
 
32
- pub(crate) fn parse_path_array(
38
+ /// `before_convert` runs before handling an element that is not a UTF-8 String,
39
+ /// because converting it can call Ruby or fail.
40
+ pub(crate) fn path_cache_hash(
33
41
  path: RArray,
34
42
  ruby: &magnus::Ruby,
35
- ) -> Result<Vec<OwnedPathElement>, Error> {
36
- let mut elements = Vec::with_capacity(path.len());
37
- for index in 0..path.len() {
38
- let item = path.entry::<Value>(index as isize)?;
39
- if let Ok(key) = RString::try_convert(item) {
40
- elements.push(OwnedPathElement::Key(key.to_string()?));
41
- continue;
42
- }
43
- if let Ok(index) = isize::try_convert(item) {
44
- elements.push(signed_index_to_owned_path_element(index));
45
- continue;
46
- }
47
- return Err(Error::new(
48
- ruby.exception_arg_error(),
49
- "Path elements must be Strings or Integers",
50
- ));
51
- }
52
-
53
- Ok(elements)
54
- }
55
-
56
- #[inline]
57
- fn signed_index_to_owned_path_element(index: isize) -> OwnedPathElement {
58
- if index >= 0 {
59
- OwnedPathElement::Index(index as usize)
60
- } else {
61
- let index_from_end = index
62
- .checked_neg()
63
- .and_then(|index| index.checked_sub(1))
64
- .map(|index| index as usize)
65
- .unwrap_or(usize::MAX);
66
- OwnedPathElement::IndexFromEnd(index_from_end)
67
- }
68
- }
69
-
70
- pub(crate) fn path_cache_hash(path: RArray, ruby: &magnus::Ruby) -> Result<u64, Error> {
43
+ before_convert: impl Fn() -> Result<(), Error>,
44
+ ) -> Result<u64, Error> {
71
45
  let mut hasher = FxHasher::default();
72
46
  path.len().hash(&mut hasher);
73
47
 
74
48
  for index in 0..path.len() {
75
49
  let item = path.entry::<Value>(index as isize)?;
76
- if let Ok(key) = RString::try_convert(item) {
50
+ if RString::from_value(item).is_none() {
51
+ before_convert()?;
52
+ }
53
+ if let Some(key) = try_convert_optional::<RString>(item, ruby)? {
77
54
  0_u8.hash(&mut hasher);
78
- hash_path_key(key, &mut hasher)?;
55
+ hash_path_key(key, &mut hasher, &before_convert)?;
79
56
  continue;
80
57
  }
81
- if let Ok(index) = isize::try_convert(item) {
58
+ if let Some(index) = path_index(item, ruby)? {
82
59
  1_u8.hash(&mut hasher);
83
60
  index.hash(&mut hasher);
84
61
  continue;
@@ -92,20 +69,10 @@ pub(crate) fn path_cache_hash(path: RArray, ruby: &magnus::Ruby) -> Result<u64,
92
69
  Ok(hasher.finish())
93
70
  }
94
71
 
95
- fn hash_path_key(key: RString, hasher: &mut FxHasher) -> Result<(), Error> {
96
- // SAFETY: the borrowed str is used only for immediate hashing and is not
97
- // stored across any call that could mutate or free the Ruby string.
98
- if let Some(key_str) = unsafe { key.test_as_str() } {
99
- key_str.hash(hasher);
100
- } else {
101
- key.to_string()?.hash(hasher);
102
- }
103
- Ok(())
104
- }
105
-
106
72
  pub(crate) fn path_matches_cached(
107
73
  path: RArray,
108
74
  cached: &[OwnedPathElement],
75
+ ruby: &magnus::Ruby,
109
76
  ) -> Result<bool, Error> {
110
77
  if path.len() != cached.len() {
111
78
  return Ok(false);
@@ -115,7 +82,7 @@ pub(crate) fn path_matches_cached(
115
82
  let item = path.entry::<Value>(index as isize)?;
116
83
  match cached_element {
117
84
  OwnedPathElement::Key(expected) => {
118
- let Ok(key) = RString::try_convert(item) else {
85
+ let Some(key) = try_convert_optional::<RString>(item, ruby)? else {
119
86
  return Ok(false);
120
87
  };
121
88
  if !path_key_matches(key, expected)? {
@@ -123,7 +90,7 @@ pub(crate) fn path_matches_cached(
123
90
  }
124
91
  }
125
92
  OwnedPathElement::Index(_) | OwnedPathElement::IndexFromEnd(_) => {
126
- let Ok(index) = isize::try_convert(item) else {
93
+ let Some(index) = path_index(item, ruby)? else {
127
94
  return Ok(false);
128
95
  };
129
96
  if signed_index_to_owned_path_element(index) != *cached_element {
@@ -136,14 +103,28 @@ pub(crate) fn path_matches_cached(
136
103
  Ok(true)
137
104
  }
138
105
 
139
- fn path_key_matches(key: RString, expected: &str) -> Result<bool, Error> {
140
- // SAFETY: the borrowed str is used only for immediate comparison and is not
141
- // stored across any call that could mutate or free the Ruby string.
142
- if let Some(key_str) = unsafe { key.test_as_str() } {
143
- Ok(key_str == expected)
144
- } else {
145
- Ok(key.to_string()? == expected)
106
+ pub(crate) fn parse_path_array(
107
+ path: RArray,
108
+ ruby: &magnus::Ruby,
109
+ ) -> Result<Vec<OwnedPathElement>, Error> {
110
+ let mut elements = Vec::with_capacity(path.len());
111
+ for index in 0..path.len() {
112
+ let item = path.entry::<Value>(index as isize)?;
113
+ if let Some(key) = try_convert_optional::<RString>(item, ruby)? {
114
+ elements.push(OwnedPathElement::Key(key.to_string()?));
115
+ continue;
116
+ }
117
+ if let Some(index) = path_index(item, ruby)? {
118
+ elements.push(signed_index_to_owned_path_element(index));
119
+ continue;
120
+ }
121
+ return Err(Error::new(
122
+ ruby.exception_arg_error(),
123
+ "Path elements must be Strings or Integers",
124
+ ));
146
125
  }
126
+
127
+ Ok(elements)
147
128
  }
148
129
 
149
130
  pub(crate) fn path_elements_from_owned_path(path: &[OwnedPathElement]) -> Vec<PathElement<'_>> {
@@ -155,3 +136,96 @@ pub(crate) fn path_elements_from_owned_path(path: &[OwnedPathElement]) -> Vec<Pa
155
136
  })
156
137
  .collect()
157
138
  }
139
+
140
+ fn hash_path_key(
141
+ key: RString,
142
+ hasher: &mut FxHasher,
143
+ before_convert: impl Fn() -> Result<(), Error>,
144
+ ) -> Result<(), Error> {
145
+ // SAFETY: the borrowed str is used only for immediate hashing and is not
146
+ // stored across any call that could mutate or free the Ruby string.
147
+ if let Some(key_str) = unsafe { key.test_as_str() } {
148
+ key_str.hash(hasher);
149
+ } else {
150
+ before_convert()?;
151
+ key.to_string()?.hash(hasher);
152
+ }
153
+ Ok(())
154
+ }
155
+
156
+ /// Returns `None` if `item` is not an Integer or is too large for an index.
157
+ #[inline]
158
+ fn path_index(item: Value, ruby: &magnus::Ruby) -> Result<Option<isize>, Error> {
159
+ let index = match try_convert_optional::<Integer>(item, ruby) {
160
+ Ok(Some(index)) => index,
161
+ Ok(None) => return Ok(None),
162
+ // A number such as Infinity, NaN or Complex(1, 1) has no Integer value.
163
+ // Ruby's own `to_int` raises then, so this is not a caller's error.
164
+ Err(err) if err.is_kind_of(ruby.exception_range_error()) && is_ruby_number(item) => {
165
+ return Ok(None)
166
+ }
167
+ Err(err) if is_missing_to_i(&err, item, ruby)? => return Ok(None),
168
+ Err(err) => return Err(err),
169
+ };
170
+ match index.to_isize() {
171
+ Ok(index) => Ok(Some(index)),
172
+ Err(err) if err.is_kind_of(ruby.exception_range_error()) => Ok(None),
173
+ Err(err) => Err(err),
174
+ }
175
+ }
176
+
177
+ /// Whether `item` is a number other than an Integer whose `to_int` is Ruby's.
178
+ fn is_ruby_number(item: Value) -> bool {
179
+ Float::from_value(item).is_some()
180
+ || RComplex::from_value(item).is_some()
181
+ // SAFETY: the name is used before any Ruby code can run.
182
+ || unsafe { item.classname() } == "BigDecimal"
183
+ }
184
+
185
+ /// Whether `err` is from Numeric#to_int calling a `to_i` that `item`, an instance
186
+ /// of a subclass, does not have.
187
+ fn is_missing_to_i(err: &Error, item: Value, ruby: &magnus::Ruby) -> Result<bool, Error> {
188
+ let exception = match err.error_type() {
189
+ ErrorType::Exception(exception)
190
+ if exception.is_kind_of(ruby.exception_no_method_error())
191
+ && item.is_kind_of(ruby.class_numeric()) =>
192
+ {
193
+ *exception
194
+ }
195
+ _ => return Ok(false),
196
+ };
197
+ let name = Symbol::from_value(exception.funcall("name", ())?);
198
+ if name != Some(ruby.to_symbol("to_i")) {
199
+ return Ok(false);
200
+ }
201
+ match exception.funcall::<_, _, Value>("receiver", ()) {
202
+ Ok(receiver) => Ok(receiver.as_raw() == item.as_raw()),
203
+ // The exception was created without a receiver.
204
+ Err(err) if err.is_kind_of(ruby.exception_arg_error()) => Ok(false),
205
+ Err(err) => Err(err),
206
+ }
207
+ }
208
+
209
+ fn path_key_matches(key: RString, expected: &str) -> Result<bool, Error> {
210
+ // SAFETY: the borrowed str is used only for immediate comparison and is not
211
+ // stored across any call that could mutate or free the Ruby string.
212
+ if let Some(key_str) = unsafe { key.test_as_str() } {
213
+ Ok(key_str == expected)
214
+ } else {
215
+ Ok(key.to_string()? == expected)
216
+ }
217
+ }
218
+
219
+ #[inline]
220
+ fn signed_index_to_owned_path_element(index: isize) -> OwnedPathElement {
221
+ if index >= 0 {
222
+ OwnedPathElement::Index(index as usize)
223
+ } else {
224
+ let index_from_end = index
225
+ .checked_neg()
226
+ .and_then(|index| index.checked_sub(1))
227
+ .map(|index| index as usize)
228
+ .unwrap_or(usize::MAX);
229
+ OwnedPathElement::IndexFromEnd(index_from_end)
230
+ }
231
+ }