Skip to main content

unityrs_texture/sprite/
canvas.rs

1// Ported from UnityPy 1.25.2 (MIT): UnityPy/export/SpriteHelper.py's get_image (the alpha merge) and the crop and transposes of get_image_from_sprite. See THIRD_PARTY_LICENSES.
2// Ported from Pillow 9.5.0 (MIT-CMU): src/PIL/Image.py's crop, _crop and _decompression_bomb_check, src/libImaging/Crop.c's ImagingCrop, src/libImaging/Geometry.c's ImagingFlipLeftRight, ImagingFlipTopBottom, ImagingRotate180 and ImagingRotate270, Image.merge's size check, and src/libImaging/Storage.c's ImagingNewPrologueSubtype (its width cap). See THIRD_PARTY_LICENSES.
3//! The images a render works in: the [`Sheet`] it reads, and the canvases
4//! it writes (a crop, a transpose of it, a mask's result, a mesh's
5//! canvas), each charged to the caller's meter before it is allocated.
6//!
7//! **The sheet's orientation.** `get_image` decodes the texture unflipped
8//! (`export/SpriteHelper.py:47-58`), and [`crate::decode()`] flips it, so
9//! row `y` of the sheet UnityPy reads is row `height - 1 - y` of the
10//! decoded image ([`Sheet::pixel`]). A merged sheet is built in the
11//! decoded orientation, row for row, so the rule holds for it too.
12//!
13//! **Pillow's crop** (`Image.crop`, `src/PIL/Image.py:1206-1250`):
14//! the box's right edge is compared with its left, then its lower with its
15//! upper, as Python `float`s (a NaN compares false, so it passes); each
16//! edge is then rounded half to even (`round`: a NaN raises `ValueError`,
17//! an infinity `OverflowError`); the crop's size, `abs(x1 - x0) x abs(y1 -
18//! y0)` in Python's integers, is checked against twice
19//! `MAX_IMAGE_PIXELS` (`DecompressionBombError`, naming that product
20//! exactly); and `im.crop` takes the four as C `int`s (`OverflowError`
21//! past one, worded as `PyLong_AsLong`'s past a C `long`), in that order.
22//! The C crop (`ImagingCrop`) sizes the image by `x1 - x0` and `y1 - y0` in
23//! `int`, a negative side made 0, and fills what lies outside the image
24//! with zeros.
25//!
26//! **Pillow's width cap.** Every image Pillow makes passes
27//! `ImagingNewPrologueSubtype`, which raises `MemoryError` for a width past
28//! `INT_MAX / 4 - 1` whatever the height (`src/libImaging/Storage.c`), so
29//! a 536,870,911 x 0 crop is refused where no pixel is held:
30//! [`width_cap`], which [`Canvas::new`] checks first, and the render
31//! wherever UnityPy makes an image it does not.
32
33// The C and Python names they port: `x0`, `a`, `b`, `xx`.
34// Floats compared exactly, as the ported code compares them.
35#![allow(
36    clippy::many_single_char_names,
37    clippy::similar_names,
38    clippy::float_cmp
39)]
40
41use std::sync::Arc;
42
43use unityrs_core::limits::{Charge, Meter, MeteredVec};
44
45use super::SpriteError;
46use super::exact::Int;
47use crate::MAX_PIXELS;
48use crate::decode::{Image, MAX_CROP_PIXELS};
49use crate::format::Mode;
50
51/// What a sprite renders from (module docs): the decoded texture, or the
52/// texture with its alpha texture merged in.
53#[derive(Debug)]
54pub struct Sheet<'a> {
55    image: SheetImage<'a>,
56}
57
58#[derive(Debug)]
59enum SheetImage<'a> {
60    Texture(&'a Image),
61    Merged(Image),
62}
63
64const _: () = crate::send_sync::<Sheet<'static>>();
65
66impl<'a> Sheet<'a> {
67    /// `get_image` (`export/SpriteHelper.py:44-59`): `texture` as
68    /// [`crate::decode()`] gave it, and, where the render data names an
69    /// alpha texture, the first three bands of `texture` with the first of
70    /// `alpha` (`Image.merge("RGBA", ...)`, `:50-52`), an `RGBA` image
71    /// charged to `meter` before it is allocated.
72    ///
73    /// The renderer is verified on `RGB` and `RGBA` sheets, the five
74    /// formats' (`PARITY.md` section 19.2), so it takes no other, and
75    /// refuses before anything is charged or drawn:
76    /// - a texture that decodes to `L` (BC4) beside an alpha texture is
77    ///   [`SpriteError::AlphaBandCount`], `Image.merge`'s `ValueError`
78    ///   "wrong number of bands", which it raises before it compares sizes;
79    /// - decoded sizes that differ are [`SpriteError::AlphaSizeMismatch`],
80    ///   its "size mismatch";
81    /// - an `L` texture alone, or an `L` alpha texture of the texture's
82    ///   size, which UnityPy renders, is [`SpriteError::UnverifiedMode`],
83    ///   unityrs's own refusal (Tier U) until a render of them is checked
84    ///   against UnityPy's.
85    ///
86    /// UnityPy's cache of the merged sheet is the caller's: a sheet serves
87    /// every sprite of its group.
88    pub fn new(
89        texture: &'a Image,
90        alpha: Option<&Image>,
91        meter: &Arc<Meter>,
92    ) -> Result<Self, SpriteError> {
93        match alpha {
94            None => {
95                verified(texture.mode())?;
96                Ok(Self {
97                    image: SheetImage::Texture(texture),
98                })
99            }
100            Some(alpha) => Sheet::merged(texture, alpha, meter),
101        }
102    }
103
104    /// [`Sheet::new`] with an alpha texture: the merged sheet, which
105    /// borrows neither image, so the caller may drop both once it is made.
106    pub fn merged(
107        texture: &Image,
108        alpha: &Image,
109        meter: &Arc<Meter>,
110    ) -> Result<Sheet<'static>, SpriteError> {
111        // `Image.merge` counts the bands before it compares sizes; one band
112        // and the alpha's are two, where `RGBA` needs four.
113        if texture.mode() == Mode::L {
114            return Err(SpriteError::AlphaBandCount);
115        }
116        if texture.width() != alpha.width() || texture.height() != alpha.height() {
117            return Err(SpriteError::AlphaSizeMismatch);
118        }
119        verified(alpha.mode())?;
120        let mut merged = Canvas::new(Mode::Rgba, texture.width(), texture.height(), meter)?;
121        let tb = bpp(texture.mode());
122        let ab = bpp(alpha.mode());
123        let (tp, ap) = (texture.pixels(), alpha.pixels());
124        super::contained(|| {
125            for (i, out) in merged.pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() {
126                let t = tp.get(i * tb..i * tb + 3).unwrap_or(&[0; 3]);
127                out.get_mut(..3).unwrap_or_default().copy_from_slice(t);
128                if let (Some(o), Some(a)) = (out.get_mut(3), ap.get(i * ab)) {
129                    *o = *a;
130                }
131            }
132        })?;
133        Ok(Sheet {
134            image: SheetImage::Merged(merged.into_image()),
135        })
136    }
137
138    fn image(&self) -> &Image {
139        match &self.image {
140            SheetImage::Texture(i) => i,
141            SheetImage::Merged(i) => i,
142        }
143    }
144
145    /// The mode: the texture's, or `RGBA` when merged.
146    #[must_use]
147    pub fn mode(&self) -> Mode {
148        self.image().mode()
149    }
150
151    /// The width in pixels.
152    #[must_use]
153    pub fn width(&self) -> u32 {
154        self.image().width()
155    }
156
157    /// The height in pixels.
158    #[must_use]
159    pub fn height(&self) -> u32 {
160        self.image().height()
161    }
162
163    /// The pixel at `(x, y)` of the sheet as UnityPy reads it, unflipped
164    /// (module docs), `None` outside it.
165    pub(crate) fn pixel(&self, x: i64, y: i64) -> Option<&[u8]> {
166        let image = self.image();
167        let (w, h) = (i64::from(image.width()), i64::from(image.height()));
168        if x < 0 || y < 0 || x >= w || y >= h {
169            return None;
170        }
171        let b = bpp(image.mode());
172        let at =
173            usize::try_from(((h - 1 - y) * w + x).checked_mul(i64::try_from(b).ok()?)?).ok()?;
174        image.pixels().get(at..at.checked_add(b)?)
175    }
176}
177
178/// A sheet's or an alpha texture's mode the renderer is verified on:
179/// `RGB` or `RGBA` ([`Sheet::new`]).
180fn verified(mode: Mode) -> Result<(), SpriteError> {
181    match mode {
182        Mode::Rgb | Mode::Rgba => Ok(()),
183        Mode::L => Err(SpriteError::UnverifiedMode { mode: mode.name() }),
184    }
185}
186
187/// The bytes of one pixel of `mode`.
188pub(crate) const fn bpp(mode: Mode) -> usize {
189    match mode {
190        Mode::L => 1,
191        Mode::Rgb => 3,
192        Mode::Rgba => 4,
193    }
194}
195
196/// An image being written: top row first, as Pillow holds it, zeroed.
197#[derive(Debug)]
198pub(crate) struct Canvas {
199    pub(crate) mode: Mode,
200    pub(crate) width: u32,
201    pub(crate) height: u32,
202    pub(crate) pixels: Vec<u8>,
203    // After `pixels`: the charge outlives the buffer it pays for.
204    charge: Charge,
205}
206
207/// The widest image Pillow makes, `INT_MAX / 4 - 1` (module docs).
208pub(crate) const WIDTH_CAP: u32 = 536_870_910;
209
210/// Pillow's width cap on an image `width` wide (module docs):
211/// [`SpriteError::ImageTooWide`] past [`WIDTH_CAP`].
212pub(crate) fn width_cap(width: u32) -> Result<(), SpriteError> {
213    if width > WIDTH_CAP {
214        Err(SpriteError::ImageTooWide)
215    } else {
216        Ok(())
217    }
218}
219
220impl Canvas {
221    /// A zeroed canvas, `Image.new(mode, (width, height))`, charged to
222    /// `meter` before it is allocated: Pillow's width cap first
223    /// ([`width_cap`]), then, past [`MAX_PIXELS`] pixels,
224    /// [`SpriteError::TooLarge`]. Its work is its bytes and its rows, one
225    /// each: Pillow callocs a pointer for every row of every image, an
226    /// empty one's included (`ImagingNewPrologueSubtype`,
227    /// `src/libImaging/Storage.c:205`), though `ImagingAllocateArray`
228    /// returns before its row loop for one 0 wide (`Storage.c:385-388`),
229    /// and the transposes step through every row of one 0 wide
230    /// (`src/libImaging/Geometry.c:32-39`, `Geometry.c:76-79`), as
231    /// UnityPy's final flip does on every sprite. So a canvas 0 wide and
232    /// many rows high is work a zero allowance refuses.
233    pub(crate) fn new(
234        mode: Mode,
235        width: u32,
236        height: u32,
237        meter: &Arc<Meter>,
238    ) -> Result<Self, SpriteError> {
239        width_cap(width)?;
240        let pixels = u64::from(width) * u64::from(height);
241        if pixels > MAX_PIXELS {
242            return Err(SpriteError::TooLarge { what: "canvas" });
243        }
244        let len = usize::try_from(pixels * bpp(mode) as u64)
245            .map_err(|_| SpriteError::TooLarge { what: "canvas" })?;
246        meter.count_decode(len as u64 + u64::from(height))?;
247        let (mut buf, charge) = MeteredVec::<u8>::with_capacity(meter, len)?.into_parts();
248        // Within the capacity just reserved: no allocation.
249        buf.resize(len, 0);
250        Ok(Self {
251            mode,
252            width,
253            height,
254            pixels: buf,
255            charge,
256        })
257    }
258
259    fn at(&self, x: u32, y: u32) -> usize {
260        (y as usize * self.width as usize + x as usize) * bpp(self.mode)
261    }
262
263    /// The pixel at `(x, y)`, which the caller keeps inside.
264    pub(crate) fn get(&self, x: u32, y: u32) -> &[u8] {
265        let at = self.at(x, y);
266        self.pixels.get(at..at + bpp(self.mode)).unwrap_or_default()
267    }
268
269    /// The pixel at `(x, y)`, to write.
270    pub(crate) fn get_mut(&mut self, x: u32, y: u32) -> &mut [u8] {
271        let at = self.at(x, y);
272        let b = bpp(self.mode);
273        self.pixels.get_mut(at..at + b).unwrap_or_default()
274    }
275
276    /// The image, as it stands.
277    pub(crate) fn into_image(self) -> Image {
278        Image::from_parts(self.mode, self.width, self.height, self.pixels, self.charge)
279    }
280
281    /// The work of a pass over the canvas, its bytes and its rows, counted
282    /// before it runs, an empty canvas's rows included.
283    fn count_pass(&self, meter: &Meter) -> Result<(), SpriteError> {
284        meter.count_decode(self.pixels.len() as u64 + u64::from(self.height))?;
285        Ok(())
286    }
287
288    /// `transpose(FLIP_TOP_BOTTOM)`, in place.
289    pub(crate) fn flip_top_bottom(&mut self, meter: &Meter) -> Result<(), SpriteError> {
290        self.count_pass(meter)?;
291        let row = self.width as usize * bpp(self.mode);
292        let h = self.height as usize;
293        let pixels = &mut self.pixels;
294        // An empty canvas has nothing to move; its rows are counted above.
295        if row == 0 {
296            return Ok(());
297        }
298        super::contained(|| {
299            for y in 0..h / 2 {
300                let (top, bottom) = pixels.split_at_mut((h - 1 - y) * row);
301                if let (Some(a), Some(b)) =
302                    (top.get_mut(y * row..(y + 1) * row), bottom.get_mut(..row))
303                {
304                    a.swap_with_slice(b);
305                }
306            }
307        })
308    }
309
310    /// `transpose(FLIP_LEFT_RIGHT)`, in place.
311    pub(crate) fn flip_left_right(&mut self, meter: &Meter) -> Result<(), SpriteError> {
312        self.count_pass(meter)?;
313        let b = bpp(self.mode);
314        let row = self.width as usize * b;
315        let pixels = &mut self.pixels;
316        super::contained(|| {
317            if row == 0 {
318                return;
319            }
320            for line in pixels.chunks_exact_mut(row) {
321                let w = line.len() / b;
322                for x in 0..w / 2 {
323                    let (l, r) = line.split_at_mut((w - 1 - x) * b);
324                    if let (Some(p), Some(q)) = (l.get_mut(x * b..(x + 1) * b), r.get_mut(..b)) {
325                        p.swap_with_slice(q);
326                    }
327                }
328            }
329        })
330    }
331
332    /// `transpose(ROTATE_180)`, in place: both flips.
333    pub(crate) fn rotate_180(&mut self, meter: &Meter) -> Result<(), SpriteError> {
334        self.flip_top_bottom(meter)?;
335        self.flip_left_right(meter)
336    }
337
338    /// `transpose(ROTATE_270)`, a quarter turn clockwise, into a new canvas
339    /// of the transposed size: output row `x` holds input column `x`, read
340    /// from the bottom (`ImagingRotate270`: `out[x][ysize - 1 - y] =
341    /// in[y][x]`).
342    pub(crate) fn rotate_270(&self, meter: &Arc<Meter>) -> Result<Self, SpriteError> {
343        let mut out = Self::new(self.mode, self.height, self.width, meter)?;
344        let (w, h) = (self.width, self.height);
345        // The input's rows, read; the output's were counted as it was made.
346        meter.count_decode(u64::from(h))?;
347        if w == 0 || h == 0 {
348            return Ok(out);
349        }
350        super::contained(|| {
351            for y in 0..h {
352                for x in 0..w {
353                    let p = self.get(x, y);
354                    out.get_mut(h - 1 - y, x).copy_from_slice(p);
355                }
356            }
357        })?;
358        Ok(out)
359    }
360}
361
362/// Python's `round(v)` of a `float`: half to even, an integral `f64`; a NaN
363/// is `ValueError`, an infinity `OverflowError`.
364pub(crate) fn py_round(v: f64) -> Result<f64, SpriteError> {
365    if v.is_nan() {
366        Err(SpriteError::RoundNan)
367    } else if v.is_infinite() {
368        Err(SpriteError::RoundInfinity)
369    } else {
370        Ok(v.round_ties_even())
371    }
372}
373
374/// An integral `f64` as `PyArg_ParseTuple`'s `i` takes it, a C `int`.
375pub(crate) fn c_int(v: f64) -> Result<i32, SpriteError> {
376    c_int_of(Int::of_f64(v))
377}
378
379/// A Python `int` as `PyArg_ParseTuple`'s `i` takes it: `PyLong_AsLong`
380/// first (past a C `long`, [`SpriteError::CLongOverflow`]), then the
381/// range of an `int` ([`SpriteError::CIntOverflow`]).
382pub(crate) fn c_int_of(v: Int) -> Result<i32, SpriteError> {
383    let Int::I(i) = v else {
384        return Err(SpriteError::CLongOverflow);
385    };
386    if i64::try_from(i).is_err() {
387        return Err(SpriteError::CLongOverflow);
388    }
389    i32::try_from(i).map_err(|_| SpriteError::CIntOverflow { above: i > 0 })
390}
391
392/// C's `(int)v` of a `double` as x86-64's `cvttsd2si` gives it: toward
393/// zero, and `INT_MIN` for a NaN or a value past an `int`, where C leaves
394/// the conversion undefined (Pillow's wheel is built for x86-64 with GCC).
395#[allow(clippy::cast_possible_truncation)]
396pub(crate) fn c_trunc(v: f64) -> i32 {
397    if v > -2_147_483_649.0 && v < 2_147_483_648.0 {
398        v as i32
399    } else {
400        i32::MIN
401    }
402}
403
404/// `Image.crop(box)` of `textureRect` up to the C crop (module docs): the
405/// box as C `int`s, or UnityPy's error, in its order.
406pub(crate) fn crop_box(rect: [f64; 4]) -> Result<[i32; 4], SpriteError> {
407    let [x, y, w, h] = rect;
408    let edges = [x, y, x + w, y + h];
409    let [x0, y0, x1, y1] = edges;
410    if x1 < x0 {
411        return Err(SpriteError::CropRightLeft);
412    }
413    if y1 < y0 {
414        return Err(SpriteError::CropLowerUpper);
415    }
416    let mut r = [Int::I(0); 4];
417    for (out, e) in r.iter_mut().zip(edges) {
418        *out = Int::of_f64(py_round(e)?);
419    }
420    bomb_check(r)?;
421    let mut out = [0; 4];
422    for (o, e) in out.iter_mut().zip(r) {
423        *o = c_int_of(e)?;
424    }
425    Ok(out)
426}
427
428/// `_decompression_bomb_check((abs(x1 - x0), abs(y1 - y0)))` of a box of
429/// Python `int`s (`src/PIL/Image.py:3162-3180`), its message naming the
430/// product exactly; past `MAX_IMAGE_PIXELS` alone it only warns.
431pub(crate) fn bomb_check([x0, y0, x1, y1]: [Int; 4]) -> Result<(), SpriteError> {
432    let pixels = x1.abs_diff(x0).mul(&y1.abs_diff(y0));
433    if pixels.above(MAX_CROP_PIXELS) {
434        return Err(SpriteError::DecompressionBomb {
435            pixels: pixels.decimal(),
436        });
437    }
438    Ok(())
439}
440
441/// The size `ImagingCrop` gives a box of C `int`s: its sides in `int`
442/// (GCC's wrapping subtraction), a negative one 0.
443pub(crate) fn crop_size([x0, y0, x1, y1]: [i32; 4]) -> (u32, u32) {
444    let side = |a: i32, b: i32| u32::try_from(b.wrapping_sub(a).max(0)).unwrap_or(0);
445    (side(x0, x1), side(y0, y1))
446}
447
448/// `ImagingCrop` of `sheet` by `box` (module docs): its sides as
449/// [`crop_size`] gives them; what lies outside the sheet zero.
450pub(crate) fn crop(
451    sheet: &Sheet<'_>,
452    crop_box: [i32; 4],
453    meter: &Arc<Meter>,
454) -> Result<Canvas, SpriteError> {
455    let [x0, y0, ..] = crop_box;
456    let (w, h) = crop_size(crop_box);
457    let mut out = Canvas::new(sheet.mode(), w, h, meter)?;
458    // The rows copied, an empty crop's included (its bytes were counted as
459    // it was made).
460    meter.count_decode(u64::from(h))?;
461    if w == 0 || h == 0 {
462        return Ok(out);
463    }
464    super::contained(|| {
465        for y in 0..h {
466            for x in 0..w {
467                if let Some(p) =
468                    sheet.pixel(i64::from(x0) + i64::from(x), i64::from(y0) + i64::from(y))
469                {
470                    out.get_mut(x, y).copy_from_slice(p);
471                }
472            }
473        }
474    })?;
475    Ok(out)
476}
477
478#[cfg(test)]
479mod tests {
480    use super::*;
481    use crate::{Format, decode};
482
483    /// A BC4 texture decodes to `L`, which the renderer is not verified on
484    /// (`Sheet::new`): beside an alpha texture it is `Image.merge`'s "wrong
485    /// number of bands", before the sizes are compared; alone, or as an
486    /// alpha texture of the texture's size, unityrs's own refusal; a size
487    /// mismatch is still `Image.merge`'s. Nothing is charged, and no
488    /// sheet is made.
489    #[test]
490    fn an_l_sheet_or_alpha_is_refused_before_anything_is_drawn() {
491        let meter = Meter::unlimited();
492        let l = decode(Format::Bc4, &[0; 8], 4, 4, &meter).unwrap();
493        let wide_l = decode(Format::Bc4, &[0; 16], 8, 4, &meter).unwrap();
494        let rgba = decode(Format::Rgba32, &[0; 64], 4, 4, &meter).unwrap();
495        let wide = decode(Format::Rgba32, &[0; 128], 8, 4, &meter).unwrap();
496        let rgb = decode(Format::Rgb24, &[0; 48], 4, 4, &meter).unwrap();
497        assert_eq!(l.mode(), Mode::L);
498        let held = meter.used();
499        let refused = |texture: &Image, alpha: Option<&Image>| {
500            Sheet::new(texture, alpha, &meter)
501                .map(|_| ())
502                .expect_err("refused")
503        };
504        // The alpha path: UnityPy's errors, the band count first.
505        for alpha in [&rgba, &rgb, &l, &wide] {
506            let e = refused(&l, Some(alpha));
507            assert!(matches!(e, SpriteError::AlphaBandCount), "{e:?}");
508            assert_eq!(
509                e.python(),
510                Some(("ValueError", "wrong number of bands".to_owned()))
511            );
512        }
513        let e = refused(&rgba, Some(&wide_l));
514        assert!(matches!(e, SpriteError::AlphaSizeMismatch), "{e:?}");
515        // An `L` alpha texture of the texture's size, and an `L` texture
516        // alone: unityrs's refusal, no exception of UnityPy's.
517        for e in [
518            refused(&rgba, Some(&l)),
519            refused(&rgb, Some(&l)),
520            refused(&l, None),
521        ] {
522            assert!(
523                matches!(e, SpriteError::UnverifiedMode { mode: "L" }),
524                "{e:?}"
525            );
526            assert_eq!(e.python(), None);
527        }
528        assert_eq!(meter.used(), held);
529        // The verified modes still make sheets.
530        assert!(Sheet::new(&rgb, None, &meter).is_ok());
531        assert!(Sheet::new(&rgb, Some(&rgba), &meter).is_ok());
532    }
533
534    /// The renderer's bounds (`PARITY.md` section 19.3): Pillow's width cap
535    /// first, whatever the height, then the pixel bound, before anything
536    /// is charged.
537    #[test]
538    fn a_canvas_past_the_bounds_is_refused_before_it_is_charged() {
539        let meter = Meter::unlimited();
540        let wide = Canvas::new(Mode::Rgba, WIDTH_CAP + 1, 0, &meter);
541        assert!(matches!(wide, Err(SpriteError::ImageTooWide)));
542        assert_eq!(
543            wide.err().and_then(|e| e.python()),
544            Some(("MemoryError", String::new()))
545        );
546        assert!(Canvas::new(Mode::Rgba, WIDTH_CAP, 0, &meter).is_ok());
547        let big = Canvas::new(Mode::Rgb, 16_385, 16_384, &meter);
548        assert!(matches!(big, Err(SpriteError::TooLarge { what: "canvas" })));
549        assert_eq!(meter.used(), 0);
550    }
551
552    #[test]
553    fn a_box_edge_is_taken_as_pyarg_s_i_takes_it() {
554        assert_eq!(c_int(-3.0).ok(), Some(-3));
555        let err = |v: f64| c_int(v).err().and_then(|e| e.python());
556        let over = |m: &str| Some(("OverflowError", m.to_owned()));
557        assert_eq!(
558            err(2_147_483_648.0),
559            over("signed integer is greater than maximum")
560        );
561        assert_eq!(
562            err(-2_147_483_649.0),
563            over("signed integer is less than minimum")
564        );
565        assert_eq!(
566            err(9.223_372_036_854_776e18),
567            over("Python int too large to convert to C long")
568        );
569        assert_eq!(
570            err(-9.223_372_036_854_776e18),
571            over("signed integer is less than minimum")
572        );
573        assert_eq!(
574            err(1e300),
575            over("Python int too large to convert to C long")
576        );
577    }
578}