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
// TODO: Use WTF-8 rather than UTF-16

#![allow(clippy::type_complexity)]

mod local;

use async_trait::async_trait;
use futures::{future::BoxFuture, ready};
use pin_project::pin_project;
use std::{
	convert::TryFrom, error::Error, ffi, fmt, future::Future, io, pin::Pin, sync::Arc, task::{Context, Poll}
};
use widestring::U16String;

use crate::pool::ProcessSend;

pub use local::LocalFile;

const PAGE_SIZE: usize = 10 * 1024 * 1024; // `Reader` reads this many bytes at a time

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct OsString {
	buf: U16String,
}
impl OsString {
	pub fn new() -> Self {
		Self {
			buf: U16String::new(),
		}
	}
	pub fn to_string_lossy(&self) -> String {
		self.buf.to_string_lossy()
	}
	pub fn display<'a>(&'a self) -> impl fmt::Display + 'a {
		struct Display<'a>(&'a OsString);
		impl<'a> fmt::Display for Display<'a> {
			fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				self.0.to_string_lossy().fmt(f)
			}
		}
		Display(self)
	}
}
impl From<Vec<u8>> for OsString {
	fn from(from: Vec<u8>) -> Self {
		Self {
			buf: String::from_utf8(from)
				.expect("Not yet imlemented: Handling non-UTF-8")
				.into(),
		} // TODO
	}
}
impl From<String> for OsString {
	fn from(from: String) -> Self {
		Self { buf: from.into() }
	}
}
impl From<&str> for OsString {
	fn from(from: &str) -> Self {
		Self {
			buf: U16String::from_str(from),
		}
	}
}
impl From<ffi::OsString> for OsString {
	fn from(from: ffi::OsString) -> Self {
		Self {
			buf: U16String::from_os_str(&from),
		}
	}
}
impl From<&ffi::OsStr> for OsString {
	fn from(from: &ffi::OsStr) -> Self {
		Self {
			buf: U16String::from_os_str(from),
		}
	}
}
pub struct InvalidOsString;
impl TryFrom<OsString> for ffi::OsString {
	type Error = InvalidOsString;

	fn try_from(from: OsString) -> Result<Self, Self::Error> {
		Ok(from.buf.to_os_string()) // TODO: this is lossy but it should error
	}
}
impl PartialEq<Vec<u8>> for OsString {
	fn eq(&self, other: &Vec<u8>) -> bool {
		self == &OsString::from(other.clone())
	}
}
impl PartialEq<String> for OsString {
	fn eq(&self, other: &String) -> bool {
		self == &OsString::from(other.clone())
	}
}
impl PartialEq<str> for OsString {
	fn eq(&self, other: &str) -> bool {
		self == &OsString::from(other)
	}
}
impl PartialEq<ffi::OsString> for OsString {
	fn eq(&self, other: &ffi::OsString) -> bool {
		self == &OsString::from(other.clone())
	}
}
impl PartialEq<ffi::OsStr> for OsString {
	fn eq(&self, other: &ffi::OsStr) -> bool {
		self == &OsString::from(other)
	}
}
impl fmt::Debug for OsString {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", self.display())
	}
}

#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct PathBuf {
	components: Vec<OsString>,
	file_name: Option<OsString>,
}
impl PathBuf {
	pub fn new() -> Self {
		Self {
			components: Vec::new(),
			file_name: None,
		}
	}
	pub fn push<S>(&mut self, component: S)
	where
		S: Into<OsString>,
	{
		assert!(self.file_name.is_none());
		self.components.push(component.into());
	}
	pub fn pop(&mut self) -> Option<OsString> {
		assert!(self.file_name.is_none());
		self.components.pop()
	}
	pub fn last(&self) -> Option<&OsString> {
		assert!(self.file_name.is_none());
		self.components.last()
	}
	pub fn set_file_name<S>(&mut self, file_name: Option<S>)
	where
		S: Into<OsString>,
	{
		self.file_name = file_name.map(Into::into);
	}
	pub fn is_file(&self) -> bool {
		self.file_name.is_some()
	}
	pub fn file_name(&self) -> Option<&OsString> {
		self.file_name.as_ref()
	}
	pub fn depth(&self) -> usize {
		self.components.len()
	}
	pub fn iter<'a>(&'a self) -> impl Iterator<Item = &OsString> + 'a {
		self.components.iter()
	}
	pub fn display<'a>(&'a self) -> impl fmt::Display + 'a {
		struct Display<'a>(&'a PathBuf);
		impl<'a> fmt::Display for Display<'a> {
			fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
				let mut res: fmt::Result = self
					.0
					.iter()
					.map(|component| write!(f, "{}/", component.to_string_lossy()))
					.collect();
				if let Some(file_name) = self.0.file_name() {
					res = res.and_then(|()| write!(f, "{}", file_name.to_string_lossy()));
				}
				res
			}
		}
		Display(self)
	}
}
impl fmt::Debug for PathBuf {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}", self.display())
	}
}

#[async_trait(?Send)]
pub trait Directory: File {
	async fn partitions_filter<F>(
		self, f: F,
	) -> Result<Vec<<Self as File>::Partition>, <Self as File>::Error>
	where
		F: FnMut(&PathBuf) -> bool;
}

#[async_trait(?Send)]
pub trait File {
	type Partition: Partition;
	type Error: Error + Clone + PartialEq + 'static;

	async fn partitions(self) -> Result<Vec<Self::Partition>, Self::Error>;
}
#[async_trait(?Send)]
pub trait Partition: Clone + fmt::Debug + ProcessSend + 'static {
	type Page: Page;
	type Error: Error + Clone + PartialEq + ProcessSend + 'static;

	async fn pages(self) -> Result<Vec<Self::Page>, Self::Error>;
}
#[allow(clippy::len_without_is_empty)]
#[async_trait]
pub trait Page: Send {
	type Error: Error + Clone + PartialEq + Into<io::Error> + ProcessSend + 'static;

	fn len(&self) -> u64;
	fn set_len(&self, len: u64) -> Result<(), Self::Error>;
	fn read(&self, offset: u64, len: usize) -> BoxFuture<'static, Result<Box<[u8]>, Self::Error>>;
	fn write(&self, offset: u64, buf: Box<[u8]>) -> BoxFuture<'static, Result<(), Self::Error>>;

	fn reader(self) -> Reader<Self>
	where
		Self: Sized,
	{
		Reader::new(self)
	}
}

#[async_trait]
impl<T: ?Sized> Page for &T
where
	T: Page + Sync,
{
	type Error = T::Error;

	fn len(&self) -> u64 {
		(**self).len()
	}
	fn set_len(&self, len: u64) -> Result<(), Self::Error> {
		(**self).set_len(len)
	}
	fn read(&self, offset: u64, len: usize) -> BoxFuture<'static, Result<Box<[u8]>, Self::Error>> {
		(**self).read(offset, len)
	}
	fn write(&self, offset: u64, buf: Box<[u8]>) -> BoxFuture<'static, Result<(), Self::Error>> {
		(**self).write(offset, buf)
	}
}
#[async_trait]
impl<T: ?Sized> Page for Arc<T>
where
	T: Page + Sync,
{
	type Error = T::Error;

	fn len(&self) -> u64 {
		(**self).len()
	}
	fn set_len(&self, len: u64) -> Result<(), Self::Error> {
		(**self).set_len(len)
	}
	fn read(&self, offset: u64, len: usize) -> BoxFuture<'static, Result<Box<[u8]>, Self::Error>> {
		(**self).read(offset, len)
	}
	fn write(&self, offset: u64, buf: Box<[u8]>) -> BoxFuture<'static, Result<(), Self::Error>> {
		(**self).write(offset, buf)
	}
}

#[pin_project]
pub struct Reader<P>
where
	P: Page,
{
	#[pin]
	page: P,
	#[pin]
	pending: Option<BoxFuture<'static, Result<Box<[u8]>, P::Error>>>,
	pending_len: Option<usize>,
	offset: u64,
}
#[allow(clippy::len_without_is_empty)]
impl<P> Reader<P>
where
	P: Page,
{
	fn new(page: P) -> Self {
		Self {
			page,
			pending: None,
			pending_len: None,
			offset: 0,
		}
	}
	pub fn len(&self) -> u64 {
		self.page.len()
	}
}
impl<P> futures::io::AsyncRead for Reader<P>
where
	P: Page,
{
	fn poll_read(
		self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8],
	) -> Poll<io::Result<usize>> {
		let mut self_ = self.project();
		if self_.pending.is_none() {
			let start = *self_.offset;
			let len = usize::try_from((self_.page.len() - start).min(buf.len() as u64)).unwrap();
			let len = len.min(PAGE_SIZE);
			let pending = self_.page.read(start, len);
			*self_.pending = Some(pending);
			*self_.pending_len = Some(len);
		}
		let ret = ready!(self_.pending.as_mut().as_pin_mut().unwrap().poll(cx));
		*self_.pending = None;
		let len = self_.pending_len.take().unwrap();
		let ret = ret
			.map(|buf_| {
				buf[..len].copy_from_slice(&buf_);
				len
			})
			.map_err(Into::into);
		*self_.offset += u64::try_from(len).unwrap();
		Poll::Ready(ret)
	}
}

// impl<P> io::Seek for Reader<P>
// where
// 	P: Page,
// {
// 	fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
// 		let len = self.page.len();
// 		self.offset = match pos {
// 			io::SeekFrom::Start(n) => Some(n),
// 			io::SeekFrom::End(n) if n >= 0 => len.checked_add(u64::try_from(n).unwrap()),
// 			io::SeekFrom::End(n) => {
// 				let n = u64::try_from(-(n + 1)).unwrap() + 1;
// 				len.checked_sub(n)
// 			}
// 			io::SeekFrom::Current(n) if n >= 0 => {
// 				self.offset.checked_add(u64::try_from(n).unwrap())
// 			}
// 			io::SeekFrom::Current(n) => {
// 				let n = u64::try_from(-(n + 1)).unwrap() + 1;
// 				self.offset.checked_sub(n)
// 			}
// 		}
// 		.ok_or_else(|| {
// 			io::Error::new(
// 				io::ErrorKind::InvalidInput,
// 				"invalid seek to a negative or overflowing position",
// 			)
// 		})?;
// 		Ok(self.offset)
// 	}
// }