1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
use std::fs::{File, OpenOptions};
use std::io;
use std::io::{Error, ErrorKind, Read, Write};
use std::net::TcpStream;
use std::path::Path;
use std::thread::{spawn, JoinHandle};

use cfg_if::cfg_if;
use polling::{Event, Poller};

use crate::utf8::encode_utf8;

pub mod duplicator;
pub mod errors;

trait ReadLine {
    /// Read lines without the end newline mark (CR and/or LF)
    fn read_line_without_line_terminator(&mut self) -> Option<String>;
}

pub struct Lines<'a, T>
where
    T: Read,
{
    readable: &'a mut T,
}

pub trait ReadLines<T>
where
    T: Read,
{
    /// Read lines from the readable stream
    ///
    /// The std lib implementation: [`Stdin::lines`]
    ///
    /// # Examples
    /// ```no_run
    /// use bczhc_lib::io::ReadLines;
    /// use std::io::stdin;
    ///
    /// let mut stdin = stdin();
    /// let lines = ReadLines::lines(&mut stdin);
    /// for line in lines {
    ///     println!("{}", line);
    /// }
    /// ```
    fn lines(&mut self) -> Lines<T>;
}

impl<T> Iterator for Lines<'_, T>
where
    T: Read,
{
    type Item = String;

    fn next(&mut self) -> Option<Self::Item> {
        super::io::ReadLine::read_line_without_line_terminator(self.readable)
    }
}

impl<T> ReadLines<T> for T
where
    T: Read,
{
    fn lines(&mut self) -> Lines<T> {
        Lines { readable: self }
    }
}

impl<T> ReadLine for T
where
    T: Read,
{
    fn read_line_without_line_terminator(&mut self) -> Option<String> {
        let mut read: Vec<u8> = Vec::new();
        let mut buf = [0_u8];
        loop {
            let result = self.read_exact(&mut buf);
            if let Err(e) = result {
                if let ErrorKind::UnexpectedEof = e.kind() {
                    return if read.is_empty() {
                        None
                    } else {
                        Some(String::from_utf8(read).unwrap())
                    };
                } else {
                    panic!("{}", e.to_string());
                }
            }
            if buf[0] == b'\n' {
                break;
            }
            read.push(buf[0]);
        }
        Some(String::from_utf8(read).unwrap())
    }
}

pub trait OpenOrCreate {
    fn open_or_create<P: AsRef<Path>>(path: P) -> std::io::Result<File> {
        OpenOptions::new()
            .truncate(true)
            .create(true)
            .write(true)
            .read(true)
            .open(path.as_ref())
    }

    fn open_append_file<P: AsRef<Path>>(path: P) -> std::io::Result<File> {
        OpenOptions::new()
            .create(true)
            .write(true)
            .read(true)
            .append(true)
            .open(path.as_ref())
    }
}

impl OpenOrCreate for File {}

pub trait Skip {
    fn skip(&mut self, size: usize) -> std::io::Result<()>;
}

impl<T> Skip for T
where
    T: Read,
{
    fn skip(&mut self, size: usize) -> std::io::Result<()> {
        let read = std::io::copy(&mut self.take(size as u64), &mut std::io::sink())?;
        if read as usize != size {
            return Err(Error::new(ErrorKind::UnexpectedEof, "Failed to skip"));
        }
        Ok(())
    }
}

pub trait ReadAll {
    /// Read all data until the end
    ///
    /// # Examples
    /// ```no_run
    /// use std::fs::File;
    /// use bczhc_lib::io::ReadAll;
    ///
    /// let mut file = File::open("aa").unwrap();
    /// let data = file.read_all();
    /// println!("Data: {:?}", data);
    /// ```
    fn read_all(&mut self) -> Vec<u8>;
}

impl<R> ReadAll for R
where
    R: Read,
{
    fn read_all(&mut self) -> Vec<u8> {
        let mut out = Vec::new();
        let mut buf = [0_u8; 4096];
        loop {
            let read_len = self.read(&mut buf[..]).unwrap();
            if read_len == 0 {
                // EOF
                break;
            }
            for b in buf[..read_len].iter() {
                out.push(*b);
            }
        }
        out
    }
}

/// Write a byte to [`stdout`] immediately
/// # Examples
///
/// ```no_run
/// use bczhc_lib::io::put_c_char;
///
/// put_c_char(b'a').unwrap();
/// ```
///
/// # Errors
/// When the C `putchar` returns [`libc::EOF`]
///
#[inline]
pub fn put_c_char(c: u8) -> std::io::Result<()> {
    unsafe {
        let r = libc::write(1, &c as *const u8 as *const libc::c_void, 1);
        if r != 1 {
            // TODO: get error kind from `errno`
            return Err(std::io::Error::from(ErrorKind::Other));
        }
    }
    Ok(())
}

/// Write a rust [`char`] to [`stdout`] immediately
///
/// # Examples
///
/// ```no_run
/// use bczhc_lib::io::put_char;
///
/// put_char('ö').unwrap();
/// ```
#[inline]
pub fn put_char(c: char) -> std::io::Result<()> {
    let mut bytes = [0_u8; 4];
    let size = encode_utf8(c as u32, &mut bytes);
    for b in bytes.iter().take(size) {
        put_c_char(*b)?;
    }
    Ok(())
}

pub trait TryReadExact {
    /// Read exact data
    ///
    /// This function blocks. It reads exact data, and returns bytes it reads. The return value
    /// will always be the buffer size until it reaches EOF.
    ///
    /// When reaching EOF, the return value will be less than the size of the given buffer,
    /// or just zero.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::io::stdin;
    /// use bczhc_lib::io::TryReadExact;
    ///
    /// let mut stdin = stdin();
    /// let mut buf = [0_u8; 5];
    /// loop {
    ///     let result = stdin.try_read_exact(&mut buf);
    ///     match result {
    ///         Ok(r) => {
    ///             if r == 0 {
    ///                 // EOF
    ///                 break;
    ///             }
    ///             println!("Read: {:?}", &buf[..r]);
    ///         }
    ///         Err(e) => {
    ///             eprintln!("IO error: {}", e);
    ///         }
    ///     }
    /// }
    /// ```
    fn try_read_exact(&mut self, buf: &mut [u8]) -> std::io::Result<usize>;
}

impl<R> TryReadExact for R
where
    R: Read,
{
    fn try_read_exact(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let mut read = 0_usize;
        loop {
            let result = self.read(&mut buf[read..]);
            match result {
                Ok(r) => {
                    if r == 0 {
                        return Ok(read);
                    }
                    read += r;
                    if read == buf.len() {
                        return Ok(read);
                    }
                }
                Err(e) => {
                    return Err(e);
                }
            }
        }
    }
}

pub fn pipe_thread<R, W>(reader: R, writer: W) -> JoinHandle<io::Result<()>>
where
    R: Read + Send + 'static,
    W: Write + Send + 'static,
{
    fn pipe<R, W>(mut reader: R, mut writer: W) -> io::Result<()>
    where
        R: Read,
        W: Write,
    {
        let mut buf = [0_u8; 4096];
        loop {
            let size = reader.read(&mut buf)?;
            if size == 0 {
                break;
            }
            writer.write_all(&buf[..size])?;
        }
        Ok(())
    }

    spawn(move || pipe(reader, writer))
}

pub fn attach_tcp_stream_to_stdio(stream: &mut TcpStream) -> io::Result<()> {
    cfg_if! {
        if #[cfg(unix)] {
            unix::attach_stream_to_stdio(stream)
        } else {
            generic::attach_tcp_stream_to_stdio(stream)
        }
    }
}

cfg_if! {
    if #[cfg(windows)] {
        use std::os::windows::io::AsRawSocket;
        pub trait Poll: Read + Write + AsRawSocket {}
        impl<T> Poll for T where T: Read + Write + AsRawSocket {}
    } else if #[cfg(unix)] {
        use std::os::unix::io::AsRawFd;
        pub trait Poll: Read + Write + AsRawFd {}
        impl<T> Poll for T where T: Read + Write + AsRawFd {}
    }
}

pub fn interact_two_streams<S1, S2>(stream1: &mut S1, stream2: &mut S2) -> io::Result<()>
where
    S1: Poll,
    S2: Poll,
{
    let stream1_key = 0;
    let stream2_key = 1;

    let poller = Poller::new()?;
    poller.add(&*stream1, Event::readable(stream1_key))?;
    poller.add(&*stream2, Event::readable(stream2_key))?;

    let mut events = Vec::new();
    let mut buf = [0_u8; 4096];
    'poll_loop: loop {
        events.clear();
        poller.wait(&mut events, None)?;
        for ev in &events {
            let key = ev.key;
            let readable = ev.readable;
            match ev.key {
                _ if key == stream1_key && readable => {
                    let size = stream1.read(&mut buf)?;
                    if size == 0 {
                        break 'poll_loop;
                    }
                    stream2.write_all(&buf[..size])?;
                }
                _ if key == stream2_key && readable => {
                    let size = stream2.read(&mut buf)?;
                    if size == 0 {
                        break 'poll_loop;
                    }
                    stream1.write_all(&buf[..size])?;
                }
                _ => {
                    unreachable!();
                }
            }
            poller.modify(&*stream1, Event::readable(stream1_key))?;
            poller.modify(&*stream2, Event::readable(stream2_key))?;
        }
    }
    Ok(())
}

pub mod unix {
    use std::io;
    use std::io::{stdin, stdout, Read, Write};
    use std::net::TcpStream;

    use polling::{Event, Poller};

    macro_rules! interact_two_stream_code_gen {
        ($stream1:expr, $stream2:expr,
        $stream1_dest:expr, $stream2_dest:expr) => {
            let stream1_key = 0;
            let stream2_key = 1;

            let poller = Poller::new()?;
            poller.add(&*$stream1, Event::readable(stream1_key))?;
            poller.add(&*$stream2, Event::readable(stream2_key))?;

            let mut events = Vec::new();
            let mut buf = [0_u8; 4096];
            'poll_loop: loop {
                events.clear();
                poller.wait(&mut events, None)?;
                for ev in &events {
                    let key = ev.key;
                    let readable = ev.readable;
                    match ev.key {
                        _ if key == stream1_key && readable => {
                            let size = $stream1.read(&mut buf)?;
                            if size == 0 {
                                break 'poll_loop;
                            }
                            $stream1_dest.write_all(&buf[..size])?;
                        }
                        _ if key == stream2_key && readable => {
                            let size = $stream2.read(&mut buf)?;
                            if size == 0 {
                                break 'poll_loop;
                            }
                            $stream2_dest.write_all(&buf[..size])?;
                        }
                        _ => {
                            unreachable!();
                        }
                    }
                    poller.modify(&*$stream1, Event::readable(stream1_key))?;
                    poller.modify(&*$stream2, Event::readable(stream2_key))?;
                }
            }

            return Ok(())
        };
    }

    #[cfg(unix)]
    use std::os::unix::io::AsRawFd;
    #[cfg(unix)]
    pub fn attach_stream_to_stdio<S>(stream: &mut S) -> io::Result<()>
    where
        S: Read + Write + AsRawFd,
    {
        let stdin = &mut stdin().lock();
        let stdout = &mut stdout().lock();

        interact_two_stream_code_gen!(stream, stdin, stdout, stream);
    }

    pub fn interact_two_stream(stream1: &mut TcpStream, stream2: &mut TcpStream) -> io::Result<()> {
        interact_two_stream_code_gen!(stream1, stream2, stream2, stream1);
    }
}

#[cfg(not(unix))]
pub mod generic {
    use std::io;
    use std::io::{stdin, stdout};
    use std::net::TcpStream;

    use crate::io::pipe_thread;

    pub fn attach_tcp_stream_to_stdio(stream: &mut TcpStream) -> io::Result<()> {
        let t1 = pipe_thread(stdin(), stream.try_clone()?);
        let t2 = pipe_thread(stream.try_clone()?, stdout());
        t1.join().unwrap()?;
        t2.join().unwrap()?;
        Ok(())
    }

    pub fn interact_two_stream(stream1: &mut TcpStream, stream2: &mut TcpStream) -> io::Result<()> {
        let t1 = pipe_thread(stream1.try_clone()?, stream2.try_clone()?);
        let t2 = pipe_thread(stream2.try_clone()?, stream1.try_clone()?);
        t1.join().unwrap()?;
        t2.join().unwrap()?;
        Ok(())
    }
}

pub trait ReadText
where
    Self: Read,
{
    fn read_text(&mut self) -> io::Result<String> {
        let mut s = String::new();
        self.read_to_string(&mut s)?;
        Ok(s)
    }
}

impl<R: Read> ReadText for R {}

#[cfg(test)]
pub mod test {
    use crate::io::TryReadExact;
    use std::io::Cursor;

    #[test]
    pub fn try_read_exact1() {
        let mut reader = Cursor::new(vec![0_u8, 1, 2, 3, 4]);
        let mut buf = [0_u8; 5];
        let size = reader.try_read_exact(&mut buf).unwrap();
        assert_eq!(size, 5);
        assert_eq!(buf, [0_u8, 1, 2, 3, 4]);

        let size = reader.try_read_exact(&mut buf).unwrap();
        assert_eq!(size, 0);
    }

    #[test]
    pub fn try_read_exact2() {
        let mut reader = Cursor::new(vec![0_u8, 1, 2, 3, 4]);
        let mut buf = [0_u8; 3];
        let size = reader.try_read_exact(&mut buf).unwrap();
        assert_eq!(size, 3);
        assert_eq!(buf, [0_u8, 1, 2]);

        let size = reader.try_read_exact(&mut buf).unwrap();
        assert_eq!(size, 2);
        assert_eq!(&buf[..2], [3_u8, 4]);

        let size = reader.try_read_exact(&mut buf).unwrap();
        assert_eq!(size, 0);
    }
}