Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 #![deny(missing_docs)]
2 #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))]
3 use pyo3::prelude::*;
4
5 use pyo3::exceptions::{PyAttributeError, PyValueError};
6 use std::io::{Read, Seek, Write};
7 #[cfg(any(unix, target_os = "wasi"))]
8 use std::os::fd::{AsFd, BorrowedFd, RawFd};
9
10 use std::borrow::Cow;
11
12 /// Rust wrapper for a Python file-like object that implements the `io` protocol.
13 #[derive(Debug)]
14 pub struct PyBinaryFile(Py<PyAny>);
15
16 impl<'py> IntoPyObject<'py> for PyBinaryFile {
17 type Target = PyAny;
18
19 type Output = Bound<'py, PyAny>;
20
21 type Error = PyErr;
22
23 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
24 let obj = self.0.clone_ref(py);
25 Ok(obj.into_bound(py))
26 }
27 }
28
29 impl Clone for PyBinaryFile {
30 fn clone(&self) -> Self {
31 Python::attach(|py| PyBinaryFile::from(self.0.clone_ref(py)))
32 }
33 }
34
35 impl Read for PyBinaryFile {
36 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
37 Python::attach(|py| {
38 let bytes = self.0.call_method1(py, "read", (buf.len(),))?;
39 let bytes = bytes
40 .extract::<&[u8]>(py)
41 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;
42 let len = std::cmp::min(buf.len(), bytes.len());
43 buf[..len].copy_from_slice(&bytes[..len]);
44 Ok(len)
45 })
46 }
47 }
48
49 impl Write for PyBinaryFile {
50 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
51 Python::attach(|py| {
52 let bytes = pyo3::types::PyBytes::new(py, buf);
53 self.0.call_method1(py, "write", (bytes,))?;
54 Ok(buf.len())
55 })
56 }
57
58 fn flush(&mut self) -> std::io::Result<()> {
59 Python::attach(|py| {
60 self.0.call_method0(py, "flush")?;
61 Ok(())
62 })
63 }
64 }
65
66 impl Seek for PyBinaryFile {
67 fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
68 Python::attach(|py| {
69 let (whence, offset) = match pos {
70 std::io::SeekFrom::Start(offset) => (0, offset as i64),
71 std::io::SeekFrom::End(offset) => (2, offset),
72 std::io::SeekFrom::Current(offset) => (1, offset),
73 };
74 let pos = self.0.call_method1(py, "seek", (offset, whence))?;
75 let pos = pos.extract::<u64>(py)?;
76 Ok(pos)
77 })
78 }
79 }
80
81 #[cfg(any(unix, target_os = "wasi"))]
82 impl AsFd for PyBinaryFile {
83 fn as_fd(&self) -> BorrowedFd<'_> {
84 Python::attach(|py| {
85 let fd = self.0.call_method0(py, "fileno")?;
86 let fd = fd.extract::<RawFd>(py)?;
87 Ok::<BorrowedFd<'_>, PyErr>(unsafe { BorrowedFd::borrow_raw(fd) })
88 })
89 .unwrap()
90 }
91 }
92
93 impl PyBinaryFile {
94 fn new(file: Py<PyAny>) -> PyResult<Self> {
95 let o = PyBinaryFile(file);
96 o.check_mode('b')?;
97 Ok(o)
98 }
99
100 fn check_mode(&self, expected_mode: char) -> PyResult<()> {
101 Python::attach(|py| {
102 match self.0.getattr(py, "mode") {
103 Ok(mode) => {
104 let mode_str = match mode.extract::<Cow<str>>(py) {
105 Ok(mode_str) => mode_str,
106 Err(_) => {
107 // Assume binary mode if mode attribute is not a string
108 return Ok(());
109 }
110 };
111 if mode_str.contains(expected_mode) {
112 return Ok(());
113 }
114 Err(PyValueError::new_err(format!(
115 "file must be opened in {} mode",
116 expected_mode
117 )))
118 }
119 Err(e) if e.is_instance_of::<PyAttributeError>(py) => {
120 // Assume binary mode if mode attribute is not present
121 Ok(())
122 }
123 Err(e) => Err(e),
124 }
125 })
126 }
127
128 /// Check if the underlying Python file-like object supports seeking.
129 ///
130 /// This method calls the Python `seekable()` method on the underlying object
131 /// to determine if seek operations are supported at runtime.
132 ///
133 /// Note: This must be checked at runtime rather than compile time because:
134 /// - The wrapped Python object is dynamically typed (`Py<PyAny>`)
135 /// - Whether seeking is supported depends on the specific Python object's
136 /// implementation, which cannot be known at compile time
137 /// - Rust's trait system operates on static types, but Python objects have
138 /// runtime capabilities that vary between instances
139 ///
140 /// # Returns
141 ///
142 /// Returns `Ok(true)` if the file supports seeking, `Ok(false)` if not,
143 /// or `Err` if the `seekable()` method call fails.
144 ///
145 /// # Example
146 ///
147 /// ```
148 /// use pyo3::prelude::*;
149 /// use pyo3_filelike::PyBinaryFile;
150 ///
151 /// Python::attach(|py| -> PyResult<()> {
152 /// let io = py.import("io")?;
153 /// let file = io.call_method1("BytesIO", (&b"hello"[..],))?;
154 /// let file = PyBinaryFile::from(file);
155 /// assert_eq!(file.seekable()?, true);
156 /// Ok(())
157 /// }).unwrap();
158 /// ```
159 pub fn seekable(&self) -> PyResult<bool> {
160 Python::attach(|py| {
161 let result = self.0.call_method0(py, "seekable")?;
162 result.extract::<bool>(py)
163 })
164 }
165 }
166
167 impl From<Py<PyAny>> for PyBinaryFile {
168 fn from(obj: Py<PyAny>) -> Self {
169 PyBinaryFile::new(obj).unwrap()
170 }
171 }
172
173 impl From<Bound<'_, PyAny>> for PyBinaryFile {
174 fn from(obj: Bound<'_, PyAny>) -> Self {
175 PyBinaryFile::new(obj.into()).unwrap()
176 }
177 }
178
179 /// Rust wrapper for a Python text file-like object that implements the `io` protocol.
180 ///
181 /// This wrapper is similar to `PyBinaryFile`, but it assumes that the file is text and
182 /// returns the byte representation of the text.
183 ///
184 /// The Python file-like object must have a `read` method that returns either a
185 /// `bytes` object or a `str` object.
186 ///
187 /// Seek operations are not supported on text files, since the equivalent Python
188 /// file-like objects seek by characters, not bytes.
189 #[derive(Debug)]
190 pub struct PyTextFile {
191 inner: Py<PyAny>,
192 buffer: Vec<u8>,
193 }
194
195 impl PyTextFile {
196 /// Create a new `PyTextFile` from a Python file-like object and an encoding.
197 pub fn new(file: Py<PyAny>) -> PyResult<Self> {
198 Ok(PyTextFile {
199 inner: file,
200 buffer: Vec::new(),
201 })
202 }
203
204 /// Check if the underlying Python file-like object supports seeking.
205 ///
206 /// This method calls the Python `seekable()` method on the underlying object
207 /// to determine if seek operations are supported at runtime.
208 ///
209 /// Note: This must be checked at runtime rather than compile time because:
210 /// - The wrapped Python object is dynamically typed (`Py<PyAny>`)
211 /// - Whether seeking is supported depends on the specific Python object's
212 /// implementation, which cannot be known at compile time
213 /// - Rust's trait system operates on static types, but Python objects have
214 /// runtime capabilities that vary between instances
215 ///
216 /// # Returns
217 ///
218 /// Returns `Ok(true)` if the file supports seeking, `Ok(false)` if not,
219 /// or `Err` if the `seekable()` method call fails.
220 ///
221 /// # Example
222 ///
223 /// ```
224 /// use pyo3::prelude::*;
225 /// use pyo3_filelike::PyTextFile;
226 ///
227 /// Python::attach(|py| -> PyResult<()> {
228 /// let io = py.import("io")?;
229 /// let file = io.call_method1("StringIO", ("hello",))?;
230 /// let file = PyTextFile::from(file);
231 /// assert_eq!(file.seekable()?, true);
232 /// Ok(())
233 /// }).unwrap();
234 /// ```
235 pub fn seekable(&self) -> PyResult<bool> {
236 Python::attach(|py| {
237 let result = self.inner.call_method0(py, "seekable")?;
238 result.extract::<bool>(py)
239 })
240 }
241 }
242
243 impl Read for PyTextFile {
244 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
245 Python::attach(|py| {
246 if self.buffer.len() >= buf.len() {
247 buf.copy_from_slice(&self.buffer[..buf.len()]);
248 self.buffer.drain(..buf.len());
249 return Ok(buf.len());
250 }
251 let text = self
252 .inner
253 .call_method1(py, "read", (buf.len() - self.buffer.len(),))?;
254 if let Ok(t) = text.extract::<Cow<str>>(py) {
255 self.buffer.extend_from_slice(t.as_bytes());
256 } else {
257 self.buffer
258 .extend_from_slice(text.extract::<&[u8]>(py).map_err(|e| {
259 std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string())
260 })?);
261 }
262
263 let len = std::cmp::min(self.buffer.len(), buf.len());
264 buf[..len].copy_from_slice(&self.buffer[..len]);
265 self.buffer.drain(..len);
266 Ok(len)
267 })
268 }
269 }
270
271 impl From<Py<PyAny>> for PyTextFile {
272 fn from(obj: Py<PyAny>) -> Self {
273 PyTextFile::new(obj).unwrap()
274 }
275 }
276
277 impl From<Bound<'_, PyAny>> for PyTextFile {
278 fn from(obj: Bound<'_, PyAny>) -> Self {
279 PyTextFile::new(obj.into()).unwrap()
280 }
281 }
282
283 impl<'py> IntoPyObject<'py> for PyTextFile {
284 type Target = PyAny;
285
286 type Output = Bound<'py, PyAny>;
287
288 type Error = PyErr;
289
290 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
291 let obj = self.inner.clone_ref(py);
292 Ok(obj.into_bound(py))
293 }
294 }
295
296 impl Clone for PyTextFile {
297 fn clone(&self) -> Self {
298 Python::attach(|py| PyTextFile::from(self.inner.clone_ref(py)))
299 }
300 }
301
302 #[cfg(test)]
303 mod tests {
304 use super::*;
305 use pyo3::ffi::c_str;
306
307 #[test]
308 fn test_read() {
309 Python::attach(|py| -> PyResult<()> {
310 let io = py.import("io")?;
311 let file = io.call_method1("BytesIO", (&b"hello"[..],))?;
312 let mut file = PyBinaryFile::from(file);
313 let mut buf = [0u8; 5];
314 file.read_exact(&mut buf)?;
315 assert_eq!(&buf, b"hello");
316 Ok(())
317 })
318 .unwrap();
319 }
320
321 #[test]
322 fn test_read_notexact() {
323 Python::attach(|py| -> PyResult<()> {
324 let io = py.import("io")?;
325 let file = io.call_method1("BytesIO", (&b"hello"[..],))?;
326 let mut file = PyBinaryFile::from(file);
327 let mut buf = [0u8; 10];
328 let n = file.read(&mut buf)?;
329 assert_eq!(n, 5);
330 assert_eq!(&buf[..n], b"hello");
331 Ok(())
332 })
333 .unwrap();
334 }
335
336 #[test]
337 fn test_read_eof() {
338 Python::attach(|py| -> PyResult<()> {
339 let io = py.import("io")?;
340 let file = io.call_method1("BytesIO", (&b"hello"[..],))?;
341 let mut file = PyBinaryFile::from(file);
342 let mut buf = [0u8; 6];
343 let err = file.read_exact(&mut buf).unwrap_err();
344 assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
345 Ok(())
346 })
347 .unwrap();
348 }
349
350 #[test]
351 fn test_read_to_end() {
352 Python::attach(|py| -> PyResult<()> {
353 let io = py.import("io")?;
354 let file = io.call_method1("BytesIO", (&b"hello"[..],))?;
355 let mut file = PyBinaryFile::from(file);
356 let mut buf = Vec::new();
357 file.read_to_end(&mut buf)?;
358 assert_eq!(&buf, b"hello");
359 Ok(())
360 })
361 .unwrap();
362 }
363
364 #[test]
365 fn test_write() {
366 Python::attach(|py| {
367 let io = py.import("io")?;
368 let file = io.call_method1("BytesIO", (&b""[..],))?;
369 let mut file = PyBinaryFile::from(file);
370 file.write_all(b"hello ")?;
371 file.write_all(b"world")?;
372 assert_eq!(
373 file.0.call_method0(py, "getvalue")?.extract::<&[u8]>(py)?,
374 b"hello world"
375 );
376 Ok::<(), PyErr>(())
377 })
378 .unwrap();
379 }
380
381 #[test]
382 fn test_seek() {
383 Python::attach(|py| {
384 let io = py.import("io")?;
385 let file = io.call_method1("BytesIO", (&b"hello"[..],))?;
386 let mut file = PyBinaryFile::from(file);
387 file.seek(std::io::SeekFrom::Start(1))?;
388 let mut buf = [0u8; 4];
389 file.read_exact(&mut buf)?;
390 assert_eq!(&buf, b"ello");
391 Ok::<(), PyErr>(())
392 })
393 .unwrap();
394 }
395
396 #[test]
397 fn test_flush() {
398 Python::attach(|py| {
399 let io = py.import("io")?;
400 let file = io.call_method1("BytesIO", (&b""[..],))?;
401 let mut file = PyBinaryFile::from(file);
402 file.write_all(b"hello")?;
403 file.flush()?;
404 assert_eq!(
405 file.0.call_method0(py, "getvalue")?.extract::<&[u8]>(py)?,
406 b"hello"
407 );
408 Ok::<(), PyErr>(())
409 })
410 .unwrap();
411 }
412
413 #[test]
414 fn test_read_text() {
415 Python::attach(|py| -> PyResult<()> {
416 let io = py.import("io")?;
417 let file = io.call_method1("StringIO", ("hello world",))?;
418 let mut file = PyTextFile::from(file);
419 let mut buf = [0u8; 5];
420 file.read_exact(&mut buf)?;
421 assert_eq!(&buf, b"hello");
422 file.read_exact(&mut buf)?;
423 assert_eq!(&buf, b" worl");
424 let mut buf = Vec::new();
425 file.read_to_end(&mut buf).unwrap();
426 assert_eq!(&buf, b"d");
427 Ok(())
428 })
429 .unwrap();
430 }
431
432 #[test]
433 fn test_read_text_unicode() {
434 // read halfway through a unicode character
435 let io = Python::attach(|py| -> PyResult<Py<PyAny>> {
436 let io = py.import("io")?;
437 let file = io.call_method1("StringIO", ("hello \u{1f600} world",))?;
438 Ok(file.into())
439 })
440 .unwrap();
441
442 let mut file = PyTextFile::from(io);
443 let mut buf = [0u8; 7];
444 file.read_exact(&mut buf).unwrap();
445 assert_eq!(&buf, b"hello \xf0");
446
447 let mut buf = [0u8; 1];
448 file.read_exact(&mut buf).unwrap();
449 assert_eq!(&buf, b"\x9f");
450 }
451
452 #[test]
453 fn test_seekable_binary() {
454 Python::attach(|py| -> PyResult<()> {
455 let io = py.import("io")?;
456 let file = io.call_method1("BytesIO", (&b"hello"[..],))?;
457 let file = PyBinaryFile::from(file);
458 assert_eq!(file.seekable()?, true);
459 Ok(())
460 })
461 .unwrap();
462 }
463
464 #[test]
465 fn test_seekable_text() {
466 Python::attach(|py| -> PyResult<()> {
467 let io = py.import("io")?;
468 let file = io.call_method1("StringIO", ("hello",))?;
469 let file = PyTextFile::from(file);
470 assert_eq!(file.seekable()?, true);
471 Ok(())
472 })
473 .unwrap();
474 }
475
476 #[test]
477 fn test_non_seekable_binary() {
478 Python::attach(|py| -> PyResult<()> {
479 // Create a custom non-seekable file-like object
480 let locals = pyo3::types::PyDict::new(py);
481 py.run(
482 c_str!(
483 r#"class NonSeekableFile:
484 def __init__(self):
485 self.data = b"hello"
486 self.pos = 0
487
488 def read(self, n=-1):
489 if n == -1:
490 result = self.data[self.pos:]
491 self.pos = len(self.data)
492 else:
493 result = self.data[self.pos:self.pos + n]
494 self.pos += len(result)
495 return result
496
497 def write(self, data):
498 return len(data)
499
500 def flush(self):
501 pass
502
503 def seekable(self):
504 return False
505
506 @property
507 def mode(self):
508 return 'rb'
509
510 file = NonSeekableFile()"#
511 ),
512 None,
513 Some(&locals),
514 )?;
515 let file = locals.get_item("file")?.unwrap();
516 let file = PyBinaryFile::from(file);
517 assert_eq!(file.seekable()?, false);
518 Ok(())
519 })
520 .unwrap();
521 }
522
523 #[test]
524 fn test_non_seekable_text() {
525 Python::attach(|py| -> PyResult<()> {
526 // Create a custom non-seekable file-like object
527 let locals = pyo3::types::PyDict::new(py);
528 py.run(
529 c_str!(
530 r#"class NonSeekableTextFile:
531 def __init__(self):
532 self.data = "hello"
533 self.pos = 0
534
535 def read(self, n=-1):
536 if n == -1:
537 result = self.data[self.pos:]
538 self.pos = len(self.data)
539 else:
540 result = self.data[self.pos:self.pos + n]
541 self.pos += len(result)
542 return result
543
544 def seekable(self):
545 return False
546
547 file = NonSeekableTextFile()"#
548 ),
549 None,
550 Some(&locals),
551 )?;
552 let file = locals.get_item("file")?.unwrap();
553 let file = PyTextFile::from(file);
554 assert_eq!(file.seekable()?, false);
555 Ok(())
556 })
557 .unwrap();
558 }
559 }