python2rust 0.1.0__py3-none-any.whl

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.
Files changed (102) hide show
  1. python2rust/__init__.py +8 -0
  2. python2rust/__main__.py +5 -0
  3. python2rust/_core.py +44 -0
  4. python2rust/agent/__init__.py +0 -0
  5. python2rust/agent/agents.py +333 -0
  6. python2rust/agent/apply.py +516 -0
  7. python2rust/agent/finish.py +295 -0
  8. python2rust/agent/fixers.py +229 -0
  9. python2rust/agent/loop.py +441 -0
  10. python2rust/agent/patches.py +1165 -0
  11. python2rust/agent/port.py +579 -0
  12. python2rust/agent/prompts/judge_v2.md +96 -0
  13. python2rust/agent/review.py +34 -0
  14. python2rust/agent/rustlex.py +232 -0
  15. python2rust/cli/__init__.py +0 -0
  16. python2rust/cli/doctor.py +62 -0
  17. python2rust/cli/inputs.py +105 -0
  18. python2rust/cli/main.py +1162 -0
  19. python2rust/cli/ops.py +642 -0
  20. python2rust/cli/workflow.py +178 -0
  21. python2rust/core/__init__.py +38 -0
  22. python2rust/core/config.py +263 -0
  23. python2rust/core/constructs.py +124 -0
  24. python2rust/core/diagnostics.py +280 -0
  25. python2rust/core/emit/__init__.py +5 -0
  26. python2rust/core/emit/crates.py +51 -0
  27. python2rust/core/emit/render.py +561 -0
  28. python2rust/core/emit/schema.py +168 -0
  29. python2rust/core/emit/translate.py +304 -0
  30. python2rust/core/frontend/__init__.py +1 -0
  31. python2rust/core/frontend/module.py +896 -0
  32. python2rust/core/frontend/names.py +129 -0
  33. python2rust/core/frontend/project.py +277 -0
  34. python2rust/core/frontend/project_imports.py +173 -0
  35. python2rust/core/frontend/symbols.py +132 -0
  36. python2rust/core/frontend/walrus.py +59 -0
  37. python2rust/core/ir/__init__.py +1 -0
  38. python2rust/core/ir/nodes.py +675 -0
  39. python2rust/core/ir/rtypes.py +122 -0
  40. python2rust/core/ir/types.py +326 -0
  41. python2rust/core/lower/__init__.py +1 -0
  42. python2rust/core/lower/calls.py +1125 -0
  43. python2rust/core/lower/context.py +223 -0
  44. python2rust/core/lower/exceptions.py +317 -0
  45. python2rust/core/lower/exprs.py +845 -0
  46. python2rust/core/lower/fstrings.py +141 -0
  47. python2rust/core/lower/funcs.py +276 -0
  48. python2rust/core/lower/lowerer.py +366 -0
  49. python2rust/core/lower/modelcalls.py +195 -0
  50. python2rust/core/lower/models.py +645 -0
  51. python2rust/core/lower/stmts.py +722 -0
  52. python2rust/core/lower/testing.py +601 -0
  53. python2rust/core/lower/validation.py +253 -0
  54. python2rust/core/passes/__init__.py +1 -0
  55. python2rust/core/passes/aliasing.py +311 -0
  56. python2rust/core/passes/analysis.py +207 -0
  57. python2rust/core/passes/devirt.py +329 -0
  58. python2rust/core/passes/ownership.py +259 -0
  59. python2rust/core/passes/raises.py +275 -0
  60. python2rust/core/rt_lib.rs +2071 -0
  61. python2rust/data/README.md +81 -0
  62. python2rust/data/py2many_builtins.toml +4744 -0
  63. python2rust/errors.py +28 -0
  64. python2rust/py.typed +0 -0
  65. python2rust/report/__init__.py +0 -0
  66. python2rust/report/constructs.py +31 -0
  67. python2rust/report/contract.py +688 -0
  68. python2rust/report/corpus.py +323 -0
  69. python2rust/report/explain.py +168 -0
  70. python2rust/report/schemas.py +914 -0
  71. python2rust/server/__init__.py +0 -0
  72. python2rust/server/mcp_server.py +289 -0
  73. python2rust/server/mcp_workflow.py +100 -0
  74. python2rust/skill/SKILL.md +214 -0
  75. python2rust/verify/__init__.py +0 -0
  76. python2rust/verify/check.py +1135 -0
  77. python2rust/verify/equiv/__init__.py +1264 -0
  78. python2rust/verify/equiv/compare.py +455 -0
  79. python2rust/verify/equiv/harness.py +505 -0
  80. python2rust/verify/equiv/judge.py +358 -0
  81. python2rust/verify/equiv/procs.py +255 -0
  82. python2rust/verify/equiv/runner.py +248 -0
  83. python2rust/verify/equiv/types.py +543 -0
  84. python2rust/verify/keystore.py +76 -0
  85. python2rust/verify/ladder.py +396 -0
  86. python2rust/verify/sandbox.py +370 -0
  87. python2rust/verify/testrun.py +280 -0
  88. python2rust/workflow/__init__.py +0 -0
  89. python2rust/workflow/brief.py +312 -0
  90. python2rust/workflow/interview.py +366 -0
  91. python2rust/workflow/layout.py +103 -0
  92. python2rust/workflow/planner.py +409 -0
  93. python2rust/workflow/project.py +134 -0
  94. python2rust/workflow/schemas.py +265 -0
  95. python2rust/workflow/state.py +392 -0
  96. python2rust/workflow/staticscan.py +209 -0
  97. python2rust-0.1.0.dist-info/METADATA +395 -0
  98. python2rust-0.1.0.dist-info/RECORD +102 -0
  99. python2rust-0.1.0.dist-info/WHEEL +4 -0
  100. python2rust-0.1.0.dist-info/entry_points.txt +4 -0
  101. python2rust-0.1.0.dist-info/licenses/LICENSE +21 -0
  102. python2rust-0.1.0.dist-info/licenses/NOTICE +65 -0
@@ -0,0 +1,2071 @@
1
+ //! Runtime helpers for python2rust output: Python semantics (floor division, negative indices,
2
+ //! Unicode slicing, repr quoting, float formatting) that std Rust spells differently.
3
+ #![allow(dead_code)]
4
+
5
+ use std::cmp::Ordering;
6
+
7
+ const OVERFLOW: &str = "OverflowError: integer result does not fit in i64";
8
+
9
+ /// Checked integer arithmetic: Python ints are unbounded, so overflow is reported, never wrapped.
10
+ /// These are `const fn`, so constants such as `24 * 60 * 60` are checked at compile time.
11
+ pub const fn add(a: i64, b: i64) -> i64 {
12
+ match a.checked_add(b) {
13
+ Some(v) => v,
14
+ None => panic!("OverflowError: integer result does not fit in i64"),
15
+ }
16
+ }
17
+
18
+ pub const fn sub(a: i64, b: i64) -> i64 {
19
+ match a.checked_sub(b) {
20
+ Some(v) => v,
21
+ None => panic!("OverflowError: integer result does not fit in i64"),
22
+ }
23
+ }
24
+
25
+ pub const fn mul(a: i64, b: i64) -> i64 {
26
+ match a.checked_mul(b) {
27
+ Some(v) => v,
28
+ None => panic!("OverflowError: integer result does not fit in i64"),
29
+ }
30
+ }
31
+
32
+ pub const fn neg(a: i64) -> i64 {
33
+ match a.checked_neg() {
34
+ Some(v) => v,
35
+ None => panic!("OverflowError: integer result does not fit in i64"),
36
+ }
37
+ }
38
+
39
+ pub const fn abs(a: i64) -> i64 {
40
+ match a.checked_abs() {
41
+ Some(v) => v,
42
+ None => panic!("OverflowError: integer result does not fit in i64"),
43
+ }
44
+ }
45
+
46
+ /// `a ** b` for a non-negative exponent.
47
+ pub const fn pow(a: i64, b: i64) -> i64 {
48
+ if b < 0 || b > u32::MAX as i64 {
49
+ panic!("OverflowError: exponent out of range");
50
+ }
51
+ match a.checked_pow(b as u32) {
52
+ Some(v) => v,
53
+ None => panic!("OverflowError: integer result does not fit in i64"),
54
+ }
55
+ }
56
+
57
+ pub fn sum<I: IntoIterator<Item = i64>>(it: I) -> i64 {
58
+ it.into_iter().fold(0, add)
59
+ }
60
+
61
+ pub fn floordiv(a: i64, b: i64) -> i64 {
62
+ if b == 0 {
63
+ panic!("ZeroDivisionError: division by zero");
64
+ }
65
+ let (q, r) = (a.checked_div(b).expect(OVERFLOW), a % b);
66
+ if r != 0 && ((r < 0) != (b < 0)) { q - 1 } else { q }
67
+ }
68
+
69
+ pub fn floormod(a: i64, b: i64) -> i64 {
70
+ if b == 0 {
71
+ panic!("ZeroDivisionError: division by zero");
72
+ }
73
+ let r = a.checked_rem(b).unwrap_or(0);
74
+ if r != 0 && ((r < 0) != (b < 0)) { r + b } else { r }
75
+ }
76
+
77
+ /// CPython's float_divmod (fmod-based, sign follows the divisor, signed zeros preserved).
78
+ fn float_divmod(a: f64, b: f64) -> (f64, f64) {
79
+ if b == 0.0 {
80
+ panic!("ZeroDivisionError: division by zero");
81
+ }
82
+ let mut m = a % b;
83
+ let mut div = (a - m) / b;
84
+ if m != 0.0 {
85
+ if (b < 0.0) != (m < 0.0) {
86
+ m += b;
87
+ div -= 1.0;
88
+ }
89
+ } else {
90
+ m = 0.0_f64.copysign(b);
91
+ }
92
+ let floor = if div != 0.0 {
93
+ let f = div.floor();
94
+ if div - f > 0.5 { f + 1.0 } else { f }
95
+ } else {
96
+ 0.0_f64.copysign(a / b)
97
+ };
98
+ (floor, m)
99
+ }
100
+
101
+ pub fn floordiv_f(a: f64, b: f64) -> f64 {
102
+ float_divmod(a, b).0
103
+ }
104
+
105
+ pub fn floormod_f(a: f64, b: f64) -> f64 {
106
+ float_divmod(a, b).1
107
+ }
108
+
109
+ /// `a / b` on floats: Python raises for a zero divisor instead of returning inf or nan.
110
+ pub fn div(a: f64, b: f64) -> f64 {
111
+ if b == 0.0 {
112
+ panic!("ZeroDivisionError: division by zero");
113
+ }
114
+ a / b
115
+ }
116
+
117
+ /// `int(x)` for a float: truncates toward zero; NaN, infinities and values outside i64 panic
118
+ /// (Python returns a bigint or raises), instead of saturating like an `as` cast.
119
+ pub fn float_to_int(x: f64) -> i64 {
120
+ if !x.is_finite() || x >= 9_223_372_036_854_775_808.0 || x < -9_223_372_036_854_775_808.0 {
121
+ panic!("OverflowError: cannot convert float to an i64 integer");
122
+ }
123
+ x as i64
124
+ }
125
+
126
+ /// Python round(): banker's rounding to an int.
127
+ pub fn round(x: f64) -> i64 {
128
+ float_to_int(x.round_ties_even())
129
+ }
130
+
131
+ /// Python sum() over floats: CPython 3.12+ uses Neumaier compensated summation.
132
+ pub fn sum_f64<I: IntoIterator<Item = f64>>(it: I, start: f64) -> f64 {
133
+ let (mut total, mut comp) = (start, 0.0_f64);
134
+ for x in it {
135
+ let t = total + x;
136
+ if total.abs() >= x.abs() {
137
+ comp += (total - t) + x;
138
+ } else {
139
+ comp += (x - t) + total;
140
+ }
141
+ total = t;
142
+ }
143
+ if comp != 0.0 && comp.is_finite() { total + comp } else { total }
144
+ }
145
+
146
+ /// `range(start, stop, step)` for a step only known at run time.
147
+ pub fn range(start: i64, stop: i64, step: i64) -> impl Iterator<Item = i64> {
148
+ if step == 0 {
149
+ panic!("ValueError: range() arg 3 must not be zero");
150
+ }
151
+ std::iter::successors(Some(start), move |&x| x.checked_add(step))
152
+ .take_while(move |&x| if step > 0 { x < stop } else { x > stop })
153
+ }
154
+
155
+ /// Resolve a possibly negative Python index; panics like IndexError when out of range.
156
+ pub fn idx(i: i64, len: usize) -> usize {
157
+ idx_in(i, len, "list")
158
+ }
159
+
160
+ /// `idx` for another sequence type: CPython says "<what> index out of range".
161
+ pub fn idx_in(i: i64, len: usize, what: &str) -> usize {
162
+ let j = if i < 0 { i + len as i64 } else { i };
163
+ if j < 0 || j >= len as i64 {
164
+ panic!("IndexError: {what} index out of range");
165
+ }
166
+ j as usize
167
+ }
168
+
169
+ fn bound(i: Option<i64>, len: i64, default: i64) -> i64 {
170
+ match i {
171
+ None => default,
172
+ Some(i) => (if i < 0 { i + len } else { i }).clamp(0, len),
173
+ }
174
+ }
175
+
176
+ pub fn list_slice<T: Clone>(xs: &[T], start: Option<i64>, stop: Option<i64>) -> Vec<T> {
177
+ let n = xs.len() as i64;
178
+ let (a, b) = (bound(start, n, 0), bound(stop, n, n));
179
+ if a >= b { Vec::new() } else { xs[a as usize..b as usize].to_vec() }
180
+ }
181
+
182
+ /// Slice by characters (not bytes), clamping like Python.
183
+ pub fn str_slice(s: &str, start: Option<i64>, stop: Option<i64>) -> String {
184
+ let chars: Vec<char> = s.chars().collect();
185
+ list_slice(&chars, start, stop).into_iter().collect()
186
+ }
187
+
188
+ pub fn str_index(s: &str, i: i64) -> String {
189
+ let chars: Vec<char> = s.chars().collect();
190
+ chars[idx_in(i, chars.len(), "string")].to_string()
191
+ }
192
+
193
+ /// Index (in characters) of the first occurrence of `sub`, or -1.
194
+ pub fn str_find(s: &str, sub: &str) -> i64 {
195
+ s.find(sub).map_or(-1, |b| s[..b].chars().count() as i64)
196
+ }
197
+
198
+ /// Python repr() of a str: single quotes unless the text contains ' and no ".
199
+ pub fn repr_str(s: &str) -> String {
200
+ let quote = if s.contains('\'') && !s.contains('"') { '"' } else { '\'' };
201
+ let mut out = String::from(quote);
202
+ for c in s.chars() {
203
+ match c {
204
+ '\\' => out.push_str("\\\\"),
205
+ '\n' => out.push_str("\\n"),
206
+ '\r' => out.push_str("\\r"),
207
+ '\t' => out.push_str("\\t"),
208
+ c if c == quote => {
209
+ out.push('\\');
210
+ out.push(c);
211
+ }
212
+ c if (c as u32) < 32 || c as u32 == 127 => out.push_str(&format!("\\x{:02x}", c as u32)),
213
+ c => out.push(c),
214
+ }
215
+ }
216
+ out.push(quote);
217
+ out
218
+ }
219
+
220
+ /// A float in a `{:.N}` field: non-finite values print as Python does (`nan`, `inf`, `-inf`).
221
+ pub struct Fixed(pub f64);
222
+
223
+ impl std::fmt::Display for Fixed {
224
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
225
+ let x = self.0;
226
+ if x.is_finite() {
227
+ return std::fmt::Display::fmt(&x, f);
228
+ }
229
+ let sign = if x < 0.0 { "-" } else if f.sign_plus() { "+" } else { "" };
230
+ let text = format!("{sign}{}", if x.is_nan() { "nan" } else { "inf" });
231
+ let pad = f.width().unwrap_or(0).saturating_sub(text.len());
232
+ let fill = f.fill().to_string();
233
+ let (left, right) = match f.align() {
234
+ Some(std::fmt::Alignment::Left) => (0, pad),
235
+ Some(std::fmt::Alignment::Center) => (pad / 2, pad - pad / 2),
236
+ _ => (pad, 0),
237
+ };
238
+ write!(f, "{}{text}{}", fill.repeat(left), fill.repeat(right))
239
+ }
240
+ }
241
+
242
+ /// Python str(float): "1.0", "1e+16", "1.5e-05", "inf", "nan".
243
+ pub fn fmt_float(x: f64) -> String {
244
+ if x.is_nan() {
245
+ return "nan".into();
246
+ }
247
+ if x.is_infinite() {
248
+ return if x > 0.0 { "inf" } else { "-inf" }.into();
249
+ }
250
+ // Shortest round-trip digits; on a tie CPython takes the correctly rounded (half-even) ones,
251
+ // which is what exact formatting to the same number of digits gives.
252
+ let shortest = format!("{x:e}");
253
+ let count = shortest.split('e').next().unwrap_or("").chars().filter(char::is_ascii_digit).count();
254
+ let exact = format!("{x:.*e}", count.saturating_sub(1));
255
+ let best = if exact.parse::<f64>() == Ok(x) { exact } else { shortest };
256
+ let (mantissa, exp) = best.split_once('e').unwrap_or((&best, "0"));
257
+ let exp: i32 = exp.parse().unwrap_or(0);
258
+ let negative = mantissa.starts_with('-');
259
+ let mut digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
260
+ while digits.len() > 1 && digits.ends_with('0') {
261
+ digits.pop();
262
+ }
263
+ let sign = if negative { "-" } else { "" };
264
+ if x != 0.0 && !(-4..16).contains(&exp) {
265
+ let tail = &digits[1..];
266
+ let dot = if tail.is_empty() { "" } else { "." };
267
+ let esign = if exp < 0 { '-' } else { '+' };
268
+ return format!("{sign}{}{dot}{tail}e{esign}{:02}", &digits[..1], exp.abs());
269
+ }
270
+ let body = if exp < 0 {
271
+ format!("0.{}{digits}", "0".repeat((-exp - 1) as usize))
272
+ } else {
273
+ let int_len = exp as usize + 1;
274
+ if digits.len() <= int_len {
275
+ format!("{digits}{}.0", "0".repeat(int_len - digits.len()))
276
+ } else {
277
+ format!("{}.{}", &digits[..int_len], &digits[int_len..])
278
+ }
279
+ };
280
+ format!("{sign}{body}")
281
+ }
282
+
283
+ pub fn fmt_bool(b: bool) -> String {
284
+ if b { "True" } else { "False" }.to_string()
285
+ }
286
+
287
+ /// Python truthiness of a JSON value.
288
+ pub fn truthy(v: &serde_json::Value) -> bool {
289
+ use serde_json::Value;
290
+ match v {
291
+ Value::Null => false,
292
+ Value::Bool(b) => *b,
293
+ Value::Number(n) => n.as_f64().is_some_and(|f| f != 0.0),
294
+ Value::String(s) => !s.is_empty(),
295
+ Value::Array(a) => !a.is_empty(),
296
+ Value::Object(o) => !o.is_empty(),
297
+ }
298
+ }
299
+
300
+ fn cmp<T: PartialOrd>(a: &T, b: &T) -> Ordering {
301
+ a.partial_cmp(b).unwrap_or(Ordering::Equal)
302
+ }
303
+
304
+ pub fn sort<T: PartialOrd>(xs: &mut [T], reverse: bool) {
305
+ if reverse { xs.sort_by(|a, b| cmp(b, a)) } else { xs.sort_by(cmp) }
306
+ }
307
+
308
+ pub fn sorted<T: PartialOrd, I: IntoIterator<Item = T>>(it: I, reverse: bool) -> Vec<T> {
309
+ let mut v: Vec<T> = it.into_iter().collect();
310
+ sort(&mut v, reverse);
311
+ v
312
+ }
313
+
314
+ pub fn sorted_by_key<T: Clone, K: PartialOrd, I: IntoIterator<Item = T>>(
315
+ it: I,
316
+ mut key: impl FnMut(T) -> K,
317
+ reverse: bool,
318
+ ) -> Vec<T> {
319
+ let mut v: Vec<(K, T)> = it.into_iter().map(|x| (key(x.clone()), x)).collect();
320
+ if reverse { v.sort_by(|a, b| cmp(&b.0, &a.0)) } else { v.sort_by(|a, b| cmp(&a.0, &b.0)) }
321
+ v.into_iter().map(|(_, x)| x).collect()
322
+ }
323
+
324
+ pub fn sort_by_key<T: Clone, K: PartialOrd>(xs: &mut Vec<T>, key: impl FnMut(T) -> K, reverse: bool) {
325
+ *xs = sorted_by_key(xs.clone(), key, reverse);
326
+ }
327
+
328
+ pub fn min_opt<T: PartialOrd, I: IntoIterator<Item = T>>(it: I) -> Option<T> {
329
+ it.into_iter().reduce(|a, b| if cmp(&b, &a) == Ordering::Less { b } else { a })
330
+ }
331
+
332
+ pub fn max_opt<T: PartialOrd, I: IntoIterator<Item = T>>(it: I) -> Option<T> {
333
+ it.into_iter().reduce(|a, b| if cmp(&b, &a) == Ordering::Greater { b } else { a })
334
+ }
335
+
336
+ pub fn min<T: PartialOrd, I: IntoIterator<Item = T>>(it: I) -> T {
337
+ min_opt(it).expect("ValueError: min() iterable argument is empty")
338
+ }
339
+
340
+ pub fn max<T: PartialOrd, I: IntoIterator<Item = T>>(it: I) -> T {
341
+ max_opt(it).expect("ValueError: max() iterable argument is empty")
342
+ }
343
+
344
+ /// A node of the exception-kind tree: one `static` per Python exception class, linked to its parent.
345
+ /// `is_a` walks the chain, so catching a base class catches subclasses exactly like Python.
346
+ pub struct ExcKind {
347
+ pub name: &'static str,
348
+ pub parent: Option<&'static ExcKind>,
349
+ }
350
+
351
+ impl ExcKind {
352
+ pub fn is_a(&'static self, ancestor: &'static ExcKind) -> bool {
353
+ let mut cur = Some(self);
354
+ while let Some(kind) = cur {
355
+ if std::ptr::eq(kind, ancestor) {
356
+ return true;
357
+ }
358
+ cur = kind.parent;
359
+ }
360
+ false
361
+ }
362
+ }
363
+
364
+ /// Python's built-in exception classes.
365
+ pub mod kinds {
366
+ use super::ExcKind;
367
+
368
+ macro_rules! kind {
369
+ ($ident:ident, $name:expr, $parent:expr) => {
370
+ pub static $ident: ExcKind = ExcKind { name: $name, parent: $parent };
371
+ };
372
+ }
373
+ kind!(BASE_EXCEPTION, "BaseException", None);
374
+ kind!(EXCEPTION, "Exception", Some(&BASE_EXCEPTION));
375
+ kind!(ARITHMETIC_ERROR, "ArithmeticError", Some(&EXCEPTION));
376
+ kind!(ZERO_DIVISION_ERROR, "ZeroDivisionError", Some(&ARITHMETIC_ERROR));
377
+ kind!(OVERFLOW_ERROR, "OverflowError", Some(&ARITHMETIC_ERROR));
378
+ kind!(LOOKUP_ERROR, "LookupError", Some(&EXCEPTION));
379
+ kind!(INDEX_ERROR, "IndexError", Some(&LOOKUP_ERROR));
380
+ kind!(KEY_ERROR, "KeyError", Some(&LOOKUP_ERROR));
381
+ kind!(VALUE_ERROR, "ValueError", Some(&EXCEPTION));
382
+ kind!(JSON_DECODE_ERROR, "JSONDecodeError", Some(&VALUE_ERROR));
383
+ kind!(VALIDATION_ERROR, "ValidationError", Some(&VALUE_ERROR));
384
+ kind!(RE_ERROR, "error", Some(&EXCEPTION));
385
+ kind!(TYPE_ERROR, "TypeError", Some(&EXCEPTION));
386
+ kind!(ATTRIBUTE_ERROR, "AttributeError", Some(&EXCEPTION));
387
+ kind!(ASSERTION_ERROR, "AssertionError", Some(&EXCEPTION));
388
+ kind!(RUNTIME_ERROR, "RuntimeError", Some(&EXCEPTION));
389
+ kind!(NOT_IMPLEMENTED_ERROR, "NotImplementedError", Some(&RUNTIME_ERROR));
390
+ kind!(OS_ERROR, "OSError", Some(&EXCEPTION));
391
+ kind!(FILE_NOT_FOUND_ERROR, "FileNotFoundError", Some(&OS_ERROR));
392
+ kind!(TIMEOUT_ERROR, "TimeoutError", Some(&OS_ERROR));
393
+ kind!(STOP_ITERATION, "StopIteration", Some(&EXCEPTION));
394
+ }
395
+
396
+ /// The one crate-level error type: a kind in the tree, a message, and an optional cause
397
+ /// (`raise X from e`).
398
+ #[derive(Debug, Clone)]
399
+ pub struct PyError {
400
+ pub kind: &'static ExcKind,
401
+ pub message: String,
402
+ pub cause: Option<Box<PyError>>,
403
+ }
404
+
405
+ impl std::fmt::Debug for ExcKind {
406
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407
+ f.write_str(self.name)
408
+ }
409
+ }
410
+
411
+ impl PyError {
412
+ /// `message` is the exception's single argument. `message` of the result is `str(e)`: for a
413
+ /// KeyError that is the repr of the argument (`KeyError("k")` prints `'k'`).
414
+ pub fn new(kind: &'static ExcKind, message: impl Into<String>) -> Self {
415
+ let message = message.into();
416
+ let message = if kind.is_a(&kinds::KEY_ERROR) { repr_str(&message) } else { message };
417
+ PyError { kind, message, cause: None }
418
+ }
419
+
420
+ /// `repr(e)`: the class name and the repr of its argument, like `KeyError('k')`.
421
+ pub fn repr(&self) -> String {
422
+ let arg = if self.kind.is_a(&kinds::KEY_ERROR) {
423
+ self.message.clone() // already the repr of the key
424
+ } else if self.message.is_empty() {
425
+ String::new()
426
+ } else {
427
+ repr_str(&self.message)
428
+ };
429
+ format!("{}({arg})", self.kind.name)
430
+ }
431
+
432
+ /// An exception raised without arguments: `str(e)` is empty.
433
+ pub fn bare(kind: &'static ExcKind) -> Self {
434
+ PyError { kind, message: String::new(), cause: None }
435
+ }
436
+
437
+ pub fn with_cause(mut self, cause: PyError) -> Self {
438
+ self.cause = Some(Box::new(cause));
439
+ self
440
+ }
441
+
442
+ pub fn is_a(&self, ancestor: &'static ExcKind) -> bool {
443
+ self.kind.is_a(ancestor)
444
+ }
445
+ }
446
+
447
+ impl std::fmt::Display for PyError {
448
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
449
+ f.write_str(&self.message)
450
+ }
451
+ }
452
+
453
+ impl std::error::Error for PyError {}
454
+
455
+ /// Zero code points of the Unicode decimal digit ranges (category Nd).
456
+ const DIGIT_ZEROS: &[u32] = &[
457
+ 0x30, 0x660, 0x6F0, 0x7C0, 0x966, 0x9E6, 0xA66, 0xAE6, 0xB66, 0xBE6, 0xC66, 0xCE6, 0xD66,
458
+ 0xDE6, 0xE50, 0xED0, 0xF20, 0x1040, 0x1090, 0x17E0, 0x1810, 0x1946, 0x19D0, 0x1A80, 0x1A90,
459
+ 0x1B50, 0x1BB0, 0x1C40, 0x1C50, 0xA620, 0xA8D0, 0xA900, 0xA9D0, 0xA9F0, 0xAA50, 0xABF0,
460
+ 0xFF10, 0x104A0, 0x10D30, 0x11066, 0x110F0, 0x11136, 0x111D0, 0x112F0, 0x11450, 0x114D0,
461
+ 0x11650, 0x116C0, 0x11730, 0x118E0, 0x11950, 0x11C50, 0x11D50, 0x11DA0, 0x16A60, 0x16AC0,
462
+ 0x16B50, 0x1D7CE, 0x1D7D8, 0x1D7E2, 0x1D7EC, 0x1D7F6, 0x1E140, 0x1E2F0, 0x1E950, 0x1FBF0,
463
+ ];
464
+
465
+ /// A Python numeric literal body as ASCII: stripped, Unicode digits mapped, single underscores
466
+ /// between digits removed. None when Python would reject the underscores.
467
+ fn ascii_number(s: &str) -> Option<String> {
468
+ let mut out = String::new();
469
+ let mut previous_digit = false;
470
+ let mut chars = s.trim_matches(is_space).chars().peekable();
471
+ while let Some(c) = chars.next() {
472
+ let code = c as u32;
473
+ let digit = DIGIT_ZEROS.iter().find(|z| code >= **z && code < **z + 10).map(|z| code - z);
474
+ if let Some(d) = digit {
475
+ out.push(char::from(b'0' + d as u8));
476
+ previous_digit = true;
477
+ continue;
478
+ }
479
+ if c == '_' {
480
+ let next_digit = chars.peek().is_some_and(|n| n.is_numeric());
481
+ if !(previous_digit && next_digit) {
482
+ return None;
483
+ }
484
+ } else {
485
+ out.push(c);
486
+ }
487
+ previous_digit = false;
488
+ }
489
+ Some(out)
490
+ }
491
+
492
+ /// `int(s)` that reports ValueError as an error value (OverflowError beyond i64).
493
+ pub fn try_int(s: &str) -> Result<i64, PyError> {
494
+ let invalid = || {
495
+ PyError::new(
496
+ &kinds::VALUE_ERROR,
497
+ format!("invalid literal for int() with base 10: {}", repr_str(s)),
498
+ )
499
+ };
500
+ let text = ascii_number(s).ok_or_else(invalid)?;
501
+ let body = text.strip_prefix(['+', '-']).unwrap_or(&text);
502
+ if body.is_empty() || !body.bytes().all(|b| b.is_ascii_digit()) {
503
+ return Err(invalid());
504
+ }
505
+ text.parse::<i64>().map_err(|_| {
506
+ PyError::new(&kinds::OVERFLOW_ERROR, "integer does not fit in i64")
507
+ })
508
+ }
509
+
510
+ /// `float(s)` that reports ValueError as an error value.
511
+ pub fn try_float(s: &str) -> Result<f64, PyError> {
512
+ let invalid = || {
513
+ PyError::new(&kinds::VALUE_ERROR, format!("could not convert string to float: {}", repr_str(s)))
514
+ };
515
+ ascii_number(s).ok_or_else(invalid)?.parse::<f64>().map_err(|_| invalid())
516
+ }
517
+
518
+ /// `xs[i]` with IndexError as an error value.
519
+ pub fn try_idx(i: i64, len: usize) -> Result<usize, PyError> {
520
+ try_idx_in(i, len, "list index out of range")
521
+ }
522
+
523
+ fn try_idx_in(i: i64, len: usize, message: &'static str) -> Result<usize, PyError> {
524
+ let j = if i < 0 { i + len as i64 } else { i };
525
+ if j < 0 || j >= len as i64 {
526
+ return Err(PyError::new(&kinds::INDEX_ERROR, message));
527
+ }
528
+ Ok(j as usize)
529
+ }
530
+
531
+ pub fn try_str_item(s: &str, i: i64) -> Result<String, PyError> {
532
+ let chars: Vec<char> = s.chars().collect();
533
+ Ok(chars[try_idx_in(i, chars.len(), "string index out of range")?].to_string())
534
+ }
535
+
536
+ pub fn try_floordiv(a: i64, b: i64) -> Result<i64, PyError> {
537
+ if b == 0 {
538
+ return Err(PyError::new(&kinds::ZERO_DIVISION_ERROR, "division by zero"));
539
+ }
540
+ Ok(floordiv(a, b))
541
+ }
542
+
543
+ pub fn try_floormod(a: i64, b: i64) -> Result<i64, PyError> {
544
+ if b == 0 {
545
+ return Err(PyError::new(&kinds::ZERO_DIVISION_ERROR, "division by zero"));
546
+ }
547
+ Ok(floormod(a, b))
548
+ }
549
+
550
+ pub fn try_floordiv_f(a: f64, b: f64) -> Result<f64, PyError> {
551
+ try_div(a, b)?;
552
+ Ok(floordiv_f(a, b))
553
+ }
554
+
555
+ pub fn try_floormod_f(a: f64, b: f64) -> Result<f64, PyError> {
556
+ try_div(a, b)?;
557
+ Ok(floormod_f(a, b))
558
+ }
559
+
560
+ pub fn try_div(a: f64, b: f64) -> Result<f64, PyError> {
561
+ if b == 0.0 {
562
+ return Err(PyError::new(&kinds::ZERO_DIVISION_ERROR, "division by zero"));
563
+ }
564
+ Ok(a / b)
565
+ }
566
+
567
+ /// `repr()` of the Python values that can be dictionary keys.
568
+ pub trait PyRepr {
569
+ fn py_repr(&self) -> String;
570
+ }
571
+
572
+ impl PyRepr for str {
573
+ fn py_repr(&self) -> String {
574
+ repr_str(self)
575
+ }
576
+ }
577
+
578
+ impl PyRepr for String {
579
+ fn py_repr(&self) -> String {
580
+ repr_str(self)
581
+ }
582
+ }
583
+
584
+ impl PyRepr for i64 {
585
+ fn py_repr(&self) -> String {
586
+ self.to_string()
587
+ }
588
+ }
589
+
590
+ impl PyRepr for bool {
591
+ fn py_repr(&self) -> String {
592
+ fmt_bool(*self)
593
+ }
594
+ }
595
+
596
+ impl PyRepr for f64 {
597
+ fn py_repr(&self) -> String {
598
+ fmt_float(*self)
599
+ }
600
+ }
601
+
602
+ impl<T: PyRepr + ?Sized> PyRepr for &T {
603
+ fn py_repr(&self) -> String {
604
+ (**self).py_repr()
605
+ }
606
+ }
607
+
608
+ impl<A: PyRepr, B: PyRepr> PyRepr for (A, B) {
609
+ fn py_repr(&self) -> String {
610
+ format!("({}, {})", self.0.py_repr(), self.1.py_repr())
611
+ }
612
+ }
613
+
614
+ impl<A: PyRepr, B: PyRepr, C: PyRepr> PyRepr for (A, B, C) {
615
+ fn py_repr(&self) -> String {
616
+ format!("({}, {}, {})", self.0.py_repr(), self.1.py_repr(), self.2.py_repr())
617
+ }
618
+ }
619
+
620
+ /// The KeyError for a missing `key` (`d.get(&key).cloned().ok_or_else(|| rt::key_error(&key))?`);
621
+ /// `str(e)` is the repr of the key, like CPython.
622
+ pub fn key_error<K: PyRepr + ?Sized>(key: &K) -> PyError {
623
+ PyError { kind: &kinds::KEY_ERROR, message: key.py_repr(), cause: None }
624
+ }
625
+
626
+ /// Unwrap a Result outside any `try`: Python would raise, here it panics with the exception class
627
+ /// name as message prefix (so `assert_raises` and callers can still classify it).
628
+ pub fn or_panic<T>(r: Result<T, PyError>) -> T {
629
+ match r {
630
+ Ok(v) => v,
631
+ Err(e) => panic!("{}: {}", e.kind.name, e.message),
632
+ }
633
+ }
634
+
635
+ /// `json.loads(s)`; JSONDecodeError is a ValueError. Object key order is preserved
636
+ /// (this crate enables serde_json's `preserve_order`).
637
+ pub fn json_loads(s: &str) -> Result<serde_json::Value, PyError> {
638
+ serde_json::from_str(s)
639
+ .map_err(|e| PyError::new(&kinds::JSON_DECODE_ERROR, e.to_string()))
640
+ }
641
+
642
+ fn json_string(s: &str, out: &mut String) {
643
+ out.push('"');
644
+ for c in s.chars() {
645
+ match c {
646
+ '"' => out.push_str("\\\""),
647
+ '\\' => out.push_str("\\\\"),
648
+ '\n' => out.push_str("\\n"),
649
+ '\r' => out.push_str("\\r"),
650
+ '\t' => out.push_str("\\t"),
651
+ '\u{8}' => out.push_str("\\b"),
652
+ '\u{c}' => out.push_str("\\f"),
653
+ c if (c as u32) < 0x20 || (c as u32) > 0x7e => {
654
+ let mut units = [0u16; 2];
655
+ for u in c.encode_utf16(&mut units) {
656
+ out.push_str(&format!("\\u{:04x}", u));
657
+ }
658
+ }
659
+ c => out.push(c),
660
+ }
661
+ }
662
+ out.push('"');
663
+ }
664
+
665
+ fn json_write(v: &serde_json::Value, out: &mut String) {
666
+ use serde_json::Value;
667
+ match v {
668
+ Value::Null => out.push_str("null"),
669
+ Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
670
+ Value::Number(n) => match n.as_f64() {
671
+ Some(f) if n.is_f64() => out.push_str(&fmt_float(f)),
672
+ _ => out.push_str(&n.to_string()),
673
+ },
674
+ Value::String(s) => json_string(s, out),
675
+ Value::Array(items) => {
676
+ out.push('[');
677
+ for (i, item) in items.iter().enumerate() {
678
+ if i > 0 {
679
+ out.push_str(", ");
680
+ }
681
+ json_write(item, out);
682
+ }
683
+ out.push(']');
684
+ }
685
+ Value::Object(map) => {
686
+ out.push('{');
687
+ for (i, (k, item)) in map.iter().enumerate() {
688
+ if i > 0 {
689
+ out.push_str(", ");
690
+ }
691
+ json_string(k, out);
692
+ out.push_str(": ");
693
+ json_write(item, out);
694
+ }
695
+ out.push('}');
696
+ }
697
+ }
698
+ }
699
+
700
+ /// `json.dumps(v)` with Python's defaults: `", "` and `": "` separators, non-ASCII escaped.
701
+ pub fn json_dumps(v: &serde_json::Value) -> String {
702
+ let mut out = String::new();
703
+ json_write(v, &mut out);
704
+ out
705
+ }
706
+
707
+ /// `len(v)` of a JSON value: arrays, objects and strings (in characters).
708
+ pub fn value_len(v: &serde_json::Value) -> i64 {
709
+ use serde_json::Value;
710
+ match v {
711
+ Value::Array(a) => a.len() as i64,
712
+ Value::Object(o) => o.len() as i64,
713
+ Value::String(s) => s.chars().count() as i64,
714
+ other => panic!("TypeError: object of type {} has no len()", json_type(other)),
715
+ }
716
+ }
717
+
718
+ fn json_type(v: &serde_json::Value) -> &'static str {
719
+ use serde_json::Value;
720
+ match v {
721
+ Value::Null => "NoneType",
722
+ Value::Bool(_) => "bool",
723
+ Value::Number(n) if n.is_f64() => "float",
724
+ Value::Number(_) => "int",
725
+ Value::String(_) => "str",
726
+ Value::Array(_) => "list",
727
+ Value::Object(_) => "dict",
728
+ }
729
+ }
730
+
731
+ /// `s.rsplit(sep, maxsplit)`: at most `n` splits, taken from the right, in left-to-right order.
732
+ pub fn rsplit_n(s: &str, sep: &str, n: i64) -> Vec<String> {
733
+ let mut parts: Vec<String> = s.rsplitn((n.max(0) + 1) as usize, sep).map(String::from).collect();
734
+ parts.reverse();
735
+ parts
736
+ }
737
+
738
+ /// `time.monotonic()` / `time.perf_counter()`: seconds since the first call.
739
+ pub fn monotonic() -> f64 {
740
+ static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
741
+ START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64()
742
+ }
743
+
744
+ /// `re.*` over the `regex` crate. Differences from Python's `re` (drift): no look-around or
745
+ /// backreferences (the pattern is an `error`), `\d`/`\w` are Unicode in both, and a group that did not
746
+ /// take part in a match makes `group(n)` panic instead of returning None.
747
+ #[cfg(feature = "regex")]
748
+ pub mod re {
749
+ use super::{kinds, PyError};
750
+ use std::cell::RefCell;
751
+ use std::collections::HashMap;
752
+
753
+ thread_local! {
754
+ static CACHE: RefCell<HashMap<String, regex::Regex>> = RefCell::new(HashMap::new());
755
+ }
756
+
757
+ fn compiled(pattern: &str) -> Result<regex::Regex, PyError> {
758
+ CACHE.with(|cache| {
759
+ if let Some(re) = cache.borrow().get(pattern) {
760
+ return Ok(re.clone());
761
+ }
762
+ let re = regex::Regex::new(pattern)
763
+ .map_err(|e| PyError::new(&kinds::RE_ERROR, e.to_string()))?;
764
+ cache.borrow_mut().insert(pattern.to_string(), re.clone());
765
+ Ok(re)
766
+ })
767
+ }
768
+
769
+ /// A match: the text of each group and its span in characters.
770
+ #[derive(Debug, Clone)]
771
+ pub struct Match {
772
+ groups: Vec<Option<(String, usize, usize)>>,
773
+ names: Vec<(String, usize)>,
774
+ }
775
+
776
+ impl Match {
777
+ pub fn group(&self, i: i64) -> String {
778
+ self.groups
779
+ .get(i as usize)
780
+ .and_then(|g| g.as_ref())
781
+ .map(|(t, _, _)| t.clone())
782
+ .unwrap_or_else(|| panic!("IndexError: no such group {i}"))
783
+ }
784
+
785
+ pub fn named(&self, name: &str) -> String {
786
+ let i = self.names.iter().find(|(n, _)| n == name).map(|(_, i)| *i);
787
+ self.group(i.unwrap_or_else(|| panic!("IndexError: no such group {name}")) as i64)
788
+ }
789
+
790
+ pub fn groups(&self) -> Vec<String> {
791
+ self.groups.iter().skip(1).map(|g| g.as_ref().map(|(t, _, _)| t.clone()).unwrap_or_default()).collect()
792
+ }
793
+
794
+ pub fn start(&self) -> i64 {
795
+ self.groups[0].as_ref().map_or(-1, |g| g.1 as i64)
796
+ }
797
+
798
+ pub fn end(&self) -> i64 {
799
+ self.groups[0].as_ref().map_or(-1, |g| g.2 as i64)
800
+ }
801
+ }
802
+
803
+ fn make(re: &regex::Regex, text: &str, caps: &regex::Captures) -> Match {
804
+ let chars = |byte: usize| text[..byte].chars().count();
805
+ let groups = (0..caps.len())
806
+ .map(|i| caps.get(i).map(|m| (m.as_str().to_string(), chars(m.start()), chars(m.end()))))
807
+ .collect();
808
+ let names = re.capture_names().enumerate().filter_map(|(i, n)| n.map(|n| (n.to_string(), i))).collect();
809
+ Match { groups, names }
810
+ }
811
+
812
+ fn find(pattern: &str, text: &str) -> Result<Option<Match>, PyError> {
813
+ let re = compiled(pattern)?;
814
+ Ok(re.captures(text).map(|c| make(&re, text, &c)))
815
+ }
816
+
817
+ pub fn search(pattern: &str, text: &str) -> Result<Option<Match>, PyError> {
818
+ find(pattern, text)
819
+ }
820
+
821
+ /// `re.match`: anchored at the start.
822
+ pub fn match_(pattern: &str, text: &str) -> Result<Option<Match>, PyError> {
823
+ find(&format!("\\A(?:{pattern})"), text)
824
+ }
825
+
826
+ pub fn fullmatch(pattern: &str, text: &str) -> Result<Option<Match>, PyError> {
827
+ find(&format!("\\A(?:{pattern})\\z"), text)
828
+ }
829
+
830
+ /// Python replacement syntax (`\1`, `\g<name>`) to the regex crate's (`${1}`, `${name}`).
831
+ fn replacement(repl: &str) -> String {
832
+ let mut out = String::new();
833
+ let mut chars = repl.chars().peekable();
834
+ while let Some(c) = chars.next() {
835
+ match c {
836
+ '$' => out.push_str("$$"),
837
+ '\\' => match chars.peek().copied() {
838
+ Some(d) if d.is_ascii_digit() => {
839
+ chars.next();
840
+ out.push_str(&format!("${{{d}}}"));
841
+ }
842
+ Some('g') => {
843
+ chars.next();
844
+ let name: String = chars.by_ref().skip_while(|c| *c == '<').take_while(|c| *c != '>').collect();
845
+ out.push_str(&format!("${{{name}}}"));
846
+ }
847
+ Some('n') => {
848
+ chars.next();
849
+ out.push('\n');
850
+ }
851
+ Some(d) => {
852
+ chars.next();
853
+ out.push(d);
854
+ }
855
+ None => out.push('\\'),
856
+ },
857
+ c => out.push(c),
858
+ }
859
+ }
860
+ out
861
+ }
862
+
863
+ pub fn sub(pattern: &str, repl: &str, text: &str) -> Result<String, PyError> {
864
+ Ok(compiled(pattern)?.replace_all(text, replacement(repl).as_str()).into_owned())
865
+ }
866
+
867
+ /// `re.findall` for patterns with at most one group (more groups return tuples in Python).
868
+ pub fn findall(pattern: &str, text: &str) -> Result<Vec<String>, PyError> {
869
+ let re = compiled(pattern)?;
870
+ if re.captures_len() > 2 {
871
+ panic!("TypeError: findall with several groups returns tuples (not supported)");
872
+ }
873
+ let group = if re.captures_len() == 2 { 1 } else { 0 };
874
+ Ok(re.captures_iter(text).map(|c| c.get(group).map_or(String::new(), |m| m.as_str().to_string())).collect())
875
+ }
876
+
877
+ pub fn split(pattern: &str, text: &str) -> Result<Vec<String>, PyError> {
878
+ Ok(compiled(pattern)?.split(text).map(String::from).collect())
879
+ }
880
+
881
+ /// `re.compile(pattern, flags)`: an invalid pattern panics (Python raises at import time).
882
+ /// Flags: re.I = 2, re.M = 8, re.S = 16, re.X = 64.
883
+ #[derive(Debug, Clone)]
884
+ pub struct Pattern {
885
+ source: String,
886
+ }
887
+
888
+ impl Pattern {
889
+ pub fn new(pattern: &str, flags: i64) -> Pattern {
890
+ let mut prefix = String::new();
891
+ for (bit, letter) in [(2, 'i'), (8, 'm'), (16, 's'), (64, 'x')] {
892
+ if flags & bit != 0 {
893
+ prefix.push(letter);
894
+ }
895
+ }
896
+ let source = if prefix.is_empty() { pattern.to_string() } else { format!("(?{prefix}){pattern}") };
897
+ if let Err(e) = compiled(&source) {
898
+ panic!("error: {}", e.message);
899
+ }
900
+ Pattern { source }
901
+ }
902
+
903
+ pub fn search(&self, text: &str) -> Option<Match> {
904
+ search(&self.source, text).unwrap()
905
+ }
906
+
907
+ pub fn match_(&self, text: &str) -> Option<Match> {
908
+ match_(&self.source, text).unwrap()
909
+ }
910
+
911
+ pub fn fullmatch(&self, text: &str) -> Option<Match> {
912
+ fullmatch(&self.source, text).unwrap()
913
+ }
914
+
915
+ pub fn sub(&self, repl: &str, text: &str) -> String {
916
+ sub(&self.source, repl, text).unwrap()
917
+ }
918
+
919
+ pub fn findall(&self, text: &str) -> Vec<String> {
920
+ findall(&self.source, text).unwrap()
921
+ }
922
+
923
+ pub fn split(&self, text: &str) -> Vec<String> {
924
+ split(&self.source, text).unwrap()
925
+ }
926
+ }
927
+ }
928
+
929
+ /// `hashlib.sha256(data)` / `md5(data)`: an immutable digest (`update()` is not supported).
930
+ #[cfg(feature = "hash")]
931
+ #[derive(Debug, Clone)]
932
+ pub struct Digest {
933
+ pub bytes: Vec<u8>,
934
+ }
935
+
936
+ #[cfg(feature = "hash")]
937
+ impl Digest {
938
+ pub fn hexdigest(&self) -> String {
939
+ self.bytes.iter().map(|b| format!("{b:02x}")).collect()
940
+ }
941
+
942
+ pub fn digest(&self) -> Vec<u8> {
943
+ self.bytes.clone()
944
+ }
945
+ }
946
+
947
+ #[cfg(feature = "hash")]
948
+ pub fn sha256(data: &[u8]) -> Digest {
949
+ use sha2::Digest as _;
950
+ Digest { bytes: sha2::Sha256::digest(data).to_vec() }
951
+ }
952
+
953
+ #[cfg(feature = "hash")]
954
+ pub fn md5(data: &[u8]) -> Digest {
955
+ use md5::Digest as _;
956
+ Digest { bytes: md5::Md5::digest(data).to_vec() }
957
+ }
958
+
959
+ /// `base64.b64encode` and friends (bytes in, bytes out, like Python).
960
+ #[cfg(feature = "base64")]
961
+ pub mod b64 {
962
+ use super::{kinds, PyError};
963
+ use base64::Engine as _;
964
+
965
+ pub fn encode(data: &[u8]) -> Vec<u8> {
966
+ base64::engine::general_purpose::STANDARD.encode(data).into_bytes()
967
+ }
968
+
969
+ pub fn urlsafe_encode(data: &[u8]) -> Vec<u8> {
970
+ base64::engine::general_purpose::URL_SAFE.encode(data).into_bytes()
971
+ }
972
+
973
+ pub fn decode(data: &[u8]) -> Result<Vec<u8>, PyError> {
974
+ base64::engine::general_purpose::STANDARD
975
+ .decode(data)
976
+ .map_err(|e| PyError::new(&kinds::VALUE_ERROR, e.to_string()))
977
+ }
978
+
979
+ pub fn urlsafe_decode(data: &[u8]) -> Result<Vec<u8>, PyError> {
980
+ base64::engine::general_purpose::URL_SAFE
981
+ .decode(data)
982
+ .map_err(|e| PyError::new(&kinds::VALUE_ERROR, e.to_string()))
983
+ }
984
+ }
985
+
986
+ /// `pydantic.ValidationError` for a value serde refuses (message texts differ from Pydantic's).
987
+ pub fn validation_error(e: &serde_json::Error) -> PyError {
988
+ PyError::new(&kinds::VALIDATION_ERROR, e.to_string())
989
+ }
990
+
991
+ /// `model_dump(exclude_none=True)`: drop null members of objects, recursively.
992
+ pub fn strip_none(v: serde_json::Value) -> serde_json::Value {
993
+ use serde_json::Value;
994
+ match v {
995
+ Value::Object(map) => Value::Object(
996
+ map.into_iter().filter(|(_, v)| !v.is_null()).map(|(k, v)| (k, strip_none(v))).collect(),
997
+ ),
998
+ Value::Array(items) => Value::Array(items.into_iter().map(strip_none).collect()),
999
+ other => other,
1000
+ }
1001
+ }
1002
+
1003
+ /// `value["key"]` on JSON data: KeyError / TypeError as error values.
1004
+ pub fn value_item(v: &serde_json::Value, key: &str) -> Result<serde_json::Value, PyError> {
1005
+ match v {
1006
+ serde_json::Value::Object(map) => {
1007
+ map.get(key).cloned().ok_or_else(|| key_error(&key))
1008
+ }
1009
+ other => Err(PyError::new(
1010
+ &kinds::TYPE_ERROR,
1011
+ format!("'{}' object is not subscriptable by a string", json_type(other)),
1012
+ )),
1013
+ }
1014
+ }
1015
+
1016
+ /// `value[i]` on a JSON array (negative indices count from the end).
1017
+ pub fn value_at(v: &serde_json::Value, i: i64) -> Result<serde_json::Value, PyError> {
1018
+ match v {
1019
+ serde_json::Value::Array(items) => Ok(items[try_idx(i, items.len())?].clone()),
1020
+ other => Err(PyError::new(
1021
+ &kinds::TYPE_ERROR,
1022
+ format!("'{}' object is not subscriptable by an integer", json_type(other)),
1023
+ )),
1024
+ }
1025
+ }
1026
+
1027
+ /// Python's definition of whitespace: Unicode White_Space plus the U+001C..U+001F separators.
1028
+ pub fn is_space(c: char) -> bool {
1029
+ c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
1030
+ }
1031
+
1032
+ /// `s.strip()` / `lstrip()` / `rstrip()` without arguments.
1033
+ pub fn strip(s: &str) -> String {
1034
+ s.trim_matches(is_space).to_string()
1035
+ }
1036
+
1037
+ pub fn lstrip(s: &str) -> String {
1038
+ s.trim_start_matches(is_space).to_string()
1039
+ }
1040
+
1041
+ pub fn rstrip(s: &str) -> String {
1042
+ s.trim_end_matches(is_space).to_string()
1043
+ }
1044
+
1045
+ /// `s.split()`: runs of whitespace separate, no empty parts.
1046
+ pub fn split_whitespace(s: &str) -> Vec<String> {
1047
+ s.split(is_space).filter(|p| !p.is_empty()).map(String::from).collect()
1048
+ }
1049
+
1050
+ // -- Shared<T>: Python's reference semantics ----------------------------------------------------
1051
+ /// A shared, mutable Python object (list, dict, set, instance). `clone()` copies the HANDLE, never
1052
+ /// the value (that is what `b = a`, `xs.append(a)`, arguments and attribute stores do in Python);
1053
+ /// reads go through `borrow()`, changes through `borrow_mut()`. `Rc<RefCell<T>>` by default,
1054
+ /// `Arc<RwLock<T>>` with the `arc` feature (for async code that must be Send).
1055
+ #[cfg(not(feature = "arc"))]
1056
+ pub struct Shared<T>(std::rc::Rc<std::cell::RefCell<T>>);
1057
+ #[cfg(feature = "arc")]
1058
+ pub struct Shared<T>(std::sync::Arc<std::sync::RwLock<T>>);
1059
+
1060
+ #[cfg(not(feature = "arc"))]
1061
+ impl<T> Shared<T> {
1062
+ pub fn new(value: T) -> Self {
1063
+ Shared(std::rc::Rc::new(std::cell::RefCell::new(value)))
1064
+ }
1065
+ pub fn borrow(&self) -> std::cell::Ref<'_, T> {
1066
+ self.0.borrow()
1067
+ }
1068
+ pub fn borrow_mut(&self) -> std::cell::RefMut<'_, T> {
1069
+ self.0.borrow_mut()
1070
+ }
1071
+ pub fn ptr_eq(&self, other: &Self) -> bool {
1072
+ std::rc::Rc::ptr_eq(&self.0, &other.0)
1073
+ }
1074
+ }
1075
+
1076
+ #[cfg(feature = "arc")]
1077
+ impl<T> Shared<T> {
1078
+ pub fn new(value: T) -> Self {
1079
+ Shared(std::sync::Arc::new(std::sync::RwLock::new(value)))
1080
+ }
1081
+ pub fn borrow(&self) -> std::sync::RwLockReadGuard<'_, T> {
1082
+ self.0.read().expect("poisoned Shared")
1083
+ }
1084
+ pub fn borrow_mut(&self) -> std::sync::RwLockWriteGuard<'_, T> {
1085
+ self.0.write().expect("poisoned Shared")
1086
+ }
1087
+ pub fn ptr_eq(&self, other: &Self) -> bool {
1088
+ std::sync::Arc::ptr_eq(&self.0, &other.0)
1089
+ }
1090
+ }
1091
+
1092
+ impl<T> Clone for Shared<T> {
1093
+ fn clone(&self) -> Self {
1094
+ Shared(self.0.clone())
1095
+ }
1096
+ }
1097
+
1098
+ impl<T: std::fmt::Debug> std::fmt::Debug for Shared<T> {
1099
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1100
+ std::fmt::Debug::fmt(&*self.borrow(), f)
1101
+ }
1102
+ }
1103
+
1104
+ impl<T: PartialEq> PartialEq for Shared<T> {
1105
+ fn eq(&self, other: &Self) -> bool {
1106
+ self.ptr_eq(other) || *self.borrow() == *other.borrow()
1107
+ }
1108
+ }
1109
+
1110
+ impl<T: Default> Default for Shared<T> {
1111
+ fn default() -> Self {
1112
+ Shared::new(T::default())
1113
+ }
1114
+ }
1115
+
1116
+ impl<T> From<T> for Shared<T> {
1117
+ fn from(value: T) -> Self {
1118
+ Shared::new(value)
1119
+ }
1120
+ }
1121
+
1122
+ impl<T: serde::Serialize> serde::Serialize for Shared<T> {
1123
+ fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1124
+ self.borrow().serialize(s)
1125
+ }
1126
+ }
1127
+
1128
+ impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for Shared<T> {
1129
+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1130
+ T::deserialize(d).map(Shared::new)
1131
+ }
1132
+ }
1133
+
1134
+ // -- module init: import-time code runs once, in source order ----------------------------------
1135
+ /// The state of one module's import-time code: not started, running, done.
1136
+ pub struct ModuleInit(std::sync::atomic::AtomicU8);
1137
+
1138
+ impl ModuleInit {
1139
+ pub const fn new() -> Self {
1140
+ ModuleInit(std::sync::atomic::AtomicU8::new(0))
1141
+ }
1142
+ }
1143
+
1144
+ impl Default for ModuleInit {
1145
+ fn default() -> Self {
1146
+ Self::new()
1147
+ }
1148
+ }
1149
+
1150
+ /// Run `f` (the module's import-time statements) once. Called again while it runs (a module that
1151
+ /// imports itself through a cycle) it returns at once: Python also hands out the partly
1152
+ /// initialised module. Another thread arriving while it runs does not wait.
1153
+ pub fn module_init(m: &'static ModuleInit, f: impl FnOnce()) {
1154
+ use std::sync::atomic::Ordering::SeqCst;
1155
+ if m.0.compare_exchange(0, 1, SeqCst, SeqCst).is_ok() {
1156
+ f();
1157
+ m.0.store(2, SeqCst);
1158
+ }
1159
+ }
1160
+
1161
+ /// `module_init` for `python module.py` (`if __name__ == "__main__"` blocks run): panics when the
1162
+ /// import-time code already ran without them, instead of silently skipping the main block.
1163
+ pub fn module_main(m: &'static ModuleInit, f: impl FnOnce()) {
1164
+ let mut ran = false;
1165
+ module_init(m, || {
1166
+ ran = true;
1167
+ f();
1168
+ });
1169
+ assert!(ran, "py2rs_main() called after py2rs_module_init(): the main block did not run");
1170
+ }
1171
+
1172
+ /// Read a module value; if the module init has not run yet it runs now (so a crate that only
1173
+ /// calls one function still sees the values). A value that is still unassigned after that (we are
1174
+ /// inside the init, before its statement) is Python's NameError.
1175
+ pub fn module_value<T>(cell: &'static std::sync::OnceLock<T>, name: &str, init: fn()) -> &'static T {
1176
+ if let Some(v) = cell.get() {
1177
+ return v;
1178
+ }
1179
+ init();
1180
+ cell.get().unwrap_or_else(|| panic!("NameError: name '{name}' is not defined"))
1181
+ }
1182
+
1183
+ /// `module_value` for a value that is not `Sync` (a `Shared` handle): a thread-local cell; the
1184
+ /// result is a clone of the handle.
1185
+ pub fn module_value_tl<T: Clone + 'static>(
1186
+ cell: &'static std::thread::LocalKey<std::cell::OnceCell<T>>,
1187
+ name: &str,
1188
+ init: fn(),
1189
+ ) -> T {
1190
+ if let Some(v) = cell.with(|c| c.get().cloned()) {
1191
+ return v;
1192
+ }
1193
+ init();
1194
+ cell.with(|c| c.get().cloned()).unwrap_or_else(|| panic!("NameError: name '{name}' is not defined"))
1195
+ }
1196
+
1197
+ pub fn module_set_tl<T: 'static>(
1198
+ cell: &'static std::thread::LocalKey<std::cell::OnceCell<T>>,
1199
+ value: T,
1200
+ ) {
1201
+ cell.with(|c| {
1202
+ let _ = c.set(value);
1203
+ });
1204
+ }
1205
+
1206
+ /// Assign a module value (once: the init runs once).
1207
+ pub fn module_set<T>(cell: &std::sync::OnceLock<T>, value: T) {
1208
+ let _ = cell.set(value);
1209
+ }
1210
+
1211
+ /// `xs.insert(i, x)`: the position Python uses (negative counts from the end, out of range clamps).
1212
+ pub fn insert_at(i: i64, len: usize) -> usize {
1213
+ let len = len as i64;
1214
+ (if i < 0 { (i + len).max(0) } else { i.min(len) }) as usize
1215
+ }
1216
+
1217
+ /// `s.title()`: a cased character after an uncased one is upper-cased, the rest lower-cased.
1218
+ pub fn title(s: &str) -> String {
1219
+ let mut out = String::new();
1220
+ let mut inside = false;
1221
+ for c in s.chars() {
1222
+ let cased = c.is_lowercase() || c.is_uppercase();
1223
+ if inside {
1224
+ out.extend(c.to_lowercase());
1225
+ } else {
1226
+ out.extend(c.to_uppercase());
1227
+ }
1228
+ inside = cased;
1229
+ }
1230
+ out
1231
+ }
1232
+
1233
+ /// `s.capitalize()`: first character upper-cased, the rest lower-cased.
1234
+ pub fn capitalize(s: &str) -> String {
1235
+ let mut chars = s.chars();
1236
+ match chars.next() {
1237
+ Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
1238
+ None => String::new(),
1239
+ }
1240
+ }
1241
+
1242
+ /// `round(x, n)` for floats: correctly rounded (ties to even) on the exact binary value.
1243
+ pub fn round_digits(x: f64, n: i64) -> f64 {
1244
+ if !x.is_finite() || n > 323 {
1245
+ return x;
1246
+ }
1247
+ format!("{x:.*}", n as usize).parse().unwrap_or(x)
1248
+ }
1249
+
1250
+ fn group(number: &str) -> String {
1251
+ let (sign, body) = number.strip_prefix('-').map_or(("", number), |b| ("-", b));
1252
+ let (int_part, frac) = body.find('.').map_or((body, ""), |i| body.split_at(i));
1253
+ let mut grouped = String::new();
1254
+ for (i, c) in int_part.chars().enumerate() {
1255
+ if i > 0 && (int_part.len() - i) % 3 == 0 {
1256
+ grouped.push(',');
1257
+ }
1258
+ grouped.push(c);
1259
+ }
1260
+ format!("{sign}{grouped}{frac}")
1261
+ }
1262
+
1263
+ /// `f"{n:,}"`.
1264
+ pub fn group_int(n: i64) -> String {
1265
+ group(&n.to_string())
1266
+ }
1267
+
1268
+ /// `f"{x:,.2f}"`.
1269
+ pub fn group_float(x: f64, digits: i64) -> String {
1270
+ if !x.is_finite() {
1271
+ return if x.is_nan() { "nan".into() } else if x > 0.0 { "inf".into() } else { "-inf".into() };
1272
+ }
1273
+ group(&format!("{x:.*}", digits.max(0) as usize))
1274
+ }
1275
+
1276
+ /// `str.casefold()`: upper- then lower-casing folds ß -> ss and ligatures like Python does.
1277
+ pub fn casefold(s: &str) -> String {
1278
+ s.to_uppercase().to_lowercase()
1279
+ }
1280
+
1281
+ pub fn partition(s: &str, sep: &str) -> (String, String, String) {
1282
+ if sep.is_empty() {
1283
+ panic!("ValueError: empty separator");
1284
+ }
1285
+ match s.split_once(sep) {
1286
+ Some((a, b)) => (a.to_string(), sep.to_string(), b.to_string()),
1287
+ None => (s.to_string(), String::new(), String::new()),
1288
+ }
1289
+ }
1290
+
1291
+ pub fn rpartition(s: &str, sep: &str) -> (String, String, String) {
1292
+ if sep.is_empty() {
1293
+ panic!("ValueError: empty separator");
1294
+ }
1295
+ match s.rsplit_once(sep) {
1296
+ Some((a, b)) => (a.to_string(), sep.to_string(), b.to_string()),
1297
+ None => (String::new(), String::new(), s.to_string()),
1298
+ }
1299
+ }
1300
+
1301
+ /// `s.index(sub)`: like `find` but a missing substring is a ValueError.
1302
+ pub fn try_str_index(s: &str, sub: &str) -> Result<i64, PyError> {
1303
+ match str_find(s, sub) {
1304
+ -1 => Err(PyError::new(&kinds::VALUE_ERROR, "substring not found")),
1305
+ i => Ok(i),
1306
+ }
1307
+ }
1308
+
1309
+ /// `s.zfill(width)`: pad with zeros after a leading sign.
1310
+ pub fn zfill(s: &str, width: i64) -> String {
1311
+ let len = s.chars().count() as i64;
1312
+ if len >= width {
1313
+ return s.to_string();
1314
+ }
1315
+ let (sign, rest) = match s.chars().next() {
1316
+ Some(c @ ('+' | '-')) => (c.to_string(), &s[1..]),
1317
+ _ => (String::new(), s),
1318
+ };
1319
+ format!("{sign}{}{rest}", "0".repeat((width - len) as usize))
1320
+ }
1321
+
1322
+ pub fn ljust(s: &str, width: i64, fill: &str) -> String {
1323
+ let pad = (width - s.chars().count() as i64).max(0) as usize;
1324
+ format!("{s}{}", fill.repeat(pad))
1325
+ }
1326
+
1327
+ pub fn rjust(s: &str, width: i64, fill: &str) -> String {
1328
+ let pad = (width - s.chars().count() as i64).max(0) as usize;
1329
+ format!("{}{s}", fill.repeat(pad))
1330
+ }
1331
+
1332
+ /// `html.escape(s)` (quote=True, the default).
1333
+ pub fn html_escape(s: &str) -> String {
1334
+ s.replace('&', "&amp;")
1335
+ .replace('<', "&lt;")
1336
+ .replace('>', "&gt;")
1337
+ .replace('"', "&quot;")
1338
+ .replace('\'', "&#x27;")
1339
+ }
1340
+
1341
+ fn percent_encode(s: &str, safe: &str, out: &mut String) {
1342
+ for b in s.bytes() {
1343
+ let c = b as char;
1344
+ if b.is_ascii() && (c.is_ascii_alphanumeric() || "_.-~".contains(c) || safe.contains(c)) {
1345
+ out.push(c);
1346
+ } else {
1347
+ out.push_str(&format!("%{b:02X}"));
1348
+ }
1349
+ }
1350
+ }
1351
+
1352
+ /// `urllib.parse.quote(s, safe="/")`.
1353
+ pub fn url_quote(s: &str, safe: &str) -> String {
1354
+ let mut out = String::new();
1355
+ percent_encode(s, safe, &mut out);
1356
+ out
1357
+ }
1358
+
1359
+ /// `urllib.parse.quote_plus(s, safe="")`: spaces become `+`.
1360
+ pub fn url_quote_plus(s: &str, safe: &str) -> String {
1361
+ url_quote(s, &format!("{safe} ")).replace(' ', "+")
1362
+ }
1363
+
1364
+ /// `urllib.parse.unquote(s)`: invalid escapes stay as written; invalid UTF-8 becomes U+FFFD.
1365
+ pub fn url_unquote(s: &str) -> String {
1366
+ let bytes = s.as_bytes();
1367
+ let mut out = Vec::with_capacity(bytes.len());
1368
+ let mut i = 0;
1369
+ while i < bytes.len() {
1370
+ let hex = bytes.get(i + 1..i + 3).and_then(|h| std::str::from_utf8(h).ok());
1371
+ match hex.and_then(|h| u8::from_str_radix(h, 16).ok().filter(|_| !h.starts_with('+'))) {
1372
+ Some(b) if bytes[i] == b'%' => {
1373
+ out.push(b);
1374
+ i += 3;
1375
+ }
1376
+ _ => {
1377
+ out.push(bytes[i]);
1378
+ i += 1;
1379
+ }
1380
+ }
1381
+ }
1382
+ String::from_utf8_lossy(&out).into_owned()
1383
+ }
1384
+
1385
+ /// `urllib.parse.urlencode(pairs)`.
1386
+ pub fn urlencode<K: AsRef<str>, V: std::fmt::Display, I: IntoIterator<Item = (K, V)>>(pairs: I) -> String {
1387
+ let encoded: Vec<String> = pairs
1388
+ .into_iter()
1389
+ .map(|(k, v)| format!("{}={}", url_quote_plus(k.as_ref(), ""), url_quote_plus(&v.to_string(), "")))
1390
+ .collect();
1391
+ encoded.join("&")
1392
+ }
1393
+
1394
+ /// Pydantic (lax mode) validation of one model field: coercion, string transforms, constraints.
1395
+ /// Error texts follow Pydantic's wording but not its structure.
1396
+ #[cfg(feature = "pydantic")]
1397
+ pub mod pydantic {
1398
+ use serde::de::{Deserialize, Deserializer, Error};
1399
+ use serde_json::Value;
1400
+
1401
+ pub enum Rule {
1402
+ Ge(f64),
1403
+ Gt(f64),
1404
+ Le(f64),
1405
+ Lt(f64),
1406
+ MultipleOf(f64),
1407
+ MinLength(usize),
1408
+ MaxLength(usize),
1409
+ Pattern(&'static str),
1410
+ Strip,
1411
+ Lower,
1412
+ Upper,
1413
+ }
1414
+
1415
+ pub trait Field: Sized {
1416
+ /// Pydantic's lax parsing from JSON.
1417
+ fn parse(v: Value) -> Result<Self, String>;
1418
+ fn apply(&mut self, rule: &Rule) -> Result<(), String>;
1419
+ }
1420
+
1421
+ /// The body of a generated `deserialize_with` function.
1422
+ pub fn field<'de, D: Deserializer<'de>, T: Field>(d: D, rules: &[Rule]) -> Result<T, D::Error> {
1423
+ let mut out = T::parse(Value::deserialize(d)?).map_err(D::Error::custom)?;
1424
+ for rule in rules {
1425
+ out.apply(rule).map_err(D::Error::custom)?;
1426
+ }
1427
+ Ok(out)
1428
+ }
1429
+
1430
+ /// pydantic-core's float check: the remainder may be off by one part in 1e9 of the value.
1431
+ fn is_multiple(x: f64, b: f64) -> bool {
1432
+ let rem = x % b;
1433
+ let threshold = x.abs() / 1e9;
1434
+ !(rem.abs() > threshold && (rem - b).abs() > threshold)
1435
+ }
1436
+
1437
+ fn number(x: f64, rule: &Rule) -> Result<(), String> {
1438
+ let bad = |text: &str, bound: f64| Err(format!("Input should be {text} {bound}"));
1439
+ match *rule {
1440
+ Rule::Ge(b) if !(x >= b) => bad("greater than or equal to", b),
1441
+ Rule::Gt(b) if !(x > b) => bad("greater than", b),
1442
+ Rule::Le(b) if !(x <= b) => bad("less than or equal to", b),
1443
+ Rule::Lt(b) if !(x < b) => bad("less than", b),
1444
+ Rule::MultipleOf(b) if !is_multiple(x, b) => bad("a multiple of", b),
1445
+ _ => Ok(()),
1446
+ }
1447
+ }
1448
+
1449
+ fn length(len: usize, what: &str, rule: &Rule) -> Result<(), String> {
1450
+ match *rule {
1451
+ Rule::MinLength(n) if len < n => Err(format!("{what} should have at least {n} items or characters")),
1452
+ Rule::MaxLength(n) if len > n => Err(format!("{what} should have at most {n} items or characters")),
1453
+ _ => Ok(()),
1454
+ }
1455
+ }
1456
+
1457
+ impl Field for i64 {
1458
+ fn parse(v: Value) -> Result<Self, String> {
1459
+ let invalid = || "Input should be a valid integer".to_string();
1460
+ match v {
1461
+ Value::Bool(b) => Ok(b as i64),
1462
+ Value::Number(n) => match n.as_i64() {
1463
+ Some(i) => Ok(i),
1464
+ None => {
1465
+ let f = n.as_f64().ok_or_else(invalid)?;
1466
+ let fits = f.fract() == 0.0 && f >= -9.223372036854775e18 && f <= 9.223372036854775e18;
1467
+ if fits && n.is_f64() { Ok(f as i64) } else { Err(invalid()) }
1468
+ }
1469
+ },
1470
+ Value::String(s) => {
1471
+ let t = s.trim();
1472
+ let t = t.strip_suffix(".0").unwrap_or(t);
1473
+ let ok = !t.starts_with('_') && !t.ends_with('_') && !t.contains("__");
1474
+ t.replace('_', "").parse::<i64>().ok().filter(|_| ok).ok_or_else(invalid)
1475
+ }
1476
+ _ => Err(invalid()),
1477
+ }
1478
+ }
1479
+
1480
+ fn apply(&mut self, rule: &Rule) -> Result<(), String> {
1481
+ number(*self as f64, rule)
1482
+ }
1483
+ }
1484
+
1485
+ impl Field for f64 {
1486
+ fn parse(v: Value) -> Result<Self, String> {
1487
+ let invalid = || "Input should be a valid number".to_string();
1488
+ match v {
1489
+ Value::Bool(b) => Ok(if b { 1.0 } else { 0.0 }),
1490
+ Value::Number(n) => n.as_f64().ok_or_else(invalid),
1491
+ Value::String(s) => super::try_float(&s).map_err(|_| invalid()),
1492
+ _ => Err(invalid()),
1493
+ }
1494
+ }
1495
+
1496
+ fn apply(&mut self, rule: &Rule) -> Result<(), String> {
1497
+ number(*self, rule)
1498
+ }
1499
+ }
1500
+
1501
+ impl Field for bool {
1502
+ fn parse(v: Value) -> Result<Self, String> {
1503
+ let invalid = || "Input should be a valid boolean".to_string();
1504
+ match v {
1505
+ Value::Bool(b) => Ok(b),
1506
+ Value::Number(n) => match n.as_f64() {
1507
+ Some(x) if x == 0.0 => Ok(false),
1508
+ Some(x) if x == 1.0 => Ok(true),
1509
+ _ => Err(invalid()),
1510
+ },
1511
+ Value::String(s) => match s.to_ascii_lowercase().as_str() {
1512
+ "true" | "t" | "yes" | "y" | "on" | "1" => Ok(true),
1513
+ "false" | "f" | "no" | "n" | "off" | "0" => Ok(false),
1514
+ _ => Err(invalid()),
1515
+ },
1516
+ _ => Err(invalid()),
1517
+ }
1518
+ }
1519
+
1520
+ fn apply(&mut self, _rule: &Rule) -> Result<(), String> {
1521
+ Ok(())
1522
+ }
1523
+ }
1524
+
1525
+ impl Field for String {
1526
+ fn parse(v: Value) -> Result<Self, String> {
1527
+ match v {
1528
+ Value::String(s) => Ok(s),
1529
+ _ => Err("Input should be a valid string".to_string()),
1530
+ }
1531
+ }
1532
+
1533
+ fn apply(&mut self, rule: &Rule) -> Result<(), String> {
1534
+ match rule {
1535
+ Rule::Strip => *self = super::strip(self),
1536
+ Rule::Lower => *self = self.to_lowercase(),
1537
+ Rule::Upper => *self = self.to_uppercase(),
1538
+ Rule::Pattern(p) => {
1539
+ #[cfg(feature = "regex")]
1540
+ if super::re::search(p, self).map_err(|e| e.message)?.is_none() {
1541
+ return Err(format!("String should match pattern '{p}'"));
1542
+ }
1543
+ #[cfg(not(feature = "regex"))]
1544
+ return Err(format!("pattern '{p}' needs the regex feature"));
1545
+ }
1546
+ other => length(self.chars().count(), "String", other)?,
1547
+ }
1548
+ Ok(())
1549
+ }
1550
+ }
1551
+
1552
+ impl<T: Field> Field for Option<T> {
1553
+ fn parse(v: Value) -> Result<Self, String> {
1554
+ if v.is_null() { Ok(None) } else { T::parse(v).map(Some) }
1555
+ }
1556
+
1557
+ fn apply(&mut self, rule: &Rule) -> Result<(), String> {
1558
+ self.as_mut().map_or(Ok(()), |v| v.apply(rule))
1559
+ }
1560
+ }
1561
+
1562
+ impl<T: Field> Field for Vec<T> {
1563
+ fn parse(v: Value) -> Result<Self, String> {
1564
+ match v {
1565
+ Value::Array(items) => items.into_iter().map(T::parse).collect(),
1566
+ _ => Err("Input should be a valid list".to_string()),
1567
+ }
1568
+ }
1569
+
1570
+ fn apply(&mut self, rule: &Rule) -> Result<(), String> {
1571
+ length(self.len(), "List", rule)
1572
+ }
1573
+ }
1574
+
1575
+ /// What Pydantic accepts as a model: a JSON object (never an array), where the last of several
1576
+ /// equal keys wins. `W` is a private struct that derives Deserialize.
1577
+ pub struct Object<W>(pub W);
1578
+
1579
+ impl<'de, W: serde::de::DeserializeOwned> Deserialize<'de> for Object<W> {
1580
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
1581
+ let value = Value::deserialize(d)?;
1582
+ if !value.is_object() {
1583
+ return Err(D::Error::custom("Input should be a valid dictionary or object to extract fields from"));
1584
+ }
1585
+ W::deserialize(value).map(Object).map_err(D::Error::custom)
1586
+ }
1587
+ }
1588
+
1589
+ impl<T: Field> Field for super::Shared<T> {
1590
+ fn parse(v: Value) -> Result<Self, String> {
1591
+ T::parse(v).map(super::Shared::new)
1592
+ }
1593
+
1594
+ fn apply(&mut self, rule: &Rule) -> Result<(), String> {
1595
+ self.borrow_mut().apply(rule)
1596
+ }
1597
+ }
1598
+
1599
+ /// A required field of any type: a missing key is an error even for `Option`.
1600
+ pub fn required<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<T, D::Error> {
1601
+ T::deserialize(d)
1602
+ }
1603
+ }
1604
+
1605
+ /// `pytest.approx(expected, rel, abs)`: |actual - expected| <= max(rel * |expected|, abs).
1606
+ pub fn approx_eq(actual: f64, expected: f64, rel: f64, abs: f64) -> bool {
1607
+ if actual == expected {
1608
+ return true;
1609
+ }
1610
+ if actual.is_nan() || expected.is_nan() || actual.is_infinite() || expected.is_infinite() {
1611
+ return false;
1612
+ }
1613
+ (actual - expected).abs() <= (rel * expected.abs()).max(abs)
1614
+ }
1615
+
1616
+ /// The exception class name a panic message stands for: our helpers prefix the class name; native
1617
+ /// Rust panics (direct `xs[0]`, `/ 0`) are classified by their well-known texts.
1618
+ fn panic_kind(message: &str) -> &str {
1619
+ if message.contains("index out of bounds") {
1620
+ "IndexError"
1621
+ } else if message.contains("divide by zero") || message.contains("divisor of zero") {
1622
+ "ZeroDivisionError"
1623
+ } else if message.contains("overflow") {
1624
+ "OverflowError"
1625
+ } else {
1626
+ message.split(':').next().unwrap_or("")
1627
+ }
1628
+ }
1629
+
1630
+ fn kind_named(name: &str) -> Option<&'static ExcKind> {
1631
+ use kinds::*;
1632
+ [
1633
+ &BASE_EXCEPTION, &EXCEPTION, &ARITHMETIC_ERROR, &ZERO_DIVISION_ERROR, &OVERFLOW_ERROR,
1634
+ &LOOKUP_ERROR, &INDEX_ERROR, &KEY_ERROR, &VALUE_ERROR, &JSON_DECODE_ERROR, &VALIDATION_ERROR, &RE_ERROR, &TYPE_ERROR, &ATTRIBUTE_ERROR,
1635
+ &ASSERTION_ERROR, &RUNTIME_ERROR, &NOT_IMPLEMENTED_ERROR, &OS_ERROR, &FILE_NOT_FOUND_ERROR,
1636
+ &TIMEOUT_ERROR, &STOP_ITERATION,
1637
+ ]
1638
+ .into_iter()
1639
+ .find(|k| k.name == name)
1640
+ }
1641
+
1642
+ /// `with pytest.raises(kind): body`. The body returns `Err(e)` when an exception is raised inside
1643
+ /// it (a lowered `raise`, or a fallible operation); a panic from a callee that panics instead of
1644
+ /// returning a Result (index, division, ...) counts as the exception its message names.
1645
+ pub fn assert_raises(kind: &'static ExcKind, body: impl FnOnce() -> Result<(), PyError>) {
1646
+ match std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)) {
1647
+ Ok(Ok(())) => panic!("DID NOT RAISE {}", kind.name),
1648
+ Ok(Err(e)) => assert!(e.is_a(kind), "expected {}, raised {}: {}", kind.name, e.kind.name, e.message),
1649
+ Err(payload) => {
1650
+ let message = payload
1651
+ .downcast_ref::<String>()
1652
+ .cloned()
1653
+ .or_else(|| payload.downcast_ref::<&str>().map(|s| s.to_string()))
1654
+ .unwrap_or_default();
1655
+ let raised = kind_named(panic_kind(&message));
1656
+ assert!(raised.is_some_and(|k| k.is_a(kind)), "expected {}, panicked with: {message}", kind.name);
1657
+ }
1658
+ }
1659
+ }
1660
+
1661
+ #[cfg(all(test, feature = "regex"))]
1662
+ mod re_tests {
1663
+ use super::*;
1664
+
1665
+ #[test]
1666
+ fn re_matches_like_python() {
1667
+ let m = re::search(r"(?P<y>\d{4})-(\d{2})", "on 2024-05-17").unwrap().unwrap();
1668
+ assert_eq!((m.group(0), m.group(1), m.group(2), m.named("y")), ("2024-05".into(), "2024".into(), "05".into(), "2024".into()));
1669
+ assert_eq!((m.start(), m.end()), (3, 10));
1670
+ assert!(re::match_(r"\d+", "x1").unwrap().is_none() && re::match_(r"\d+", "12x").unwrap().is_some());
1671
+ assert!(re::fullmatch(r"\d+", "12x").unwrap().is_none());
1672
+ assert_eq!(re::sub(r"(\w+)@(\w+)", r"\2 at \1$", "joe@example").unwrap(), "example at joe$");
1673
+ assert_eq!(re::findall(r"\d+", "a1b22c333").unwrap(), vec!["1", "22", "333"]);
1674
+ assert_eq!(re::findall(r"(\d)\w", "a1b22c3d").unwrap(), vec!["1", "2", "3"]);
1675
+ assert_eq!(re::split(r"\s*,\s*", "a , b,c").unwrap(), vec!["a", "b", "c"]);
1676
+ assert!(re::search("(", "x").unwrap_err().is_a(&kinds::RE_ERROR));
1677
+ assert_eq!(re::search("é+", "caféé").unwrap().unwrap().start(), 3);
1678
+ let p = re::Pattern::new(r"^hello\s+(\w+)$", 2 | 8);
1679
+ assert_eq!(p.search("x\nHELLO World").unwrap().group(1), "World");
1680
+ assert_eq!(p.sub("<\\1>", "Hello a"), "<a>");
1681
+ assert!(p.match_("nope").is_none() && p.fullmatch("hello b").is_some());
1682
+ assert!(std::panic::catch_unwind(|| re::Pattern::new("(", 0)).is_err());
1683
+ }
1684
+ }
1685
+
1686
+ #[cfg(all(test, feature = "hash"))]
1687
+ mod hash_tests {
1688
+ use super::*;
1689
+
1690
+ #[test]
1691
+ fn digests_match_known_vectors() {
1692
+ assert_eq!(sha256(b"abc").hexdigest(), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
1693
+ assert_eq!(md5(b"abc").hexdigest(), "900150983cd24fb0d6963f7d28e17f72");
1694
+ }
1695
+ }
1696
+
1697
+ #[cfg(all(test, feature = "base64"))]
1698
+ mod b64_tests {
1699
+ use super::*;
1700
+
1701
+ #[test]
1702
+ fn base64_round_trip() {
1703
+ assert_eq!(b64::encode(b"hello?>"), b"aGVsbG8/Pg==");
1704
+ assert_eq!(b64::urlsafe_encode(b"hello?>"), b"aGVsbG8_Pg==");
1705
+ assert_eq!(b64::decode(b"aGVsbG8/Pg==").unwrap(), b"hello?>");
1706
+ assert!(b64::decode(b"!!").is_err());
1707
+ }
1708
+ }
1709
+
1710
+ #[cfg(all(test, feature = "pydantic"))]
1711
+ mod pydantic_tests {
1712
+ use super::pydantic::{field, Object, Rule};
1713
+ use serde_json::json;
1714
+
1715
+ fn run<T: super::pydantic::Field>(v: serde_json::Value, rules: &[Rule]) -> Result<T, String> {
1716
+ field::<serde_json::Value, T>(v, rules).map_err(|e| e.to_string())
1717
+ }
1718
+
1719
+ #[test]
1720
+ fn lax_coercion_follows_pydantic() {
1721
+ for good in [json!(5), json!("5"), json!(" 5 "), json!(5.0), json!("5.0")] {
1722
+ assert_eq!(run::<i64>(good.clone(), &[]), Ok(5), "{good}");
1723
+ }
1724
+ assert_eq!((run::<i64>(json!("1_000"), &[]), run::<i64>(json!(true), &[])), (Ok(1000), Ok(1)));
1725
+ for bad in [json!("x"), json!(5.5), json!(null), json!([]), json!(1e30), json!("_1")] {
1726
+ assert!(run::<i64>(bad.clone(), &[]).is_err(), "{bad}");
1727
+ }
1728
+ assert_eq!((run::<f64>(json!("2.5"), &[]), run::<f64>(json!(2), &[])), (Ok(2.5), Ok(2.0)));
1729
+ assert_eq!((run::<bool>(json!("YES"), &[]), run::<bool>(json!(0), &[])), (Ok(true), Ok(false)));
1730
+ assert!(run::<bool>(json!("maybe"), &[]).is_err() && run::<bool>(json!(2), &[]).is_err());
1731
+ assert!(run::<String>(json!(1), &[]).is_err());
1732
+ assert_eq!(run::<Option<i64>>(json!(null), &[Rule::Ge(1.0)]), Ok(None));
1733
+ assert_eq!(run::<Vec<i64>>(json!(["1", 2]), &[]), Ok(vec![1, 2]));
1734
+ }
1735
+
1736
+ #[test]
1737
+ fn models_read_objects_only_and_the_last_duplicate_wins() {
1738
+ #[derive(serde::Deserialize, Debug, PartialEq)]
1739
+ struct W {
1740
+ a: String,
1741
+ b: i64,
1742
+ }
1743
+ let parse = |s: &str| serde_json::from_str::<Object<W>>(s).map(|o| o.0).map_err(|e| e.to_string());
1744
+ assert_eq!(parse(r#"{"a": "x", "b": 1}"#), Ok(W { a: "x".into(), b: 1 }));
1745
+ assert_eq!(parse(r#"{"a": "x", "b": 1, "b": 2}"#), Ok(W { a: "x".into(), b: 2 }));
1746
+ assert!(parse(r#"["x", 1]"#).is_err() && parse("3").is_err() && parse("null").is_err());
1747
+ }
1748
+
1749
+ #[test]
1750
+ fn constraints_and_transforms_apply_in_order() {
1751
+ assert!(run::<i64>(json!(0), &[Rule::Ge(1.0)]).is_err() && run::<i64>(json!(60), &[Rule::Le(60.0)]).is_ok());
1752
+ assert!(run::<i64>(json!(60), &[Rule::Lt(60.0)]).is_err() && run::<i64>(json!(1), &[Rule::Gt(1.0)]).is_err());
1753
+ assert!(run::<i64>(json!(7), &[Rule::MultipleOf(5.0)]).is_err());
1754
+ for ok in [0.3, 0.7, 1.1, 0.0, 12.3] {
1755
+ assert!(run::<f64>(json!(ok), &[Rule::MultipleOf(0.1)]).is_ok(), "{ok}");
1756
+ }
1757
+ assert!(run::<f64>(json!(0.25), &[Rule::MultipleOf(0.1)]).is_err());
1758
+ let rules = [Rule::Strip, Rule::MinLength(1)];
1759
+ assert!(run::<String>(json!(" "), &rules).is_err());
1760
+ assert_eq!(run::<String>(json!(" Ab "), &[Rule::Strip, Rule::Lower]), Ok("ab".to_string()));
1761
+ assert_eq!(run::<String>(json!("ab"), &[Rule::Upper, Rule::MaxLength(2)]), Ok("AB".to_string()));
1762
+ assert!(run::<Vec<String>>(json!(["a", "b", "c"]), &[Rule::MaxLength(2)]).is_err());
1763
+ }
1764
+ }
1765
+
1766
+ #[cfg(test)]
1767
+ mod tests {
1768
+ use super::*;
1769
+
1770
+ #[test]
1771
+ fn monotonic_never_goes_back() {
1772
+ let a = monotonic();
1773
+ assert!(monotonic() >= a);
1774
+ }
1775
+
1776
+ #[test]
1777
+ fn floor_division_and_modulo_follow_python() {
1778
+ assert_eq!((floordiv(-7, 2), floormod(-7, 2)), (-4, 1));
1779
+ assert_eq!((floordiv(7, -2), floormod(7, -2)), (-4, -1));
1780
+ assert_eq!((floordiv(7, 2), floormod(7, 2)), (3, 1));
1781
+ assert_eq!(floordiv_f(-7.0, 2.0), -4.0);
1782
+ assert_eq!(floormod_f(-7.5, 2.0), 0.5);
1783
+ }
1784
+
1785
+ #[test]
1786
+ fn checked_arithmetic_detects_overflow() {
1787
+ assert_eq!((add(2, 3), sub(2, 3), mul(4, 5), neg(7), abs(-7), pow(2, 10), sum([1, 2, 3])), (5, -1, 20, -7, 7, 1024, 6));
1788
+ assert!(std::panic::catch_unwind(|| add(i64::MAX, 1)).is_err());
1789
+ assert!(std::panic::catch_unwind(|| mul(i64::MAX, 2)).is_err());
1790
+ assert!(std::panic::catch_unwind(|| pow(2, 64)).is_err());
1791
+ assert!(std::panic::catch_unwind(|| pow(2, -1)).is_err());
1792
+ assert!(std::panic::catch_unwind(|| floordiv(i64::MIN, -1)).is_err());
1793
+ assert_eq!(floormod(i64::MIN, -1), 0);
1794
+ }
1795
+
1796
+ #[test]
1797
+ fn float_sum_is_compensated_like_python() {
1798
+ assert_eq!(sum_f64([0.1, 0.2, 0.3], 0.0), 0.6);
1799
+ assert_eq!([0.1, 0.2, 0.3].iter().sum::<f64>(), 0.6000000000000001);
1800
+ assert_eq!(sum_f64([1e100, 1.0, -1e100], 0.0), 1.0);
1801
+ assert_eq!(sum_f64(Vec::<f64>::new(), 0.5), 0.5);
1802
+ }
1803
+
1804
+ #[test]
1805
+ fn float_to_int_refuses_what_python_would_bigint() {
1806
+ assert_eq!((float_to_int(-3.7), float_to_int(3.99), round(2.5)), (-3, 3, 2));
1807
+ for bad in [1e30, f64::NAN, f64::INFINITY, -1e30] {
1808
+ assert!(std::panic::catch_unwind(|| float_to_int(bad)).is_err());
1809
+ }
1810
+ }
1811
+
1812
+ #[test]
1813
+ fn exception_tree_and_error_values() {
1814
+ use kinds::*;
1815
+ assert!(INDEX_ERROR.is_a(&LOOKUP_ERROR) && INDEX_ERROR.is_a(&EXCEPTION));
1816
+ assert!(ZERO_DIVISION_ERROR.is_a(&ARITHMETIC_ERROR) && !KEY_ERROR.is_a(&INDEX_ERROR));
1817
+ static MY_ERROR: ExcKind = ExcKind { name: "MyError", parent: Some(&VALUE_ERROR) };
1818
+ let err = PyError::new(&MY_ERROR, "boom").with_cause(PyError::new(&KEY_ERROR, "k"));
1819
+ assert!(err.is_a(&VALUE_ERROR) && err.is_a(&EXCEPTION) && !err.is_a(&TYPE_ERROR));
1820
+ assert_eq!(err.to_string(), "boom");
1821
+ assert_eq!(err.cause.as_ref().map(|c| c.kind.name), Some("KeyError"));
1822
+ assert_eq!(try_int(" 42 ").unwrap(), 42);
1823
+ assert!(try_int("x").unwrap_err().is_a(&VALUE_ERROR));
1824
+ assert!(try_float("1.5").is_ok() && try_float("z").is_err());
1825
+ assert!(try_idx(-1, 3).is_ok() && try_idx(3, 3).unwrap_err().is_a(&LOOKUP_ERROR));
1826
+ assert_eq!(try_idx(3, 3).unwrap_err().message, "list index out of range");
1827
+ assert_eq!(try_floordiv(1, 0).unwrap_err().message, "division by zero");
1828
+ assert_eq!(key_error("b").message, "'b'");
1829
+ assert_eq!(key_error(&2_i64).message, "2");
1830
+ assert_eq!(key_error(&("a".to_string(), 1_i64)).message, "('a', 1)");
1831
+ assert_eq!(PyError::new(&KEY_ERROR, "k").message, "'k'");
1832
+ assert_eq!(PyError::new(&VALUE_ERROR, "k").message, "k");
1833
+ assert_eq!(PyError::new(&VALUE_ERROR, "bad value").repr(), "ValueError('bad value')");
1834
+ assert_eq!((PyError::new(&KEY_ERROR, "k").repr(), PyError::bare(&KEY_ERROR).repr()), ("KeyError('k')".to_string(), "KeyError()".to_string()));
1835
+ assert_eq!((PyError::new(&KEY_ERROR, "").message, PyError::bare(&KEY_ERROR).message), ("''".into(), String::new()));
1836
+ assert!(try_floordiv(1, 0).unwrap_err().is_a(&ARITHMETIC_ERROR));
1837
+ assert_eq!((try_floordiv(-7, 2).unwrap(), try_floormod(-7, 2).unwrap()), (-4, 1));
1838
+ assert!(try_div(1.0, 0.0).is_err() && try_div(3.0, 2.0).unwrap() == 1.5);
1839
+ assert!(key_error(&"a").is_a(&KEY_ERROR));
1840
+ }
1841
+
1842
+ #[test]
1843
+ fn json_round_trip_follows_python_formatting() {
1844
+ let v = json_loads(r#"{"b": 1, "a": [1.5, "x", null, true], "é": "ü😀\n"}"#).unwrap();
1845
+ assert_eq!(
1846
+ json_dumps(&v),
1847
+ r#"{"b": 1, "a": [1.5, "x", null, true], "\u00e9": "\u00fc\ud83d\ude00\n"}"#
1848
+ );
1849
+ assert_eq!(json_dumps(&serde_json::json!({"k": 2.0})), r#"{"k": 2.0}"#);
1850
+ assert!(json_loads("{").unwrap_err().is_a(&kinds::VALUE_ERROR));
1851
+ assert!(json_loads("{").unwrap_err().is_a(&kinds::JSON_DECODE_ERROR));
1852
+ assert_eq!(value_len(&serde_json::json!({"a": 1, "b": [1, 2]})), 2);
1853
+ assert_eq!(value_len(&serde_json::json!("héé")), 3);
1854
+ assert!(std::panic::catch_unwind(|| value_len(&serde_json::json!(1))).is_err());
1855
+ assert_eq!(rsplit_n("a.b.c", ".", 1), vec!["a.b", "c"]);
1856
+ assert_eq!(rsplit_n("abc", ".", 3), vec!["abc"]);
1857
+ assert_eq!(or_panic(Ok::<i64, PyError>(3)), 3);
1858
+ assert!(std::panic::catch_unwind(|| or_panic::<i64>(Err(PyError::new(&kinds::KEY_ERROR, "k")))).is_err());
1859
+ }
1860
+
1861
+ #[test]
1862
+ fn pydantic_and_json_item_helpers() {
1863
+ use serde_json::json;
1864
+ assert_eq!(strip_none(json!({"a": null, "b": {"c": null, "d": [1, null]}})), json!({"b": {"d": [1, null]}}));
1865
+ assert_eq!(value_item(&json!({"a": 1}), "a").unwrap(), json!(1));
1866
+ assert!(value_item(&json!({}), "a").unwrap_err().is_a(&kinds::KEY_ERROR));
1867
+ assert!(value_item(&json!(1), "a").unwrap_err().is_a(&kinds::TYPE_ERROR));
1868
+ assert_eq!(value_at(&json!([1, 2]), -1).unwrap(), json!(2));
1869
+ assert!(value_at(&json!([]), 0).unwrap_err().is_a(&kinds::INDEX_ERROR));
1870
+ let bad = serde_json::from_str::<serde_json::Value>("{").unwrap_err();
1871
+ assert!(validation_error(&bad).is_a(&kinds::VALUE_ERROR));
1872
+ }
1873
+
1874
+ #[test]
1875
+ fn string_helpers_match_python() {
1876
+ assert_eq!(casefold("Straße fi"), "strasse fi");
1877
+ assert_eq!(partition("a=b=c", "="), ("a".into(), "=".into(), "b=c".into()));
1878
+ assert_eq!(rpartition("a=b=c", "="), ("a=b".into(), "=".into(), "c".into()));
1879
+ assert_eq!(rpartition("abc", "="), ("".into(), "".into(), "abc".into()));
1880
+ assert!(try_str_index("abc", "z").is_err() && try_str_index("héllo", "l").unwrap() == 2);
1881
+ assert_eq!((zfill("42", 5), zfill("-42", 5), zfill("abc", 2)), ("00042".into(), "-0042".into(), "abc".into()));
1882
+ assert_eq!((ljust("ab", 4, "."), rjust("ab", 4, " ")), ("ab..".into(), " ab".into()));
1883
+ assert_eq!(html_escape("<a href=\"x\">'&'</a>"), "&lt;a href=&quot;x&quot;&gt;&#x27;&amp;&#x27;&lt;/a&gt;");
1884
+ assert_eq!(url_quote("a b/c?é", "/"), "a%20b/c%3F%C3%A9");
1885
+ assert_eq!(url_quote("a/b", ""), "a%2Fb");
1886
+ assert_eq!(url_quote_plus("a b+c", ""), "a+b%2Bc");
1887
+ assert_eq!(url_unquote("a%20b%C3%A9%zz%+1"), "a bé%zz%+1");
1888
+ assert_eq!(urlencode([("q", "a b"), ("n", "1&2")]), "q=a+b&n=1%262");
1889
+ }
1890
+
1891
+ #[test]
1892
+ fn float_divmod_follows_cpython() {
1893
+ assert_eq!((floordiv_f(123456.789, 0.0001), floormod_f(7.5, -2.0)), (1234567889.0, -0.5));
1894
+ assert!(floormod_f(-0.0, 0.3) == 0.0 && floormod_f(-0.0, 0.3).is_sign_positive());
1895
+ assert!(std::panic::catch_unwind(|| floordiv_f(1.0, 0.0)).is_err());
1896
+ assert!(std::panic::catch_unwind(|| floormod_f(1.0, 0.0)).is_err());
1897
+ assert!(std::panic::catch_unwind(|| div(1.0, 0.0)).is_err());
1898
+ assert!(try_floordiv_f(1.0, 0.0).is_err() && try_floormod_f(5.0, 2.0).unwrap() == 1.0);
1899
+ }
1900
+
1901
+ #[test]
1902
+ fn parsing_and_printing_follow_python() {
1903
+ assert_eq!(try_int(" 1_000 ").unwrap(), 1000);
1904
+ assert_eq!(try_int("-\u{664}\u{662}").unwrap(), -42);
1905
+ for bad in ["_1", "1_", "1__0", "", "+", "1.0", "0x10"] {
1906
+ assert!(try_int(bad).is_err(), "{bad}");
1907
+ }
1908
+ assert!(try_int("99999999999999999999").unwrap_err().is_a(&kinds::OVERFLOW_ERROR));
1909
+ assert_eq!(try_float("1_0.5").unwrap(), 10.5);
1910
+ assert_eq!(fmt_float(0.30000000000000004 + 1e15), "1000000000000000.2");
1911
+ assert_eq!((fmt_float(-0.0), fmt_float(1e-5), fmt_float(123.456)), ("-0.0".into(), "1e-05".into(), "123.456".into()));
1912
+ assert_eq!(format!("{:.2}|{:>6.1}|{:<5.0}|", Fixed(f64::NAN), Fixed(f64::INFINITY), Fixed(-f64::INFINITY)), "nan| inf|-inf |");
1913
+ assert_eq!(format!("{:08.2}|{:+.1}", Fixed(-3.5), Fixed(2.0)), "-0003.50|+2.0");
1914
+ assert_eq!(strip("\u{1c}x\u{1f}"), "x");
1915
+ assert_eq!(split_whitespace("a\u{1c}b c"), vec!["a", "b", "c"]);
1916
+ }
1917
+
1918
+ #[test]
1919
+ fn shared_handles_alias_and_values_compare_by_content() {
1920
+ let a = Shared::new(vec![1]);
1921
+ let b = a.clone();
1922
+ b.borrow_mut().push(2);
1923
+ assert_eq!(a.borrow().len(), 2);
1924
+ assert!(a.ptr_eq(&b) && a == Shared::new(vec![1, 2]));
1925
+ assert_eq!(serde_json::to_string(&a).unwrap(), "[1,2]");
1926
+ let c: Shared<Vec<i64>> = serde_json::from_str("[3]").unwrap();
1927
+ assert_eq!(*c.borrow(), vec![3]);
1928
+ }
1929
+
1930
+ static INIT_TEST: ModuleInit = ModuleInit::new();
1931
+ static CELL_TEST: std::sync::OnceLock<i64> = std::sync::OnceLock::new();
1932
+ static LOG_TEST: std::sync::Mutex<Vec<&'static str>> = std::sync::Mutex::new(Vec::new());
1933
+
1934
+ fn init_test() {
1935
+ module_init(&INIT_TEST, || {
1936
+ LOG_TEST.lock().unwrap().push("run");
1937
+ module_set(&CELL_TEST, 7);
1938
+ });
1939
+ }
1940
+
1941
+ #[test]
1942
+ fn module_init_runs_once_and_values_trigger_it() {
1943
+ assert_eq!(*module_value(&CELL_TEST, "CELL", init_test), 7);
1944
+ init_test();
1945
+ init_test();
1946
+ assert_eq!(LOG_TEST.lock().unwrap().len(), 1);
1947
+ assert_eq!(*module_value(&CELL_TEST, "CELL", init_test), 7);
1948
+ assert!(std::panic::catch_unwind(|| module_main(&INIT_TEST, || {})).is_err());
1949
+ }
1950
+
1951
+ #[test]
1952
+ fn insert_position_clamps_like_python() {
1953
+ assert_eq!((insert_at(0, 3), insert_at(-1, 3), insert_at(-9, 3), insert_at(9, 3)), (0, 2, 0, 3));
1954
+ }
1955
+
1956
+ #[test]
1957
+ fn title_capitalize_round_and_grouping() {
1958
+ assert_eq!((title("hello world-wide o'neil 2nd"), capitalize("hELLO")), ("Hello World-Wide O'Neil 2Nd".into(), "Hello".into()));
1959
+ assert_eq!((round_digits(2.675, 2), round_digits(0.125, 2), round_digits(2.5, 0)), (2.67, 0.12, 2.0));
1960
+ assert_eq!((group_int(1234567), group_int(-1000), group_int(999)), ("1,234,567".into(), "-1,000".into(), "999".into()));
1961
+ assert_eq!(group_float(-1234567.891, 2), "-1,234,567.89");
1962
+ }
1963
+
1964
+ #[test]
1965
+ fn approx_and_raises_helpers() {
1966
+ assert!(approx_eq(0.30000000000000004, 0.3, 1e-6, 1e-12));
1967
+ assert!(!approx_eq(0.31, 0.3, 1e-6, 1e-12) && !approx_eq(f64::NAN, f64::NAN, 1e-6, 1e-12));
1968
+ assert!(approx_eq(f64::INFINITY, f64::INFINITY, 1e-6, 1e-12));
1969
+ assert_raises(&kinds::INDEX_ERROR, || {
1970
+ idx(5, 2);
1971
+ Ok(())
1972
+ });
1973
+ assert_raises(&kinds::LOOKUP_ERROR, || Err(PyError::new(&kinds::KEY_ERROR, "k")));
1974
+ assert_raises(&kinds::EXCEPTION, || {
1975
+ floordiv(1, 0);
1976
+ Ok(())
1977
+ });
1978
+ assert!(std::panic::catch_unwind(|| assert_raises(&kinds::KEY_ERROR, || Ok(()))).is_err());
1979
+ assert!(
1980
+ std::panic::catch_unwind(|| {
1981
+ assert_raises(&kinds::KEY_ERROR, || Err(PyError::new(&kinds::INDEX_ERROR, "")))
1982
+ })
1983
+ .is_err()
1984
+ );
1985
+ }
1986
+
1987
+ #[test]
1988
+ fn round_is_bankers() {
1989
+ assert_eq!((round(0.5), round(1.5), round(2.5), round(-0.5)), (0, 2, 2, 0));
1990
+ }
1991
+
1992
+ #[test]
1993
+ fn range_with_a_runtime_step() {
1994
+ assert_eq!(range(0, 10, 3).collect::<Vec<_>>(), vec![0, 3, 6, 9]);
1995
+ assert_eq!(range(10, 0, -4).collect::<Vec<_>>(), vec![10, 6, 2]);
1996
+ assert_eq!(range(3, 3, 1).count(), 0);
1997
+ assert!(std::panic::catch_unwind(|| range(0, 1, 0).count()).is_err());
1998
+ }
1999
+
2000
+ #[test]
2001
+ fn negative_indices_resolve_from_the_end() {
2002
+ assert_eq!(idx(-1, 3), 2);
2003
+ assert_eq!(idx(0, 3), 0);
2004
+ }
2005
+
2006
+ #[test]
2007
+ #[should_panic(expected = "IndexError")]
2008
+ fn out_of_range_index_panics() {
2009
+ idx(3, 3);
2010
+ }
2011
+
2012
+ #[test]
2013
+ fn slices_clamp_and_count_characters() {
2014
+ assert_eq!(str_slice("héllo", Some(1), Some(3)), "él");
2015
+ assert_eq!(str_slice("héllo", Some(-3), None), "llo");
2016
+ assert_eq!(str_slice("abc", Some(5), None), "");
2017
+ assert_eq!(str_slice("abc", None, Some(-10)), "");
2018
+ assert_eq!(list_slice(&[1, 2, 3, 4], Some(1), Some(-1)), vec![2, 3]);
2019
+ assert_eq!(str_index("héllo", -4), "é");
2020
+ assert_eq!(str_find("héllo", "l"), 2);
2021
+ assert_eq!(str_find("abc", "z"), -1);
2022
+ }
2023
+
2024
+ #[test]
2025
+ fn repr_picks_python_quotes() {
2026
+ assert_eq!(repr_str("a"), "'a'");
2027
+ assert_eq!(repr_str("it's"), "\"it's\"");
2028
+ assert_eq!(repr_str("a'b\"c"), "'a\\'b\"c'");
2029
+ assert_eq!(repr_str("l1\nl2\t\\"), "'l1\\nl2\\t\\\\'");
2030
+ }
2031
+
2032
+ #[test]
2033
+ fn floats_print_like_python() {
2034
+ assert_eq!(fmt_float(1.0), "1.0");
2035
+ assert_eq!(fmt_float(0.1), "0.1");
2036
+ assert_eq!(fmt_float(-2.5), "-2.5");
2037
+ assert_eq!(fmt_float(1e16), "1e+16");
2038
+ assert_eq!(fmt_float(1.5e-5), "1.5e-05");
2039
+ assert_eq!(fmt_float(f64::INFINITY), "inf");
2040
+ assert_eq!(fmt_float(f64::NAN), "nan");
2041
+ assert_eq!(fmt_float(0.0), "0.0");
2042
+ assert_eq!(fmt_bool(true), "True");
2043
+ }
2044
+
2045
+ #[test]
2046
+ fn truthiness_of_json_values() {
2047
+ use serde_json::json;
2048
+ assert!(!truthy(&json!(null)) && !truthy(&json!([])) && !truthy(&json!("")) && !truthy(&json!(0)));
2049
+ assert!(truthy(&json!({"a": 1})) && truthy(&json!("x")) && truthy(&json!(2.5)));
2050
+ }
2051
+
2052
+ #[test]
2053
+ fn sorting_is_stable_and_supports_keys_and_reverse() {
2054
+ assert_eq!(sorted(vec![3, 1, 2], false), vec![1, 2, 3]);
2055
+ assert_eq!(sorted(vec![3, 1, 2], true), vec![3, 2, 1]);
2056
+ let words = vec!["bb", "a", "cc", "d"];
2057
+ assert_eq!(sorted_by_key(words.clone(), |w| w.len(), false), vec!["a", "d", "bb", "cc"]);
2058
+ assert_eq!(sorted_by_key(words, |w| w.len(), true), vec!["bb", "cc", "a", "d"]);
2059
+ let mut xs = vec![2.5, -1.0, 9.0];
2060
+ sort(&mut xs, false);
2061
+ assert_eq!(xs, vec![-1.0, 2.5, 9.0]);
2062
+ }
2063
+
2064
+ #[test]
2065
+ fn min_and_max_over_iterables() {
2066
+ assert_eq!(min([3, 1, 2]), 1);
2067
+ assert_eq!(max(vec![1.5, 9.5, 2.0]), 9.5);
2068
+ assert_eq!(min_opt(Vec::<i64>::new()), None);
2069
+ assert_eq!(max_opt([1, 2]), Some(2));
2070
+ }
2071
+ }