|
| 1 | +#[cfg(any(target_os = "linux", target_os = "android"))] |
| 2 | +mod linux_android { |
| 3 | + use std::io::prelude::*; |
| 4 | + use std::os::unix::prelude::*; |
| 5 | + |
| 6 | + use libc::loff_t; |
| 7 | + |
| 8 | + use nix::fcntl::{SpliceFFlags, splice, tee, vmsplice}; |
| 9 | + use nix::sys::uio::IoVec; |
| 10 | + use nix::unistd::{close, pipe, read, write}; |
| 11 | + |
| 12 | + use tempfile::tempfile; |
| 13 | + |
| 14 | + #[test] |
| 15 | + fn test_splice() { |
| 16 | + const CONTENTS: &'static [u8] = b"abcdef123456"; |
| 17 | + let mut tmp = tempfile().unwrap(); |
| 18 | + tmp.write(CONTENTS).unwrap(); |
| 19 | + |
| 20 | + let (rd, wr) = pipe().unwrap(); |
| 21 | + let mut offset: loff_t = 5; |
| 22 | + let res = splice(tmp.as_raw_fd(), Some(&mut offset), |
| 23 | + wr, None, 2, SpliceFFlags::empty()).unwrap(); |
| 24 | + |
| 25 | + assert_eq!(2, res); |
| 26 | + |
| 27 | + let mut buf = [0u8; 1024]; |
| 28 | + assert_eq!(2, read(rd, &mut buf).unwrap()); |
| 29 | + assert_eq!(b"f1", &buf[0..2]); |
| 30 | + assert_eq!(7, offset); |
| 31 | + |
| 32 | + close(rd).unwrap(); |
| 33 | + close(wr).unwrap(); |
| 34 | + } |
| 35 | + |
| 36 | + #[test] |
| 37 | + fn test_tee() { |
| 38 | + let (rd1, wr1) = pipe().unwrap(); |
| 39 | + let (rd2, wr2) = pipe().unwrap(); |
| 40 | + |
| 41 | + write(wr1, b"abc").unwrap(); |
| 42 | + let res = tee(rd1, wr2, 2, SpliceFFlags::empty()).unwrap(); |
| 43 | + |
| 44 | + assert_eq!(2, res); |
| 45 | + |
| 46 | + let mut buf = [0u8; 1024]; |
| 47 | + |
| 48 | + // Check the tee'd bytes are at rd2. |
| 49 | + assert_eq!(2, read(rd2, &mut buf).unwrap()); |
| 50 | + assert_eq!(b"ab", &buf[0..2]); |
| 51 | + |
| 52 | + // Check all the bytes are still at rd1. |
| 53 | + assert_eq!(3, read(rd1, &mut buf).unwrap()); |
| 54 | + assert_eq!(b"abc", &buf[0..3]); |
| 55 | + |
| 56 | + close(rd1).unwrap(); |
| 57 | + close(wr1).unwrap(); |
| 58 | + close(rd2).unwrap(); |
| 59 | + close(wr2).unwrap(); |
| 60 | + } |
| 61 | + |
| 62 | + #[test] |
| 63 | + fn test_vmsplice() { |
| 64 | + let (rd, wr) = pipe().unwrap(); |
| 65 | + |
| 66 | + let buf1 = b"abcdef"; |
| 67 | + let buf2 = b"defghi"; |
| 68 | + let mut iovecs = Vec::with_capacity(2); |
| 69 | + iovecs.push(IoVec::from_slice(&buf1[0..3])); |
| 70 | + iovecs.push(IoVec::from_slice(&buf2[0..3])); |
| 71 | + |
| 72 | + let res = vmsplice(wr, &iovecs[..], SpliceFFlags::empty()).unwrap(); |
| 73 | + |
| 74 | + assert_eq!(6, res); |
| 75 | + |
| 76 | + // Check the bytes can be read at rd. |
| 77 | + let mut buf = [0u8; 32]; |
| 78 | + assert_eq!(6, read(rd, &mut buf).unwrap()); |
| 79 | + assert_eq!(b"abcdef", &buf[0..6]); |
| 80 | + |
| 81 | + close(rd).unwrap(); |
| 82 | + close(wr).unwrap(); |
| 83 | + } |
| 84 | + |
| 85 | +} |
0 commit comments