|
1 | 1 | use crossbeam_utils::atomic::AtomicCell; |
| 2 | +use num_traits::ToPrimitive; |
2 | 3 | use std::fmt; |
3 | 4 |
|
4 | | -use super::objiter; |
5 | 5 | use super::objsequence::get_item; |
6 | 6 | use super::objtype::PyTypeRef; |
7 | | -use crate::function::OptionalArg; |
| 7 | +use super::{objint::PyIntRef, objiter}; |
8 | 8 | use crate::pyobject::{ |
9 | 9 | self, BorrowValue, Either, IdProtocol, IntoPyObject, PyArithmaticValue, PyClassImpl, |
10 | | - PyComparisonValue, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol, |
| 10 | + PyComparisonValue, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TryFromObject, |
| 11 | + TypeProtocol, |
11 | 12 | }; |
12 | 13 | use crate::sequence::{self, SimpleSeq}; |
13 | 14 | use crate::slots::{Comparable, Hashable, PyComparisonOp}; |
14 | 15 | use crate::vm::{ReprGuard, VirtualMachine}; |
| 16 | +use crate::{bytesinner::PyBytesInner, function::OptionalArg}; |
15 | 17 | use rustpython_common::hash::PyHash; |
16 | 18 |
|
17 | 19 | /// tuple() -> empty tuple |
@@ -66,6 +68,25 @@ impl PyTuple { |
66 | 68 | pub(crate) fn fast_getitem(&self, idx: usize) -> PyObjectRef { |
67 | 69 | self.elements[idx].clone() |
68 | 70 | } |
| 71 | + |
| 72 | + // TODO: more generic way to do so |
| 73 | + pub(crate) fn to_bytes_inner(&self, vm: &VirtualMachine) -> PyResult<PyBytesInner> { |
| 74 | + let mut elements = Vec::<u8>::with_capacity(self.borrow_value().len()); |
| 75 | + for elem in self.borrow_value().iter() { |
| 76 | + let py_int = PyIntRef::try_from_object(vm, elem.clone()).map_err(|_| { |
| 77 | + vm.new_type_error(format!( |
| 78 | + "'{}' object cannot be interpreted as an integer", |
| 79 | + elem.class().name |
| 80 | + )) |
| 81 | + })?; |
| 82 | + let result = py_int |
| 83 | + .borrow_value() |
| 84 | + .to_u8() |
| 85 | + .ok_or_else(|| vm.new_value_error("bytes must be in range (0, 256)".to_owned()))?; |
| 86 | + elements.push(result); |
| 87 | + } |
| 88 | + Ok(elements.into()) |
| 89 | + } |
69 | 90 | } |
70 | 91 |
|
71 | 92 | pub type PyTupleRef = PyRef<PyTuple>; |
|
0 commit comments