Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit9c3d97b

Browse files
committed
bytesinner from pytuple
1 parentd560d4b commit9c3d97b

File tree

6 files changed

+80
-27
lines changed

6 files changed

+80
-27
lines changed

‎Lib/test/test_memoryview.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ def setitem(value):
7171
m=None
7272
self.assertEqual(sys.getrefcount(b),oldrefcount)
7373

74+
# TODO: RUSTPYTHON
75+
@unittest.expectedFailure
7476
deftest_setitem_writable(self):
7577
ifnotself.rw_type:
7678
self.skipTest("no writable type to test")
@@ -112,13 +114,11 @@ def setitem(key, value):
112114
self.assertRaises(TypeError,setitem,"a",b"a")
113115
# Not implemented: multidimensional slices
114116
slices= (slice(0,1,1),slice(0,1,2))
115-
# TODO: RUSTPYTHON
116-
# self.assertRaises(NotImplementedError, setitem, slices, b"a")
117+
self.assertRaises(NotImplementedError,setitem,slices,b"a")
117118
# Trying to resize the memory object
118119
exc=ValueErrorifm.format=='c'elseTypeError
119-
# TODO: RUSTPYTHON
120-
# self.assertRaises(exc, setitem, 0, b"")
121-
# self.assertRaises(exc, setitem, 0, b"ab")
120+
self.assertRaises(exc,setitem,0,b"")
121+
self.assertRaises(exc,setitem,0,b"ab")
122122
self.assertRaises(ValueError,setitem,slice(1,1),b"a")
123123
self.assertRaises(ValueError,setitem,slice(0,2),b"a")
124124

@@ -150,6 +150,8 @@ def test_tolist(self):
150150
l=m.tolist()
151151
self.assertEqual(l,list(b"abcdef"))
152152

153+
# TODO: RUSTPYTHON
154+
@unittest.expectedFailure
153155
deftest_compare(self):
154156
# memoryviews can compare for equality with other objects
155157
# having the buffer interface.
@@ -174,12 +176,11 @@ def test_compare(self):
174176
self.assertTrue("abcdef"!=m)
175177

176178
# Unordered comparisons
177-
# TODO: RUSTPYTHON
178-
# for c in (m, b"abcdef"):
179-
# self.assertRaises(TypeError, lambda: m < c)
180-
# self.assertRaises(TypeError, lambda: c <= m)
181-
# self.assertRaises(TypeError, lambda: m >= c)
182-
# self.assertRaises(TypeError, lambda: c > m)
179+
forcin (m,b"abcdef"):
180+
self.assertRaises(TypeError,lambda:m<c)
181+
self.assertRaises(TypeError,lambda:c<=m)
182+
self.assertRaises(TypeError,lambda:m>=c)
183+
self.assertRaises(TypeError,lambda:c>m)
183184

184185
defcheck_attributes_with_type(self,tp):
185186
m=self._view(tp(self._source))
@@ -272,12 +273,11 @@ def _check_released(self, m, tp):
272273
withcheck:m.itemsize
273274
withcheck:m.ndim
274275
withcheck:m.readonly
275-
# TODO: RUSTPYTHON
276-
# with check: m.shape
277-
# with check: m.strides
278-
# with check:
279-
# with m:
280-
# pass
276+
withcheck:m.shape
277+
withcheck:m.strides
278+
withcheck:
279+
withm:
280+
pass
281281
# str() and repr() still function
282282
self.assertIn("released memory",str(m))
283283
self.assertIn("released memory",repr(m))

‎extra_tests/snippets/memoryview.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
a=memoryview(obj)
77
asserta.obj==obj
88

9-
#assert a[2:3] == b"c"
9+
asserta[2:3]==b"c"
1010

1111
asserthash(obj)==hash(a)
1212

‎vm/src/bytesinner.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ use itertools::Itertools;
33
use num_bigint::BigInt;
44
use num_traits::ToPrimitive;
55

6-
usecrate::anystr::{self,AnyStr,AnyStrContainer,AnyStrWrapper};
76
usecrate::byteslike::try_bytes_like;
87
usecrate::function::{OptionalArg,OptionalOption};
98
usecrate::obj::objbytearray::PyByteArray;
@@ -23,6 +22,10 @@ use crate::pyobject::{
2322
};
2423
usecrate::slots::PyComparisonOp;
2524
usecrate::vm::VirtualMachine;
25+
usecrate::{
26+
anystr::{self,AnyStr,AnyStrContainer,AnyStrWrapper},
27+
obj::objtuple::PyTuple,
28+
};
2629
use rustpython_common::hash;
2730

2831
#[derive(Debug,Default,Clone)]
@@ -43,8 +46,9 @@ impl TryFromObject for PyBytesInner {
4346
}
4447

4548
match_class!(match obj{
49+
// TODO: generic way from &[PyObjectRef]
4650
l @PyList => l.to_byte_inner(vm),
47-
// TODO: PyTyple
51+
t @PyTuple => t.to_bytes_inner(vm),
4852
obj =>{
4953
let iter = vm.get_method_or_type_error(obj.clone(),"__iter__", ||{
5054
format!("a bytes-like object is required, not {}", obj.class())

‎vm/src/obj/objlist.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ impl PyList {
7474
self.elements.write()
7575
}
7676

77+
// TODO: more generic way to do so
7778
pub(crate)fnto_byte_inner(&self,vm:&VirtualMachine) ->PyResult<bytesinner::PyBytesInner>{
7879
letmut elements =Vec::<u8>::with_capacity(self.borrow_value().len());
7980
for eleminself.borrow_value().iter(){

‎vm/src/obj/objmemory.rs

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ use crate::obj::objslice::PySliceRef;
99
usecrate::obj::objstr::PyStr;
1010
usecrate::obj::objtype::PyTypeRef;
1111
usecrate::pyobject::{
12-
IdProtocol,PyClassImpl,PyComparisonValue,PyContext,PyObjectRef,PyRef,PyResult,
13-
PyThreadingConstraint,PyValue,TypeProtocol,
12+
IdProtocol,IntoPyObject,PyClassImpl,PyComparisonValue,PyContext,PyObjectRef,PyRef,
13+
PyResult,PyThreadingConstraint,PyValue,TypeProtocol,
1414
};
1515
usecrate::slots::{BufferProtocol,Comparable,Hashable,PyComparisonOp};
1616
usecrate::stdlib::pystruct::_struct::FormatSpec;
@@ -85,9 +85,11 @@ pub struct BufferOptions {
8585
publen:usize,
8686
pubitemsize:usize,
8787
pubcontiguous:bool,
88+
pubformat:String,
8889
// TODO: support multiple dimension array
8990
pubndim:usize,
90-
pubformat:String,
91+
pubshape:Vec<usize>,
92+
pubstrides:Vec<isize>,
9193
}
9294

9395
implDefaultforBufferOptions{
@@ -97,8 +99,10 @@ impl Default for BufferOptions {
9799
len:0,
98100
itemsize:1,
99101
contiguous:true,
100-
ndim:1,
101102
format:"B".to_owned(),
103+
ndim:1,
104+
shape:Vec::new(),
105+
strides:Vec::new(),
102106
}
103107
}
104108
}
@@ -209,12 +213,35 @@ impl PyMemoryView {
209213
self.try_not_released(vm).map(|_|self.options.ndim)
210214
}
211215

216+
// TODO
217+
#[pyproperty]
218+
fnshape(&self,vm:&VirtualMachine) ->PyResult<PyObjectRef>{
219+
self.try_not_released(vm)
220+
.map(|_|(self.options.len,).into_pyobject(vm))
221+
}
222+
223+
// TODO
224+
#[pyproperty]
225+
fnstrides(&self,vm:&VirtualMachine) ->PyResult<PyObjectRef>{
226+
self.try_not_released(vm).map(|_|(0,).into_pyobject(vm))
227+
}
228+
212229
#[pyproperty]
213230
fnformat(&self,vm:&VirtualMachine) ->PyResult<PyStr>{
214231
self.try_not_released(vm)
215232
.map(|_|PyStr::from(&self.options.format))
216233
}
217234

235+
#[pymethod(magic)]
236+
fnenter(zelf:PyRef<Self>,vm:&VirtualMachine) ->PyResult<PyRef<Self>>{
237+
zelf.try_not_released(vm).map(|_| zelf)
238+
}
239+
240+
#[pymethod(magic)]
241+
fnexit(&self){
242+
self.release();
243+
}
244+
218245
// translate the slice index to memory index
219246
fnget_pos(&self,i:isize) ->Option<usize>{
220247
let len =self.options.len;

‎vm/src/obj/objtuple.rs

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
11
use crossbeam_utils::atomic::AtomicCell;
2+
use num_traits::ToPrimitive;
23
use std::fmt;
34

4-
usesuper::objiter;
55
usesuper::objsequence::get_item;
66
usesuper::objtype::PyTypeRef;
7-
usecrate::function::OptionalArg;
7+
usesuper::{objint::PyIntRef, objiter};
88
usecrate::pyobject::{
99
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,
1112
};
1213
usecrate::sequence::{self,SimpleSeq};
1314
usecrate::slots::{Comparable,Hashable,PyComparisonOp};
1415
usecrate::vm::{ReprGuard,VirtualMachine};
16+
usecrate::{bytesinner::PyBytesInner, function::OptionalArg};
1517
use rustpython_common::hash::PyHash;
1618

1719
/// tuple() -> empty tuple
@@ -66,6 +68,25 @@ impl PyTuple {
6668
pub(crate)fnfast_getitem(&self,idx:usize) ->PyObjectRef{
6769
self.elements[idx].clone()
6870
}
71+
72+
// TODO: more generic way to do so
73+
pub(crate)fnto_bytes_inner(&self,vm:&VirtualMachine) ->PyResult<PyBytesInner>{
74+
letmut elements =Vec::<u8>::with_capacity(self.borrow_value().len());
75+
for eleminself.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+
}
6990
}
7091

7192
pubtypePyTupleRef =PyRef<PyTuple>;

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp