forked from developmentseed/async-tiff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreader.rs
433 lines (376 loc) · 14.1 KB
/
reader.rs
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
//! Abstractions for network reading.
use std::fmt::Debug;
use std::io::Read;
use std::ops::Range;
use std::sync::Arc;
use byteorder::{BigEndian, LittleEndian, ReadBytesExt};
use bytes::buf::Reader;
use bytes::{Buf, Bytes};
use futures::future::{BoxFuture, FutureExt, TryFutureExt};
#[cfg(feature = "object_store")]
use object_store::ObjectStore;
use crate::error::{AsyncTiffError, AsyncTiffResult};
/// The asynchronous interface used to read COG files
///
/// This was derived from the Parquet
/// [`AsyncFileReader`](https://docs.rs/parquet/latest/parquet/arrow/async_reader/trait.AsyncFileReader.html)
///
/// Notes:
///
/// 1. There is a default implementation for types that implement [`tokio::io::AsyncRead`]
/// and [`tokio::io::AsyncSeek`], for example [`tokio::fs::File`].
///
/// 2. [`ObjectReader`], available when the `object_store` crate feature
/// is enabled, implements this interface for [`ObjectStore`].
///
/// [`ObjectStore`]: object_store::ObjectStore
///
/// [`tokio::fs::File`]: https://docs.rs/tokio/latest/tokio/fs/struct.File.html
pub trait AsyncFileReader: Debug + Send + Sync {
/// Retrieve the bytes in `range`
fn get_bytes(&self, range: Range<u64>) -> BoxFuture<'_, AsyncTiffResult<Bytes>>;
/// Retrieve multiple byte ranges. The default implementation will call `get_bytes`
/// sequentially
fn get_byte_ranges(
&self,
ranges: Vec<Range<u64>>,
) -> BoxFuture<'_, AsyncTiffResult<Vec<Bytes>>> {
async move {
let mut result = Vec::with_capacity(ranges.len());
for range in ranges.into_iter() {
let data = self.get_bytes(range).await?;
result.push(data);
}
Ok(result)
}
.boxed()
}
}
/// This allows Box<dyn AsyncFileReader + '_> to be used as an AsyncFileReader,
impl AsyncFileReader for Box<dyn AsyncFileReader + '_> {
fn get_bytes(&self, range: Range<u64>) -> BoxFuture<'_, AsyncTiffResult<Bytes>> {
self.as_ref().get_bytes(range)
}
fn get_byte_ranges(
&self,
ranges: Vec<Range<u64>>,
) -> BoxFuture<'_, AsyncTiffResult<Vec<Bytes>>> {
self.as_ref().get_byte_ranges(ranges)
}
}
// #[cfg(feature = "tokio")]
// impl<T: tokio::io::AsyncRead + tokio::io::AsyncSeek + Unpin + Debug + Send + Sync> AsyncFileReader
// for T
// {
// fn get_bytes(&self, range: Range<u64>) -> BoxFuture<'_, AsyncTiffResult<Bytes>> {
// use tokio::io::{AsyncReadExt, AsyncSeekExt};
// async move {
// self.seek(std::io::SeekFrom::Start(range.start)).await?;
// let to_read = (range.end - range.start).try_into().unwrap();
// let mut buffer = Vec::with_capacity(to_read);
// let read = self.take(to_read as u64).read_to_end(&mut buffer).await?;
// if read != to_read {
// return Err(AsyncTiffError::EndOfFile(to_read, read));
// }
// Ok(buffer.into())
// }
// .boxed()
// }
// }
/// An AsyncFileReader that reads from an [`ObjectStore`] instance.
#[cfg(feature = "object_store")]
#[derive(Clone, Debug)]
pub struct ObjectReader {
store: Arc<dyn ObjectStore>,
path: object_store::path::Path,
}
#[cfg(feature = "object_store")]
impl ObjectReader {
/// Creates a new [`ObjectReader`] for the provided [`ObjectStore`] and path
///
/// [`ObjectMeta`] can be obtained using [`ObjectStore::list`] or [`ObjectStore::head`]
pub fn new(store: Arc<dyn ObjectStore>, path: object_store::path::Path) -> Self {
Self { store, path }
}
}
#[cfg(feature = "object_store")]
impl AsyncFileReader for ObjectReader {
fn get_bytes(&self, range: Range<u64>) -> BoxFuture<'_, AsyncTiffResult<Bytes>> {
let range = range.start as _..range.end as _;
self.store
.get_range(&self.path, range)
.map_err(|e| e.into())
.boxed()
}
fn get_byte_ranges(&self, ranges: Vec<Range<u64>>) -> BoxFuture<'_, AsyncTiffResult<Vec<Bytes>>>
where
Self: Send,
{
let ranges = ranges
.into_iter()
.map(|r| r.start as _..r.end as _)
.collect::<Vec<_>>();
async move {
self.store
.get_ranges(&self.path, &ranges)
.await
.map_err(|e| e.into())
}
.boxed()
}
}
/// An AsyncFileReader that reads from a URL using reqwest.
#[cfg(feature = "reqwest")]
#[derive(Debug, Clone)]
pub struct ReqwestReader {
client: reqwest::Client,
url: reqwest::Url,
}
#[cfg(feature = "reqwest")]
impl ReqwestReader {
/// Construct a new ReqwestReader from a reqwest client and URL.
pub fn new(client: reqwest::Client, url: reqwest::Url) -> Self {
Self { client, url }
}
}
#[cfg(feature = "reqwest")]
impl AsyncFileReader for ReqwestReader {
fn get_bytes(&self, range: Range<u64>) -> BoxFuture<'_, AsyncTiffResult<Bytes>> {
let url = self.url.clone();
let client = self.client.clone();
// HTTP range is inclusive, so we need to subtract 1 from the end
let range = format!("bytes={}-{}", range.start, range.end - 1);
async move {
let response = client.get(url).header("Range", range).send().await?;
let bytes = response.bytes().await?;
Ok(bytes)
}
.boxed()
}
}
/// An AsyncFileReader that caches the first `prefetch` bytes of a file.
#[derive(Debug)]
pub struct PrefetchReader {
reader: Arc<dyn AsyncFileReader>,
buffer: Bytes,
}
impl PrefetchReader {
/// Construct a new PrefetchReader, catching the first `prefetch` bytes of the file.
pub async fn new(reader: Arc<dyn AsyncFileReader>, prefetch: u64) -> AsyncTiffResult<Self> {
let buffer = reader.get_bytes(0..prefetch).await?;
Ok(Self { reader, buffer })
}
}
impl AsyncFileReader for PrefetchReader {
fn get_bytes(&self, range: Range<u64>) -> BoxFuture<'_, AsyncTiffResult<Bytes>> {
if range.start < self.buffer.len() as _ {
if range.end < self.buffer.len() as _ {
let usize_range = range.start as usize..range.end as usize;
let result = self.buffer.slice(usize_range);
async { Ok(result) }.boxed()
} else {
// TODO: reuse partial internal buffer
self.reader.get_bytes(range)
}
} else {
self.reader.get_bytes(range)
}
}
fn get_byte_ranges(&self, ranges: Vec<Range<u64>>) -> BoxFuture<'_, AsyncTiffResult<Vec<Bytes>>>
where
Self: Send,
{
// In practice, get_byte_ranges is only used for fetching tiles, which are unlikely to
// overlap a metadata prefetch.
self.reader.get_byte_ranges(ranges)
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum Endianness {
LittleEndian,
BigEndian,
}
/// A wrapper around an [ObjectStore] that provides a seek-oriented interface
// TODO: in the future add buffering to this
#[derive(Debug)]
pub(crate) struct AsyncCursor {
reader: Arc<dyn AsyncFileReader>,
offset: u64,
endianness: Endianness,
}
impl AsyncCursor {
/// Create a new AsyncCursor from a reader and endianness.
pub(crate) fn new(reader: Arc<dyn AsyncFileReader>, endianness: Endianness) -> Self {
Self {
reader,
offset: 0,
endianness,
}
}
/// Create a new AsyncCursor for a TIFF file, automatically inferring endianness from the first
/// two bytes.
pub(crate) async fn try_open_tiff(reader: Arc<dyn AsyncFileReader>) -> AsyncTiffResult<Self> {
// Initialize with little endianness and then set later
let mut cursor = Self::new(reader, Endianness::LittleEndian);
let magic_bytes = cursor.read(2).await?;
let magic_bytes = magic_bytes.as_ref();
// Should be b"II" for little endian or b"MM" for big endian
if magic_bytes == Bytes::from_static(b"II") {
cursor.endianness = Endianness::LittleEndian;
} else if magic_bytes == Bytes::from_static(b"MM") {
cursor.endianness = Endianness::BigEndian;
} else {
return Err(AsyncTiffError::General(format!(
"unexpected magic bytes {magic_bytes:?}"
)));
};
Ok(cursor)
}
/// Consume self and return the underlying [`AsyncFileReader`].
#[allow(dead_code)]
pub(crate) fn into_inner(self) -> Arc<dyn AsyncFileReader> {
self.reader
}
/// Read the given number of bytes, advancing the internal cursor state by the same amount.
pub(crate) async fn read(&mut self, length: u64) -> AsyncTiffResult<EndianAwareReader> {
let range = self.offset as _..(self.offset + length) as _;
self.offset += length;
let bytes = self.reader.get_bytes(range).await?;
Ok(EndianAwareReader {
reader: bytes.reader(),
endianness: self.endianness,
})
}
/// Read a u8 from the cursor, advancing the internal state by 1 byte.
pub(crate) async fn read_u8(&mut self) -> AsyncTiffResult<u8> {
self.read(1).await?.read_u8()
}
/// Read a i8 from the cursor, advancing the internal state by 1 byte.
pub(crate) async fn read_i8(&mut self) -> AsyncTiffResult<i8> {
self.read(1).await?.read_i8()
}
/// Read a u16 from the cursor, advancing the internal state by 2 bytes.
pub(crate) async fn read_u16(&mut self) -> AsyncTiffResult<u16> {
self.read(2).await?.read_u16()
}
/// Read a i16 from the cursor, advancing the internal state by 2 bytes.
pub(crate) async fn read_i16(&mut self) -> AsyncTiffResult<i16> {
self.read(2).await?.read_i16()
}
/// Read a u32 from the cursor, advancing the internal state by 4 bytes.
pub(crate) async fn read_u32(&mut self) -> AsyncTiffResult<u32> {
self.read(4).await?.read_u32()
}
/// Read a i32 from the cursor, advancing the internal state by 4 bytes.
pub(crate) async fn read_i32(&mut self) -> AsyncTiffResult<i32> {
self.read(4).await?.read_i32()
}
/// Read a u64 from the cursor, advancing the internal state by 8 bytes.
pub(crate) async fn read_u64(&mut self) -> AsyncTiffResult<u64> {
self.read(8).await?.read_u64()
}
/// Read a i64 from the cursor, advancing the internal state by 8 bytes.
pub(crate) async fn read_i64(&mut self) -> AsyncTiffResult<i64> {
self.read(8).await?.read_i64()
}
pub(crate) async fn read_f32(&mut self) -> AsyncTiffResult<f32> {
self.read(4).await?.read_f32()
}
pub(crate) async fn read_f64(&mut self) -> AsyncTiffResult<f64> {
self.read(8).await?.read_f64()
}
#[allow(dead_code)]
pub(crate) fn reader(&self) -> &Arc<dyn AsyncFileReader> {
&self.reader
}
#[allow(dead_code)]
pub(crate) fn endianness(&self) -> Endianness {
self.endianness
}
/// Advance cursor position by a set amount
pub(crate) fn advance(&mut self, amount: u64) {
self.offset += amount;
}
pub(crate) fn seek(&mut self, offset: u64) {
self.offset = offset;
}
pub(crate) fn position(&self) -> u64 {
self.offset
}
}
pub(crate) struct EndianAwareReader {
reader: Reader<Bytes>,
endianness: Endianness,
}
impl EndianAwareReader {
/// Read a u8 from the cursor, advancing the internal state by 1 byte.
pub(crate) fn read_u8(&mut self) -> AsyncTiffResult<u8> {
Ok(self.reader.read_u8()?)
}
/// Read a i8 from the cursor, advancing the internal state by 1 byte.
pub(crate) fn read_i8(&mut self) -> AsyncTiffResult<i8> {
Ok(self.reader.read_i8()?)
}
pub(crate) fn read_u16(&mut self) -> AsyncTiffResult<u16> {
match self.endianness {
Endianness::LittleEndian => Ok(self.reader.read_u16::<LittleEndian>()?),
Endianness::BigEndian => Ok(self.reader.read_u16::<BigEndian>()?),
}
}
pub(crate) fn read_i16(&mut self) -> AsyncTiffResult<i16> {
match self.endianness {
Endianness::LittleEndian => Ok(self.reader.read_i16::<LittleEndian>()?),
Endianness::BigEndian => Ok(self.reader.read_i16::<BigEndian>()?),
}
}
pub(crate) fn read_u32(&mut self) -> AsyncTiffResult<u32> {
match self.endianness {
Endianness::LittleEndian => Ok(self.reader.read_u32::<LittleEndian>()?),
Endianness::BigEndian => Ok(self.reader.read_u32::<BigEndian>()?),
}
}
pub(crate) fn read_i32(&mut self) -> AsyncTiffResult<i32> {
match self.endianness {
Endianness::LittleEndian => Ok(self.reader.read_i32::<LittleEndian>()?),
Endianness::BigEndian => Ok(self.reader.read_i32::<BigEndian>()?),
}
}
pub(crate) fn read_u64(&mut self) -> AsyncTiffResult<u64> {
match self.endianness {
Endianness::LittleEndian => Ok(self.reader.read_u64::<LittleEndian>()?),
Endianness::BigEndian => Ok(self.reader.read_u64::<BigEndian>()?),
}
}
pub(crate) fn read_i64(&mut self) -> AsyncTiffResult<i64> {
match self.endianness {
Endianness::LittleEndian => Ok(self.reader.read_i64::<LittleEndian>()?),
Endianness::BigEndian => Ok(self.reader.read_i64::<BigEndian>()?),
}
}
pub(crate) fn read_f32(&mut self) -> AsyncTiffResult<f32> {
match self.endianness {
Endianness::LittleEndian => Ok(self.reader.read_f32::<LittleEndian>()?),
Endianness::BigEndian => Ok(self.reader.read_f32::<BigEndian>()?),
}
}
pub(crate) fn read_f64(&mut self) -> AsyncTiffResult<f64> {
match self.endianness {
Endianness::LittleEndian => Ok(self.reader.read_f64::<LittleEndian>()?),
Endianness::BigEndian => Ok(self.reader.read_f64::<BigEndian>()?),
}
}
#[allow(dead_code)]
pub(crate) fn into_inner(self) -> (Reader<Bytes>, Endianness) {
(self.reader, self.endianness)
}
}
impl AsRef<[u8]> for EndianAwareReader {
fn as_ref(&self) -> &[u8] {
self.reader.get_ref().as_ref()
}
}
impl Read for EndianAwareReader {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.reader.read(buf)
}
}