#pipe #io #thread-safe #io-write #io-read #single-reader #multi-writer

io-pipe

一个用于在 Rust 中创建多写入和多读取管道的快速且线程安全的库

14 个版本 (5 个破坏性更新)

0.6.2 2024 年 8 月 15 日
0.6.1 2024 年 8 月 15 日
0.5.2 2024 年 8 月 15 日
0.4.0 2024 年 8 月 9 日
0.1.2 2024 年 8 月 7 日

145并发

Download history 479/week @ 2024-08-05 629/week @ 2024-08-12

每月下载 1,108

MIT 许可证

32KB
558

IO 管道库

Crates.io Version GitHub Actions Workflow Status docs.rs Crates.io License

IO 管道是一个线程安全的 Rust 库,用于创建多写入和多读取管道。它非常适合需要从多个线程写入字节并从单个线程读取它们的情况。

功能

  • 写入者和读者之间的线程安全通信
  • 支持同步和异步操作(通过功能标志)
  • 易于使用的 API 用于创建管道

安装

将其添加到您的 Cargo.toml

[dependencies]
io-pipe = "0.x.x"

对于异步支持,启用 async 功能

[dependencies]
io-pipe = { version = "0.x.x", features = ["async"] }

使用

同步 API

单线程示例

use std::io::{read_to_string, Write};
use io_pipe::pipe;

fn main() {
    let (mut writer, reader) = pipe();
    writer.write_all("hello".as_bytes()).unwrap();
    drop(writer);

    assert_eq!("hello".to_string(), read_to_string(reader).unwrap());
}

多线程示例

use std::io::{read_to_string, Write};
use std::thread::spawn;
use io_pipe::pipe;

fn main() {
    let (mut writer, reader) = pipe();
    spawn(move || {
        writer.write_all("hello".as_bytes()).unwrap();
    });

    assert_eq!("hello".len(), read_to_string(reader).unwrap().len());
}

异步 API

use io_pipe::async_pipe;
use futures::io::{AsyncWriteExt, AsyncReadExt};
use futures::executor::block_on;

fn main() {
    block_on(async {
        let (mut writer, mut reader) = async_pipe();

        writer.write_all(b"hello").await.unwrap();
        drop(writer);

        let mut buffer = String::new();
        reader.read_to_string(&mut buffer).await.unwrap();
        assert_eq!("hello", buffer);
    });
}

同步到异步示例

use io_pipe::async_reader_pipe;
use std::io::Write;
use futures::io::AsyncReadExt;
use futures::executor::block_on;

fn main() {
    let (mut writer, mut reader) = async_reader_pipe();
    writer.write_all(b"hello").unwrap();
    drop(writer);

    block_on(async {
        let mut buffer = String::new();
        reader.read_to_string(&mut buffer).await.unwrap();
        assert_eq!("hello", buffer);
    })
}

异步到同步示例

use io_pipe::async_writer_pipe;
use std::io::Read;
use futures::io::AsyncWriteExt;
use futures::executor::block_on;

fn main() {
    let (mut writer, mut reader) = async_writer_pipe();

    block_on(async {
        writer.write_all(b"hello").await.unwrap();
        drop(writer);
    });

    let mut buffer = String::new();
    reader.read_to_string(&mut buffer).unwrap();
    assert_eq!("hello", buffer);
}

文档

有关详细 API 文档,请参阅 docs.rs

贡献

欢迎贡献!请随时提交拉取请求。

指南

  1. 使用 rustfmt 格式化您的代码。
  2. 在提交拉取请求之前运行 clippy 并解决任何 lint。
  3. 为新功能编写测试。
  4. 根据需要更新文档。

许可证

本项目采用 MIT 许可证 - 有关详细信息,请参阅 LICENSE 文件。

依赖项

~51KB