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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{
    any::Any,
    io::{Read, Seek},
};

use crate::{prelude::*, subclass::prelude::*, InputStream};

mod imp {
    use std::cell::RefCell;

    use super::*;

    pub(super) enum Reader {
        Read(AnyReader),
        ReadSeek(AnyReader),
    }

    #[derive(Default)]
    pub struct ReadInputStream {
        pub(super) read: RefCell<Option<Reader>>,
    }

    #[glib::object_subclass]
    impl ObjectSubclass for ReadInputStream {
        const NAME: &'static str = "ReadInputStream";
        type Type = super::ReadInputStream;
        type ParentType = InputStream;
        type Interfaces = (crate::Seekable,);
    }

    impl ObjectImpl for ReadInputStream {}

    impl InputStreamImpl for ReadInputStream {
        fn read(
            &self,
            buffer: &mut [u8],
            _cancellable: Option<&crate::Cancellable>,
        ) -> Result<usize, glib::Error> {
            let mut read = self.read.borrow_mut();
            let read = match *read {
                None => {
                    return Err(glib::Error::new(
                        crate::IOErrorEnum::Closed,
                        "Already closed",
                    ));
                }
                Some(Reader::Read(ref mut read)) => read,
                Some(Reader::ReadSeek(ref mut read)) => read,
            };

            loop {
                match std_error_to_gio_error(read.read(buffer)) {
                    None => continue,
                    Some(res) => return res,
                }
            }
        }

        fn close(&self, _cancellable: Option<&crate::Cancellable>) -> Result<(), glib::Error> {
            let _ = self.read.take();
            Ok(())
        }
    }

    impl SeekableImpl for ReadInputStream {
        fn tell(&self) -> i64 {
            // XXX: stream_position is not stable yet
            // let mut read = self.read.borrow_mut();
            // match *read {
            //     Some(Reader::ReadSeek(ref mut read)) => {
            //         read.stream_position().map(|pos| pos as i64).unwrap_or(-1)
            //     },
            //     _ => -1,
            // };
            -1
        }

        fn can_seek(&self) -> bool {
            let read = self.read.borrow();
            matches!(*read, Some(Reader::ReadSeek(_)))
        }

        fn seek(
            &self,
            offset: i64,
            type_: glib::SeekType,
            _cancellable: Option<&crate::Cancellable>,
        ) -> Result<(), glib::Error> {
            use std::io::SeekFrom;

            let mut read = self.read.borrow_mut();
            match *read {
                Some(Reader::ReadSeek(ref mut read)) => {
                    let pos = match type_ {
                        glib::SeekType::Cur => SeekFrom::Current(offset),
                        glib::SeekType::Set => {
                            if offset < 0 {
                                return Err(glib::Error::new(
                                    crate::IOErrorEnum::InvalidArgument,
                                    "Invalid Argument",
                                ));
                            } else {
                                SeekFrom::Start(offset as u64)
                            }
                        }
                        glib::SeekType::End => SeekFrom::End(offset),
                        _ => unimplemented!(),
                    };

                    loop {
                        match std_error_to_gio_error(read.seek(pos)) {
                            None => continue,
                            Some(res) => return res.map(|_| ()),
                        }
                    }
                }
                _ => Err(glib::Error::new(
                    crate::IOErrorEnum::NotSupported,
                    "Truncating not supported",
                )),
            }
        }

        fn can_truncate(&self) -> bool {
            false
        }

        fn truncate(
            &self,
            _offset: i64,
            _cancellable: Option<&crate::Cancellable>,
        ) -> Result<(), glib::Error> {
            Err(glib::Error::new(
                crate::IOErrorEnum::NotSupported,
                "Truncating not supported",
            ))
        }
    }
}

glib::wrapper! {
    pub struct ReadInputStream(ObjectSubclass<imp::ReadInputStream>) @extends crate::InputStream, @implements crate::Seekable;
}

impl ReadInputStream {
    pub fn new<R: Read + Send + 'static>(read: R) -> ReadInputStream {
        let obj: Self = glib::Object::new();

        *obj.imp().read.borrow_mut() = Some(imp::Reader::Read(AnyReader::new(read)));

        obj
    }

    pub fn new_seekable<R: Read + Seek + Send + 'static>(read: R) -> ReadInputStream {
        let obj: Self = glib::Object::new();

        *obj.imp().read.borrow_mut() = Some(imp::Reader::ReadSeek(AnyReader::new_seekable(read)));

        obj
    }

    pub fn close_and_take(&self) -> Box<dyn Any + Send + 'static> {
        let inner = self.imp().read.take();

        let ret = match inner {
            None => {
                panic!("Stream already closed or inner taken");
            }
            Some(imp::Reader::Read(read)) => read.reader,
            Some(imp::Reader::ReadSeek(read)) => read.reader,
        };

        let _ = self.close(crate::Cancellable::NONE);

        match ret {
            AnyOrPanic::Any(r) => r,
            AnyOrPanic::Panic(p) => std::panic::resume_unwind(p),
        }
    }
}

enum AnyOrPanic {
    Any(Box<dyn Any + Send + 'static>),
    Panic(Box<dyn Any + Send + 'static>),
}

// Helper struct for dynamically dispatching to any kind of Reader and
// catching panics along the way
struct AnyReader {
    reader: AnyOrPanic,
    read_fn: fn(s: &mut AnyReader, buffer: &mut [u8]) -> std::io::Result<usize>,
    seek_fn: Option<fn(s: &mut AnyReader, pos: std::io::SeekFrom) -> std::io::Result<u64>>,
}

impl AnyReader {
    fn new<R: Read + Any + Send + 'static>(r: R) -> Self {
        Self {
            reader: AnyOrPanic::Any(Box::new(r)),
            read_fn: Self::read_fn::<R>,
            seek_fn: None,
        }
    }

    fn new_seekable<R: Read + Seek + Any + Send + 'static>(r: R) -> Self {
        Self {
            reader: AnyOrPanic::Any(Box::new(r)),
            read_fn: Self::read_fn::<R>,
            seek_fn: Some(Self::seek_fn::<R>),
        }
    }

    fn read_fn<R: Read + 'static>(s: &mut AnyReader, buffer: &mut [u8]) -> std::io::Result<usize> {
        s.with_inner(|r: &mut R| r.read(buffer))
    }

    fn seek_fn<R: Seek + 'static>(
        s: &mut AnyReader,
        pos: std::io::SeekFrom,
    ) -> std::io::Result<u64> {
        s.with_inner(|r: &mut R| r.seek(pos))
    }

    fn with_inner<R: 'static, T, F: FnOnce(&mut R) -> std::io::Result<T>>(
        &mut self,
        func: F,
    ) -> std::io::Result<T> {
        match self.reader {
            AnyOrPanic::Any(ref mut reader) => {
                let r = reader.downcast_mut::<R>().unwrap();
                match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| func(r))) {
                    Ok(res) => res,
                    Err(panic) => {
                        self.reader = AnyOrPanic::Panic(panic);
                        Err(std::io::Error::new(std::io::ErrorKind::Other, "Panicked"))
                    }
                }
            }
            AnyOrPanic::Panic(_) => Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                "Panicked before",
            )),
        }
    }

    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
        (self.read_fn)(self, buffer)
    }

    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        if let Some(ref seek_fn) = self.seek_fn {
            seek_fn(self, pos)
        } else {
            unreachable!()
        }
    }
}

pub(crate) fn std_error_to_gio_error<T>(
    res: Result<T, std::io::Error>,
) -> Option<Result<T, glib::Error>> {
    match res {
        Ok(res) => Some(Ok(res)),
        Err(err) => {
            use std::io::ErrorKind;

            #[allow(clippy::wildcard_in_or_patterns)]
            match err.kind() {
                ErrorKind::NotFound => Some(Err(glib::Error::new(
                    crate::IOErrorEnum::NotFound,
                    "Not Found",
                ))),
                ErrorKind::PermissionDenied => Some(Err(glib::Error::new(
                    crate::IOErrorEnum::PermissionDenied,
                    "Permission Denied",
                ))),
                ErrorKind::ConnectionRefused => Some(Err(glib::Error::new(
                    crate::IOErrorEnum::ConnectionRefused,
                    "Connection Refused",
                ))),
                ErrorKind::ConnectionReset
                | ErrorKind::ConnectionAborted
                | ErrorKind::NotConnected => Some(Err(glib::Error::new(
                    crate::IOErrorEnum::NotConnected,
                    "Connection Reset",
                ))),
                ErrorKind::AddrInUse | ErrorKind::AddrNotAvailable => Some(Err(glib::Error::new(
                    crate::IOErrorEnum::AddressInUse,
                    "Address In Use",
                ))),
                ErrorKind::BrokenPipe => Some(Err(glib::Error::new(
                    crate::IOErrorEnum::BrokenPipe,
                    "Broken Pipe",
                ))),
                ErrorKind::AlreadyExists => Some(Err(glib::Error::new(
                    crate::IOErrorEnum::Exists,
                    "Already Exists",
                ))),
                ErrorKind::WouldBlock => Some(Err(glib::Error::new(
                    crate::IOErrorEnum::WouldBlock,
                    "Would Block",
                ))),
                ErrorKind::InvalidInput | ErrorKind::InvalidData => Some(Err(glib::Error::new(
                    crate::IOErrorEnum::InvalidData,
                    "Invalid Input",
                ))),
                ErrorKind::TimedOut => Some(Err(glib::Error::new(
                    crate::IOErrorEnum::TimedOut,
                    "Timed Out",
                ))),
                ErrorKind::Interrupted => None,
                ErrorKind::UnexpectedEof => Some(Err(glib::Error::new(
                    crate::IOErrorEnum::Closed,
                    "Unexpected Eof",
                ))),
                ErrorKind::WriteZero | _ => Some(Err(glib::Error::new(
                    crate::IOErrorEnum::Failed,
                    format!("Unknown error: {err:?}").as_str(),
                ))),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use super::*;

    #[test]
    fn test_read() {
        let cursor = Cursor::new(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
        let stream = ReadInputStream::new(cursor);

        let mut buf = [0u8; 1024];
        assert_eq!(stream.read(&mut buf[..], crate::Cancellable::NONE), Ok(10));
        assert_eq!(&buf[..10], &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10][..]);

        assert_eq!(stream.read(&mut buf[..], crate::Cancellable::NONE), Ok(0));

        let inner = stream.close_and_take();
        assert!(inner.is::<Cursor<Vec<u8>>>());
        let inner = inner.downcast_ref::<Cursor<Vec<u8>>>().unwrap();
        assert_eq!(inner.get_ref(), &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    }

    #[test]
    fn test_read_seek() {
        let cursor = Cursor::new(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
        let stream = ReadInputStream::new_seekable(cursor);

        let mut buf = [0u8; 1024];
        assert_eq!(stream.read(&mut buf[..], crate::Cancellable::NONE), Ok(10));
        assert_eq!(&buf[..10], &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10][..]);

        assert_eq!(stream.read(&mut buf[..], crate::Cancellable::NONE), Ok(0));

        assert!(stream.can_seek());
        assert_eq!(
            stream.seek(0, glib::SeekType::Set, crate::Cancellable::NONE),
            Ok(())
        );
        assert_eq!(stream.read(&mut buf[..], crate::Cancellable::NONE), Ok(10));
        assert_eq!(&buf[..10], &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10][..]);

        let inner = stream.close_and_take();
        assert!(inner.is::<Cursor<Vec<u8>>>());
        let inner = inner.downcast_ref::<Cursor<Vec<u8>>>().unwrap();
        assert_eq!(inner.get_ref(), &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    }
}