1use std::io;
2use std::path::Path;
3
4use io::BufWriter;
5use io::Write;
6
7use std::os::unix::net::UnixDatagram;
8
9pub fn bytes2str2wtr<W>(bytes: &[u8], wtr: &mut W) -> Result<(), io::Error>
10where
11 W: Write,
12{
13 let s: &str = std::str::from_utf8(bytes).unwrap_or_default();
14 let nolf: &str = s.trim_end();
15 writeln!(wtr, "{nolf}")?;
16 Ok(())
17}
18
19pub fn dgram2bytes(dgram: &UnixDatagram, buf: &mut [u8; 65536]) -> Result<usize, io::Error> {
20 let ms: &mut [u8] = buf.as_mut_slice();
21 dgram.recv(ms)
22}
23
24pub fn dgram2bytes2lines2wtr_forever<W>(
25 dgram: &UnixDatagram,
26 buf: &mut [u8; 65536],
27 wtr: &mut W,
28) -> Result<(), io::Error>
29where
30 W: Write,
31{
32 loop {
33 let sz: usize = dgram2bytes(dgram, buf)?;
34 let got: &[u8] = &buf[..sz];
35 bytes2str2wtr(got, wtr)?;
36 wtr.flush()?;
37 }
38}
39
40pub fn path2dgram2bytes2lines2wtr_forever<P, W>(
41 path2dgram: P,
42 buf: &mut [u8; 65536],
43 wtr: &mut W,
44) -> Result<(), io::Error>
45where
46 P: AsRef<Path>,
47 W: Write,
48{
49 let ud: UnixDatagram = UnixDatagram::bind(path2dgram)?;
50 dgram2bytes2lines2wtr_forever(&ud, buf, wtr)?;
51 wtr.flush()
52}
53
54pub fn path2dgram2bytes2lines2stdout_forever_default<P>(path2dgram: P) -> Result<(), io::Error>
55where
56 P: AsRef<Path>,
57{
58 let mut buf: [u8; 65536] = [0; 65536];
59 let o = io::stdout();
60 let mut ol = o.lock();
61 let mut bw = BufWriter::new(&mut ol);
62 path2dgram2bytes2lines2wtr_forever(path2dgram, &mut buf, &mut bw)?;
63 drop(bw);
64 ol.flush()
65}