rustpython-stdlib 0.6.0

RustPython standard libraries in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
// cspell:ignore siftup siftdown mhalf
pub(crate) use _heapq::module_def;

#[pymodule]
mod _heapq {

    use crate::vm::{
        Py, PyObjectRef, PyResult, VirtualMachine,
        builtins::{PyList, PyListRef},
        types::PyComparisonOp,
    };

    /// [CPython's siftdown](https://github.com/python/cpython/blob/v3.14.5/Modules/_heapqmodule.c#L25-L68)
    fn siftdown(
        heap: &Py<PyList>,
        startpos: usize,
        mut pos: usize,
        vm: &VirtualMachine,
    ) -> PyResult<()> {
        let size = heap.__len__();

        let newitem = match heap.borrow_vec().get(pos) {
            Some(v) => v.clone(),
            None => return Err(vm.new_index_error("index out of range")),
        };

        // Follow the path to the root, moving parents down until finding
        // a place newitem fits.
        while pos > startpos {
            let parentpos = (pos - 1) >> 1;
            let parent = {
                let vec = heap.borrow_vec();
                vec[parentpos].clone()
            };

            let cmp = newitem.rich_compare_bool(&parent, PyComparisonOp::Lt, vm)?;

            if size != heap.__len__() {
                return Err(vm.new_runtime_error("list changed size during iteration"));
            }

            if !cmp {
                break;
            }

            {
                let mut vec = heap.borrow_vec_mut();
                vec.swap(pos, parentpos);
            }

            pos = parentpos;
        }

        Ok(())
    }

    /// [CPython's siftup](https://github.com/python/cpython/blob/v3.14.5/Modules/_heapqmodule.c#L70-L118)
    fn siftup(heap: &Py<PyList>, mut pos: usize, vm: &VirtualMachine) -> PyResult<()> {
        let endpos = heap.__len__();
        let startpos = pos;

        if pos >= endpos {
            return Err(vm.new_index_error("index out of range"));
        };

        let limit = endpos >> 1; // smallest pos that has no child

        // Bubble up the smaller child until hitting a leaf.
        while pos < limit {
            // Set childpos to index of smaller child.
            let mut childpos = 2 * pos + 1; // leftmost child position

            if childpos + 1 < endpos {
                let (a, b) = {
                    let vec = heap.borrow_vec();
                    (vec[childpos].clone(), vec[childpos + 1].clone())
                };

                let cmp = a.rich_compare_bool(&b, PyComparisonOp::Lt, vm)?;

                if endpos != heap.__len__() {
                    return Err(vm.new_runtime_error("list changed size during iteration"));
                }

                if !cmp {
                    childpos += 1;
                }
            }

            {
                // Move the smaller child up
                let mut vec = heap.borrow_vec_mut();
                vec.swap(pos, childpos);
            }

            pos = childpos;
        }

        // Bubble it up to its final resting place (by sifting its parents down)
        siftdown(heap, startpos, pos, vm)
    }

    /// configurable `sift_func` for doing heappush operation.
    ///
    /// A generic implementation of:
    /// - [CPython's _heapq_heappush_impl](https://github.com/python/cpython/blob/v3.14.5/Modules/_heapqmodule.c#L131-L150)
    /// - [CPython's _heapq_heappush_max_impl](https://github.com/python/cpython/blob/v3.14.5/Modules/_heapqmodule.c#L512-L532)
    fn heappush_internal<F>(
        heap: &Py<PyList>,
        item: PyObjectRef,
        siftdown_func: F,
        vm: &VirtualMachine,
    ) -> PyResult<()>
    where
        F: Fn(&Py<PyList>, usize, usize, &VirtualMachine) -> PyResult<()>,
    {
        {
            let mut vec = heap.borrow_vec_mut();
            vec.push(item);
        }

        let size = heap.__len__();

        siftdown_func(heap, 0, size - 1, vm)
    }

    #[pyfunction]
    fn heappush(heap: PyListRef, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
        heappush_internal(&heap, item, siftdown, vm)
    }

    /// [CPython's heappop_internal](https://github.com/python/cpython/blob/v3.14.5/Modules/_heapqmodule.c#L152-L183)
    fn heappop_internal<F>(
        heap: &Py<PyList>,
        siftup_func: F,
        vm: &VirtualMachine,
    ) -> PyResult<PyObjectRef>
    where
        F: Fn(&Py<PyList>, usize, &VirtualMachine) -> PyResult<()>,
    {
        let Some(lastelt) = heap.borrow_vec_mut().pop() else {
            return Err(vm.new_index_error("index out of range"));
        };

        if heap.borrow_vec().is_empty() {
            return Ok(lastelt);
        };

        let returnitem = {
            let mut vec = heap.borrow_vec_mut();
            let root = vec[0].clone();
            vec[0] = lastelt;
            root
        };

        siftup_func(heap, 0, vm)?;
        Ok(returnitem)
    }

    #[pyfunction]
    fn heappop(heap: PyListRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
        heappop_internal(&heap, siftup, vm)
    }

    /// [CPython's heapreplace_internal](https://github.com/python/cpython/blob/v3.14.5/Modules/_heapqmodule.c#L202-L220)
    fn heapreplace_internal<F>(
        heap: &Py<PyList>,
        item: PyObjectRef,
        siftup_func: F,
        vm: &VirtualMachine,
    ) -> PyResult<PyObjectRef>
    where
        F: Fn(&Py<PyList>, usize, &VirtualMachine) -> PyResult<()>,
    {
        let returnitem = {
            let mut vec = heap.borrow_vec_mut();
            let root = match vec.first() {
                Some(v) => v.clone(),
                None => return Err(vm.new_index_error("index out of range")),
            };

            vec[0] = item;
            root
        };

        siftup_func(heap, 0, vm)?;
        Ok(returnitem)
    }

    #[pyfunction]
    fn heapreplace(
        heap: PyListRef,
        item: PyObjectRef,
        vm: &VirtualMachine,
    ) -> PyResult<PyObjectRef> {
        heapreplace_internal(&heap, item, siftup, vm)
    }

    #[pyfunction]
    fn heappushpop(
        heap: PyListRef,
        item: PyObjectRef,
        vm: &VirtualMachine,
    ) -> PyResult<PyObjectRef> {
        let top = {
            let vec = heap.borrow_vec();
            match vec.first() {
                Some(v) => v.clone(),
                None => return Ok(item),
            }
        };

        let cmp = top.rich_compare_bool(&item, PyComparisonOp::Lt, vm)?;
        if !cmp {
            return Ok(item);
        }

        let returnitem = {
            let mut vec = heap.borrow_vec_mut();
            let root = match vec.first() {
                Some(v) => v.clone(),
                None => return Err(vm.new_index_error("index out of range")),
            };

            vec[0] = item;
            root
        };

        siftup(&heap, 0, vm)?;
        Ok(returnitem)
    }

    /// [CPython's keep_top_bit](https://github.com/python/cpython/blob/v3.14.5/Modules/_heapqmodule.c#L299-L309)
    const fn keep_top_bit(mut n: usize) -> usize {
        let mut i = 0;

        while n > 1 {
            n >>= 1;
            i += 1;
        }

        n << i
    }

    /// [CPython's cache_friendly_heapify](https://github.com/python/cpython/blob/v3.14.5/Modules/_heapqmodule.c#L311-L362)
    fn cache_friendly_heapify<F>(
        heap: &Py<PyList>,
        siftup_func: F,
        vm: &VirtualMachine,
    ) -> PyResult<()>
    where
        F: Fn(&Py<PyList>, usize, &VirtualMachine) -> PyResult<()>,
    {
        let m = heap.__len__() >> 1; // index of first childless node
        let leftmost = keep_top_bit(m + 1) - 1; // leftmost node in row of m 
        let mhalf = m >> 1; // parent of first childless node

        for i in (mhalf..leftmost).rev() {
            let mut j = i;

            loop {
                siftup_func(heap, j, vm)?;

                if j & 1 == 0 {
                    break;
                }

                j >>= 1;
            }
        }

        for i in (leftmost..m).rev() {
            let mut j = i;

            loop {
                siftup_func(heap, j, vm)?;

                if j & 1 == 0 {
                    break;
                }

                j >>= 1;
            }
        }

        Ok(())
    }

    /// [CPython's heapify_internal](https://github.com/python/cpython/blob/v3.14.5/Modules/_heapqmodule.c#L364-L388)
    fn heapify_internal<F>(heap: &Py<PyList>, siftup_func: F, vm: &VirtualMachine) -> PyResult<()>
    where
        F: Fn(&Py<PyList>, usize, &VirtualMachine) -> PyResult<()>,
    {
        let n = heap.__len__();

        if n > 2500 {
            return cache_friendly_heapify(heap, siftup_func, vm);
        }

        for i in (0..(n >> 1)).rev() {
            siftup_func(heap, i, vm)?;
        }

        Ok(())
    }

    #[pyfunction]
    fn heapify(heap: PyListRef, vm: &VirtualMachine) -> PyResult<()> {
        heapify_internal(&heap, siftup, vm)
    }

    /// [CPython's siftdown_max](https://github.com/python/cpython/blob/v3.14.5/Modules/_heapqmodule.c#L407-L449)
    fn siftdown_max(
        heap: &Py<PyList>,
        startpos: usize,
        mut pos: usize,
        vm: &VirtualMachine,
    ) -> PyResult<()> {
        let size = heap.__len__();

        let newitem = match heap.borrow_vec().get(pos) {
            Some(v) => v.clone(),
            None => return Err(vm.new_index_error("index out of range")),
        };

        // Follow the path to the root, moving parents down until finding
        // a place newitem fits.
        while pos > startpos {
            let parentpos = (pos - 1) >> 1;
            let parent = {
                let vec = heap.borrow_vec();
                vec[parentpos].clone()
            };

            let cmp = parent.rich_compare_bool(&newitem, PyComparisonOp::Lt, vm)?;

            if size != heap.__len__() {
                return Err(vm.new_runtime_error("list changed size during iteration"));
            }

            if !cmp {
                break;
            }

            {
                let mut vec = heap.borrow_vec_mut();
                vec.swap(pos, parentpos);
            }

            pos = parentpos;
        }

        Ok(())
    }

    /// [CPython's siftup_max](https://github.com/python/cpython/blob/v3.14.5/Modules/_heapqmodule.c#L451-L499)
    fn siftup_max(heap: &Py<PyList>, mut pos: usize, vm: &VirtualMachine) -> PyResult<()> {
        let endpos = heap.__len__();
        let startpos = pos;

        if pos >= endpos {
            return Err(vm.new_index_error("index out of range"));
        };

        let limit = endpos >> 1; // smallest pos that has no child

        // Bubble up the larger child until hitting a leaf.
        while pos < limit {
            // Set childpos to index of larger child.
            let mut childpos = 2 * pos + 1; // leftmost child position

            if childpos + 1 < endpos {
                let (a, b) = {
                    let vec = heap.borrow_vec();
                    (vec[childpos + 1].clone(), vec[childpos].clone())
                };

                let cmp = a.rich_compare_bool(&b, PyComparisonOp::Lt, vm)?;

                if endpos != heap.__len__() {
                    return Err(vm.new_runtime_error("list changed size during iteration"));
                }

                if !cmp {
                    childpos += 1;
                }
            }

            {
                // Move the larger child up
                let mut vec = heap.borrow_vec_mut();
                vec.swap(pos, childpos);
            }

            pos = childpos;
        }

        // Bubble it up to its final resting place (by sifting its parents down)
        siftdown_max(heap, startpos, pos, vm)
    }

    #[pyfunction]
    fn heappush_max(heap: PyListRef, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
        heappush_internal(&heap, item, siftdown_max, vm)
    }

    #[pyfunction]
    fn heappop_max(heap: PyListRef, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
        heappop_internal(&heap, siftup_max, vm)
    }

    #[pyfunction]
    fn heapreplace_max(
        heap: PyListRef,
        item: PyObjectRef,
        vm: &VirtualMachine,
    ) -> PyResult<PyObjectRef> {
        heapreplace_internal(&heap, item, siftup_max, vm)
    }

    #[pyfunction]
    fn heapify_max(heap: PyListRef, vm: &VirtualMachine) -> PyResult<()> {
        heapify_internal(&heap, siftup_max, vm)
    }

    #[pyfunction]
    fn heappushpop_max(
        heap: PyListRef,
        item: PyObjectRef,
        vm: &VirtualMachine,
    ) -> PyResult<PyObjectRef> {
        let top = {
            let vec = heap.borrow_vec();
            match vec.first() {
                Some(v) => v.clone(),
                None => return Ok(item),
            }
        };

        let cmp = item.rich_compare_bool(&top, PyComparisonOp::Lt, vm)?;
        if !cmp {
            return Ok(item);
        }

        let returnitem = {
            let mut vec = heap.borrow_vec_mut();
            let root = match vec.first() {
                Some(v) => v.clone(),
                None => return Err(vm.new_index_error("index out of range")),
            };

            vec[0] = item;
            root
        };

        siftup_max(&heap, 0, vm)?;
        Ok(returnitem)
    }
}