pyo3-filelike-0.5.1/.cargo_vcs_info.json0000644000000001360000000000100135130ustar { "git": { "sha1": "b2f69e02a968c11607d507b1aff30f05f33f5b36" }, "path_in_vcs": "" }pyo3-filelike-0.5.1/.codespellrc000064400000000000000000000000461046102023000146030ustar 00000000000000[codespell] ignore-words-list = crate pyo3-filelike-0.5.1/.github/CODEOWNERS000064400000000000000000000000121046102023000152270ustar 00000000000000* @jelmer pyo3-filelike-0.5.1/.github/FUNDING.yml000064400000000000000000000000171046102023000154560ustar 00000000000000github: jelmer pyo3-filelike-0.5.1/.github/dependabot.yaml000064400000000000000000000010751046102023000166370ustar 00000000000000# Keep GitHub Actions up to date with GitHub's Dependabot... # https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot # https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem version: 2 updates: - package-ecosystem: "cargo" directory: "/" schedule: interval: "weekly" rebase-strategy: "disabled" - package-ecosystem: "github-actions" directory: "/" schedule: interval: weekly pyo3-filelike-0.5.1/.github/workflows/auto-merge.yml000064400000000000000000000011341046102023000204670ustar 00000000000000name: Dependabot auto-merge on: pull_request_target permissions: pull-requests: write contents: write jobs: dependabot: runs-on: ubuntu-latest if: ${{ github.actor == 'dependabot[bot]' }} steps: - name: Dependabot metadata id: metadata uses: dependabot/fetch-metadata@v2 with: github-token: "${{ secrets.GITHUB_TOKEN }}" - name: Enable auto-merge for Dependabot PRs run: gh pr merge --auto --squash "$PR_URL" env: PR_URL: ${{github.event.pull_request.html_url}} GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} pyo3-filelike-0.5.1/.github/workflows/publish.yaml000064400000000000000000000010511046102023000202270ustar 00000000000000on: push: tags: - 'v*' # Push events to every tag not containing / workflow_dispatch: name: Publish jobs: publish: name: Publish runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@v5 - name: Install stable toolchain uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable override: true - run: cargo publish --token ${CRATES_TOKEN} env: CRATES_TOKEN: ${{ secrets.CRATES_TOKEN }} pyo3-filelike-0.5.1/.github/workflows/rust.yml000064400000000000000000000016521046102023000174240ustar 00000000000000name: Rust on: push: pull_request: env: CARGO_TERM_COLOR: always jobs: build: runs-on: ubuntu-latest strategy: matrix: version-mode: ['maximal', 'minimal'] steps: - uses: actions/checkout@v5 - name: Install cargo-minimal-versions and cargo-hack if: matrix.version-mode == 'minimal' run: | cargo install cargo-minimal-versions --locked cargo install cargo-hack --locked - name: Build (maximal versions) if: matrix.version-mode == 'maximal' run: cargo build --verbose - name: Run tests (maximal versions) if: matrix.version-mode == 'maximal' run: cargo test --verbose - name: Build (minimal versions) if: matrix.version-mode == 'minimal' run: cargo minimal-versions build --verbose - name: Run tests (minimal versions) if: matrix.version-mode == 'minimal' run: cargo minimal-versions test --verbose pyo3-filelike-0.5.1/.gitignore000064400000000000000000000000131046102023000142650ustar 00000000000000/target *~ pyo3-filelike-0.5.1/CODE_OF_CONDUCT.md000064400000000000000000000125451046102023000151110ustar 00000000000000 # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socioeconomic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations pyo3-filelike-0.5.1/Cargo.lock0000644000000105730000000000100114740ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "autocfg" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "indoc" version = "2.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" dependencies = [ "rustversion", ] [[package]] name = "libc" version = "0.2.177" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" [[package]] name = "memoffset" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" dependencies = [ "autocfg", ] [[package]] name = "once_cell" version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] name = "portable-atomic" version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" [[package]] name = "proc-macro2" version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" dependencies = [ "unicode-ident", ] [[package]] name = "pyo3" version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37a6df7eab65fc7bee654a421404947e10a0f7085b6951bf2ea395f4659fb0cf" dependencies = [ "indoc", "libc", "memoffset", "once_cell", "portable-atomic", "pyo3-build-config", "pyo3-ffi", "pyo3-macros", "unindent", ] [[package]] name = "pyo3-build-config" version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f77d387774f6f6eec64a004eac0ed525aab7fa1966d94b42f743797b3e395afb" dependencies = [ "target-lexicon", ] [[package]] name = "pyo3-ffi" version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dd13844a4242793e02df3e2ec093f540d948299a6a77ea9ce7afd8623f542be" dependencies = [ "libc", "pyo3-build-config", ] [[package]] name = "pyo3-filelike" version = "0.5.1" dependencies = [ "pyo3", ] [[package]] name = "pyo3-macros" version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaf8f9f1108270b90d3676b8679586385430e5c0bb78bb5f043f95499c821a71" dependencies = [ "proc-macro2", "pyo3-macros-backend", "quote", "syn", ] [[package]] name = "pyo3-macros-backend" version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70a3b2274450ba5288bc9b8c1b69ff569d1d61189d4bff38f8d22e03d17f932b" dependencies = [ "heck", "proc-macro2", "pyo3-build-config", "quote", "syn", ] [[package]] name = "quote" version = "1.0.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1" dependencies = [ "proc-macro2", ] [[package]] name = "rustversion" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" [[package]] name = "syn" version = "2.0.108" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da58917d35242480a05c2897064da0a80589a2a0476c9a3f2fdc83b53502e917" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "target-lexicon" version = "0.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df7f62577c25e07834649fc3b39fafdc597c0a3527dc1c60129201ccfcbaa50c" [[package]] name = "unicode-ident" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "462eeb75aeb73aea900253ce739c8e18a67423fadf006037cd3ff27e82748a06" [[package]] name = "unindent" version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3" pyo3-filelike-0.5.1/Cargo.toml0000644000000017420000000000100115150ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "pyo3-filelike" version = "0.5.1" build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Rust access to Python file-like objects" readme = "README.md" license = "Apache-2.0" repository = "https://github.com/jelmer/pyo3-filelike" [lib] name = "pyo3_filelike" path = "src/lib.rs" [dependencies.pyo3] version = ">=0.26, <0.28" [dev-dependencies.pyo3] version = ">=0.26, <0.28" features = [ "auto-initialize", "abi3", ] pyo3-filelike-0.5.1/Cargo.toml.orig000064400000000000000000000005221046102023000151710ustar 00000000000000[package] name = "pyo3-filelike" version = "0.5.1" edition = "2021" description = "Rust access to Python file-like objects" license = "Apache-2.0" repository = "https://github.com/jelmer/pyo3-filelike" [dependencies] pyo3 = ">=0.26, <0.28" [dev-dependencies] pyo3 = { version = ">=0.26, <0.28", features = ["auto-initialize", "abi3"] } pyo3-filelike-0.5.1/README.md000064400000000000000000000026021046102023000135620ustar 00000000000000# Rust compatible wrappers for file-like objects in Python This crate provides a wrapper for file-like objects in Python that implement the `io` protocol, and allows them to be used as `Read`, `Write`, and `Seek` traits in Rust. Objects need to implement the `io` protocol. For the `Read` trait, the object must have a `read` method that takes a single argument, the number of bytes to read, and returns a `bytes` object. For the `Write` trait, the object must have a `write` method that takes a single argument, a `bytes` object. For the `Seek` trait, the object must have a `seek` method that takes two arguments, the offset and whence, and returns the new position. The `mode` attribute is checked to ensure that the file is opened in binary mode. If the `mode` attribute is not present, the file is assumed to be opened in binary mode. The `AsFd` trait is implemented for Unix-like systems, allowing the file to be used with functions that take a file descriptor. The `fileno` method is called to get the file descriptor. # Example ```rust use pyo3::prelude::*; use std::io::{Read, Write}; pyo3::Python::with_gil(|py| -> PyResult<()> { let io = py.import("io")?; let file = io.call_method1("BytesIO", (&b"hello"[..], ))?; let mut file = pyo3_filelike::PyBinaryFile::from(file); let mut buf = [0u8; 5]; file.read_exact(&mut buf)?; assert_eq!(&buf, b"hello"); Ok(()) }).unwrap(); pyo3-filelike-0.5.1/src/lib.rs000064400000000000000000000262001046102023000142060ustar 00000000000000#![deny(missing_docs)] #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))] use pyo3::prelude::*; use pyo3::exceptions::{PyAttributeError, PyValueError}; use std::io::{Read, Seek, Write}; #[cfg(any(unix, target_os = "wasi"))] use std::os::fd::{AsFd, BorrowedFd, RawFd}; use std::borrow::Cow; /// Rust wrapper for a Python file-like object that implements the `io` protocol. #[derive(Debug)] pub struct PyBinaryFile(Py); impl<'py> IntoPyObject<'py> for PyBinaryFile { type Target = PyAny; type Output = Bound<'py, PyAny>; type Error = PyErr; fn into_pyobject(self, py: Python<'py>) -> Result { let obj = self.0.clone_ref(py); Ok(obj.into_bound(py)) } } impl Clone for PyBinaryFile { fn clone(&self) -> Self { Python::attach(|py| PyBinaryFile::from(self.0.clone_ref(py))) } } impl Read for PyBinaryFile { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { Python::attach(|py| { let bytes = self.0.call_method1(py, "read", (buf.len(),))?; let bytes = bytes .extract::<&[u8]>(py) .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?; let len = std::cmp::min(buf.len(), bytes.len()); buf[..len].copy_from_slice(&bytes[..len]); Ok(len) }) } } impl Write for PyBinaryFile { fn write(&mut self, buf: &[u8]) -> std::io::Result { Python::attach(|py| { let bytes = pyo3::types::PyBytes::new(py, buf); self.0.call_method1(py, "write", (bytes,))?; Ok(buf.len()) }) } fn flush(&mut self) -> std::io::Result<()> { Python::attach(|py| { self.0.call_method0(py, "flush")?; Ok(()) }) } } impl Seek for PyBinaryFile { fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { Python::attach(|py| { let (whence, offset) = match pos { std::io::SeekFrom::Start(offset) => (0, offset as i64), std::io::SeekFrom::End(offset) => (2, offset), std::io::SeekFrom::Current(offset) => (1, offset), }; let pos = self.0.call_method1(py, "seek", (offset, whence))?; let pos = pos.extract::(py)?; Ok(pos) }) } } #[cfg(any(unix, target_os = "wasi"))] impl AsFd for PyBinaryFile { fn as_fd(&self) -> BorrowedFd<'_> { Python::attach(|py| { let fd = self.0.call_method0(py, "fileno")?; let fd = fd.extract::(py)?; Ok::, PyErr>(unsafe { BorrowedFd::borrow_raw(fd) }) }) .unwrap() } } impl PyBinaryFile { fn new(file: Py) -> PyResult { let o = PyBinaryFile(file); o.check_mode('b')?; Ok(o) } fn check_mode(&self, expected_mode: char) -> PyResult<()> { Python::attach(|py| { match self.0.getattr(py, "mode") { Ok(mode) => { let mode_str = match mode.extract::>(py) { Ok(mode_str) => mode_str, Err(_) => { // Assume binary mode if mode attribute is not a string return Ok(()); } }; if mode_str.contains(expected_mode) { return Ok(()); } Err(PyValueError::new_err(format!( "file must be opened in {} mode", expected_mode ))) } Err(e) if e.is_instance_of::(py) => { // Assume binary mode if mode attribute is not present Ok(()) } Err(e) => Err(e), } }) } } impl From> for PyBinaryFile { fn from(obj: Py) -> Self { PyBinaryFile::new(obj).unwrap() } } impl From> for PyBinaryFile { fn from(obj: Bound<'_, PyAny>) -> Self { PyBinaryFile::new(obj.into()).unwrap() } } /// Rust wrapper for a Python text file-like object that implements the `io` protocol. /// /// This wrapper is similar to `PyBinaryFile`, but it assumes that the file is text and /// returns the byte representation of the text. /// /// The Python file-like object must have a `read` method that returns either a /// `bytes` object or a `str` object. /// /// Seek operations are not supported on text files, since the equivalent Python /// file-like objects seek by characters, not bytes. #[derive(Debug)] pub struct PyTextFile { inner: Py, buffer: Vec, } impl PyTextFile { /// Create a new `PyTextFile` from a Python file-like object and an encoding. pub fn new(file: Py) -> PyResult { Ok(PyTextFile { inner: file, buffer: Vec::new(), }) } } impl Read for PyTextFile { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { Python::attach(|py| { if self.buffer.len() >= buf.len() { buf.copy_from_slice(&self.buffer[..buf.len()]); self.buffer.drain(..buf.len()); return Ok(buf.len()); } let text = self .inner .call_method1(py, "read", (buf.len() - self.buffer.len(),))?; if let Ok(t) = text.extract::>(py) { self.buffer.extend_from_slice(t.as_bytes()); } else { self.buffer .extend_from_slice(text.extract::<&[u8]>(py).map_err(|e| { std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()) })?); } let len = std::cmp::min(self.buffer.len(), buf.len()); buf[..len].copy_from_slice(&self.buffer[..len]); self.buffer.drain(..len); Ok(len) }) } } impl From> for PyTextFile { fn from(obj: Py) -> Self { PyTextFile::new(obj).unwrap() } } impl From> for PyTextFile { fn from(obj: Bound<'_, PyAny>) -> Self { PyTextFile::new(obj.into()).unwrap() } } impl<'py> IntoPyObject<'py> for PyTextFile { type Target = PyAny; type Output = Bound<'py, PyAny>; type Error = PyErr; fn into_pyobject(self, py: Python<'py>) -> Result { let obj = self.inner.clone_ref(py); Ok(obj.into_bound(py)) } } impl Clone for PyTextFile { fn clone(&self) -> Self { Python::attach(|py| PyTextFile::from(self.inner.clone_ref(py))) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_read() { Python::attach(|py| -> PyResult<()> { let io = py.import("io")?; let file = io.call_method1("BytesIO", (&b"hello"[..],))?; let mut file = PyBinaryFile::from(file); let mut buf = [0u8; 5]; file.read_exact(&mut buf)?; assert_eq!(&buf, b"hello"); Ok(()) }) .unwrap(); } #[test] fn test_read_notexact() { Python::attach(|py| -> PyResult<()> { let io = py.import("io")?; let file = io.call_method1("BytesIO", (&b"hello"[..],))?; let mut file = PyBinaryFile::from(file); let mut buf = [0u8; 10]; let n = file.read(&mut buf)?; assert_eq!(n, 5); assert_eq!(&buf[..n], b"hello"); Ok(()) }) .unwrap(); } #[test] fn test_read_eof() { Python::attach(|py| -> PyResult<()> { let io = py.import("io")?; let file = io.call_method1("BytesIO", (&b"hello"[..],))?; let mut file = PyBinaryFile::from(file); let mut buf = [0u8; 6]; let err = file.read_exact(&mut buf).unwrap_err(); assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof); Ok(()) }) .unwrap(); } #[test] fn test_read_to_end() { Python::attach(|py| -> PyResult<()> { let io = py.import("io")?; let file = io.call_method1("BytesIO", (&b"hello"[..],))?; let mut file = PyBinaryFile::from(file); let mut buf = Vec::new(); file.read_to_end(&mut buf)?; assert_eq!(&buf, b"hello"); Ok(()) }) .unwrap(); } #[test] fn test_write() { Python::attach(|py| { let io = py.import("io")?; let file = io.call_method1("BytesIO", (&b""[..],))?; let mut file = PyBinaryFile::from(file); file.write_all(b"hello ")?; file.write_all(b"world")?; assert_eq!( file.0.call_method0(py, "getvalue")?.extract::<&[u8]>(py)?, b"hello world" ); Ok::<(), PyErr>(()) }) .unwrap(); } #[test] fn test_seek() { Python::attach(|py| { let io = py.import("io")?; let file = io.call_method1("BytesIO", (&b"hello"[..],))?; let mut file = PyBinaryFile::from(file); file.seek(std::io::SeekFrom::Start(1))?; let mut buf = [0u8; 4]; file.read_exact(&mut buf)?; assert_eq!(&buf, b"ello"); Ok::<(), PyErr>(()) }) .unwrap(); } #[test] fn test_flush() { Python::attach(|py| { let io = py.import("io")?; let file = io.call_method1("BytesIO", (&b""[..],))?; let mut file = PyBinaryFile::from(file); file.write_all(b"hello")?; file.flush()?; assert_eq!( file.0.call_method0(py, "getvalue")?.extract::<&[u8]>(py)?, b"hello" ); Ok::<(), PyErr>(()) }) .unwrap(); } #[test] fn test_read_text() { Python::attach(|py| -> PyResult<()> { let io = py.import("io")?; let file = io.call_method1("StringIO", ("hello world",))?; let mut file = PyTextFile::from(file); let mut buf = [0u8; 5]; file.read_exact(&mut buf)?; assert_eq!(&buf, b"hello"); file.read_exact(&mut buf)?; assert_eq!(&buf, b" worl"); let mut buf = Vec::new(); file.read_to_end(&mut buf).unwrap(); assert_eq!(&buf, b"d"); Ok(()) }) .unwrap(); } #[test] fn test_read_text_unicode() { // read halfway through a unicode character let io = Python::attach(|py| -> PyResult> { let io = py.import("io")?; let file = io.call_method1("StringIO", ("hello \u{1f600} world",))?; Ok(file.into()) }) .unwrap(); let mut file = PyTextFile::from(io); let mut buf = [0u8; 7]; file.read_exact(&mut buf).unwrap(); assert_eq!(&buf, b"hello \xf0"); let mut buf = [0u8; 1]; file.read_exact(&mut buf).unwrap(); assert_eq!(&buf, b"\x9f"); } }