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
use std::{future::Future, pin::Pin};

use crate::{
    AsyncFile, ByteSource, Bytes, FileErr, FileId, FileReader, FileReaderFuture, FileSource,
    FileSourceFuture, ReadFrom,
};
use sea_streamer_types::{export::futures::FutureExt, SeqPos};

/// A runtime adapter of `FileReader` and `FileSource`,
/// also able to switch between the two mode of operations dynamically.
pub enum DynFileSource {
    FileReader(FileReader),
    FileSource(FileSource),
    /// If you encounter this, it's a programming mistake
    Dead,
}

pub enum FileSourceType {
    FileReader,
    FileSource,
}

pub enum DynReadFuture<'a> {
    FileReader(FileReaderFuture<'a>),
    FileSource(FileSourceFuture<'a>),
}

impl DynFileSource {
    pub async fn new(file_id: FileId, stype: FileSourceType) -> Result<Self, FileErr> {
        match stype {
            FileSourceType::FileReader => Ok(Self::FileReader(FileReader::new(file_id).await?)),
            FileSourceType::FileSource => Ok(Self::FileSource(
                FileSource::new(file_id, ReadFrom::Beginning).await?,
            )),
        }
    }

    pub async fn seek(&mut self, to: SeqPos) -> Result<u64, FileErr> {
        match self {
            Self::FileReader(file) => file.seek(to).await,
            Self::FileSource(file) => file.seek(to).await,
            Self::Dead => panic!("DynFileSource: Dead"),
        }
    }

    pub fn source_type(&self) -> FileSourceType {
        match self {
            Self::FileReader(_) => FileSourceType::FileReader,
            Self::FileSource(_) => FileSourceType::FileSource,
            Self::Dead => panic!("DynFileSource: Dead"),
        }
    }

    /// Switch to a different mode of operation.
    ///
    /// Warning: This future must not be canceled.
    pub async fn switch_to(self, stype: FileSourceType) -> Result<Self, FileErr> {
        match (self, stype) {
            (Self::Dead, _) => panic!("DynFileSource: Dead"),
            (Self::FileReader(file), FileSourceType::FileSource) => {
                let (file, offset, buffer) = file.end();
                Ok(Self::FileSource(FileSource::new_with(
                    file, offset, buffer,
                )?))
            }
            (Self::FileSource(mut src), FileSourceType::FileReader) => {
                let (file, _, _, buffer) = src.end().await;
                Ok(Self::FileReader(FileReader::new_with(
                    file,
                    src.offset(),
                    buffer,
                )?))
            }
            (myself, _) => Ok(myself),
        }
    }

    pub async fn end(self) -> AsyncFile {
        match self {
            Self::Dead => panic!("DynFileSource: Dead"),
            Self::FileReader(file) => {
                let (file, _, _) = file.end();
                file
            }
            Self::FileSource(mut src) => {
                let (file, _, _, _) = src.end().await;
                file
            }
        }
    }

    #[inline]
    pub fn offset(&self) -> u64 {
        match self {
            Self::FileReader(file) => file.offset(),
            Self::FileSource(file) => file.offset(),
            Self::Dead => panic!("DynFileSource: Dead"),
        }
    }

    #[inline]
    pub fn file_size(&self) -> u64 {
        match self {
            Self::FileReader(file) => file.file_size(),
            Self::FileSource(file) => file.file_size(),
            Self::Dead => panic!("DynFileSource: Dead"),
        }
    }

    #[inline]
    pub(crate) async fn resize(&mut self) -> Result<u64, FileErr> {
        match self {
            Self::FileReader(file) => file.resize().await,
            Self::FileSource(_) => panic!("DynFileSource: FileSource cannot be resized"),
            Self::Dead => panic!("DynFileSource: Dead"),
        }
    }

    pub fn is_dead(&self) -> bool {
        matches!(self, Self::Dead)
    }
}

impl ByteSource for DynFileSource {
    type Future<'a> = DynReadFuture<'a>;

    fn request_bytes(&mut self, size: usize) -> Self::Future<'_> {
        match self {
            Self::FileReader(file) => DynReadFuture::FileReader(file.request_bytes(size)),
            Self::FileSource(file) => DynReadFuture::FileSource(file.request_bytes(size)),
            Self::Dead => panic!("DynFileSource: Dead"),
        }
    }
}

impl<'a> Future for DynReadFuture<'a> {
    type Output = Result<Bytes, FileErr>;

    fn poll(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        use std::task::Poll::{Pending, Ready};

        match Pin::into_inner(self) {
            Self::FileReader(fut) => match Pin::new(fut).poll_unpin(cx) {
                Ready(res) => Ready(res),
                Pending => Pending,
            },
            Self::FileSource(fut) => match Pin::new(fut).poll_unpin(cx) {
                Ready(res) => Ready(res),
                Pending => Pending,
            },
        }
    }
}