ckb_script_ipc_common/
pipe.rs1use crate::io::{Error, ErrorKind, Read, Write};
2use ckb_std::syscalls::{read, write};
3
4pub struct Pipe {
5 id: u64,
6}
7
8impl Pipe {
9 pub fn new(id: u64) -> Self {
10 Self { id }
11 }
12
13 pub fn fd(&self) -> u64 {
14 self.id
15 }
16
17 pub fn readable(&self) -> bool {
18 self.id % 2 == 0
19 }
20
21 pub fn writable(&self) -> bool {
22 self.id % 2 == 1
23 }
24}
25
26impl From<u64> for Pipe {
27 fn from(id: u64) -> Self {
28 Self::new(id)
29 }
30}
31
32impl Read for Pipe {
33 fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error> {
34 match read(self.id, buf) {
35 Ok(n) => Ok(n),
36 Err(_e) => Err(Error::Simple(ErrorKind::Other)),
37 }
38 }
39}
40
41impl Write for Pipe {
42 fn write(&mut self, buf: &[u8]) -> Result<usize, Error> {
43 if buf.is_empty() {
44 return Ok(0);
45 }
46 match write(self.id, buf) {
47 Ok(n) => Ok(n),
48 Err(_e) => Err(Error::Simple(ErrorKind::Other)),
49 }
50 }
51
52 fn flush(&mut self) -> Result<(), Error> {
53 Ok(())
54 }
55}