Initial commit
This commit is contained in:
commit
e6e61c86a8
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
/target
|
||||||
|
/Cargo.lock
|
22
Cargo.toml
Normal file
22
Cargo.toml
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
[package]
|
||||||
|
name = "tile-buffer"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Andrey Tkachenko <andrey@aidev.ru>"]
|
||||||
|
description = "Tiling Buffer useful when dealing with range requests"
|
||||||
|
keywords = ["io", "buffer", "async", "tile", "range"]
|
||||||
|
documentation = "https://docs.rs/tile-bufer"
|
||||||
|
repository = "https://github.com/andreytkachenko/tile-buffer"
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
readme = "README.md"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
arrayvec = "0.7.4"
|
||||||
|
bytes = "1.5.0"
|
||||||
|
futures = "0.3.28"
|
||||||
|
parking_lot = "0.12.1"
|
||||||
|
pin-project-lite = "0.2.13"
|
||||||
|
tokio = "1.32.0"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tokio = { version = "1.32.0", features = ["full"] }
|
201
LICENSE-APACHE
Normal file
201
LICENSE-APACHE
Normal file
@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
25
LICENSE-MIT
Normal file
25
LICENSE-MIT
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
Copyright (c) 2019 Alexey Gerasev
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any
|
||||||
|
person obtaining a copy of this software and associated
|
||||||
|
documentation files (the "Software"), to deal in the
|
||||||
|
Software without restriction, including without
|
||||||
|
limitation the rights to use, copy, modify, merge,
|
||||||
|
publish, distribute, sublicense, and/or sell copies of
|
||||||
|
the Software, and to permit persons to whom the Software
|
||||||
|
is furnished to do so, subject to the following
|
||||||
|
conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice
|
||||||
|
shall be included in all copies or substantial portions
|
||||||
|
of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||||
|
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||||
|
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||||
|
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||||
|
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||||
|
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
|
DEALINGS IN THE SOFTWARE.
|
45
examples/demo.rs
Normal file
45
examples/demo.rs
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
use std::{io, pin::Pin};
|
||||||
|
|
||||||
|
use futures::Future;
|
||||||
|
use tile_buffer::{AsyncRangeRead, TileBuffer};
|
||||||
|
use tokio::io::AsyncReadExt;
|
||||||
|
|
||||||
|
struct Test;
|
||||||
|
impl AsyncRangeRead for Test {
|
||||||
|
type Fut<'a> = Pin<Box<dyn Future<Output = io::Result<()>> + 'a>>
|
||||||
|
where Self: 'a;
|
||||||
|
|
||||||
|
fn total_size(&self) -> usize {
|
||||||
|
50630
|
||||||
|
}
|
||||||
|
|
||||||
|
fn range_read<'a>(&'a self, buf: &'a mut [u8], offset: usize) -> Self::Fut<'a> {
|
||||||
|
println!("range_read size {}; offset {}", buf.len(), offset);
|
||||||
|
|
||||||
|
Box::pin(async move {
|
||||||
|
let mut counter = offset;
|
||||||
|
|
||||||
|
for val in buf.iter_mut() {
|
||||||
|
*val = counter as _;
|
||||||
|
counter += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
let inner = Test;
|
||||||
|
|
||||||
|
let mut buff: TileBuffer<5, _> = TileBuffer::new_with_tile_size(inner, 1024);
|
||||||
|
let mut data = Vec::new();
|
||||||
|
|
||||||
|
let x = buff.read_to_end(&mut data).await.unwrap();
|
||||||
|
|
||||||
|
let valid = (0..50630u32).map(|x| x as u8).collect::<Vec<u8>>();
|
||||||
|
|
||||||
|
assert_eq!(x, 50630);
|
||||||
|
assert_eq!(data, valid);
|
||||||
|
}
|
19
src/cast.rs
Normal file
19
src/cast.rs
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
use std::mem::MaybeUninit;
|
||||||
|
|
||||||
|
pub(crate) trait CastExt<const N: usize, T>: Sized + Iterator<Item = T> {
|
||||||
|
fn cast(mut self) -> [T; N] {
|
||||||
|
let mut out: MaybeUninit<[T; N]> = MaybeUninit::uninit();
|
||||||
|
|
||||||
|
(0..N).for_each(|i| {
|
||||||
|
let item = self.next().expect("Array was not filled");
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
let slot = (out.as_mut_ptr() as *mut T).add(i);
|
||||||
|
slot.write(item);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
unsafe { out.assume_init() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<const N: usize, T, V: Sized + Iterator<Item = T>> CastExt<N, T> for V {}
|
413
src/lib.rs
Normal file
413
src/lib.rs
Normal file
@ -0,0 +1,413 @@
|
|||||||
|
mod cast;
|
||||||
|
mod range;
|
||||||
|
mod waker;
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
future::Future,
|
||||||
|
io,
|
||||||
|
pin::Pin,
|
||||||
|
sync::Arc,
|
||||||
|
task::{ready, Context, Poll, Waker},
|
||||||
|
};
|
||||||
|
|
||||||
|
use arrayvec::ArrayVec;
|
||||||
|
use tokio::io::{AsyncRead, AsyncSeek, ReadBuf};
|
||||||
|
use waker::PollPendingQueue;
|
||||||
|
|
||||||
|
pub use range::AsyncRangeRead;
|
||||||
|
|
||||||
|
use crate::cast::CastExt;
|
||||||
|
|
||||||
|
pub const DEFAULT_TILE_SIZE: usize = 4096;
|
||||||
|
pub const MAX_TILE_COUNT: usize = 1 << TILE_COUNT_BITS;
|
||||||
|
|
||||||
|
const TILE_COUNT_BITS: usize = 5;
|
||||||
|
const TILE_COUNT_MASK: usize = MAX_TILE_COUNT - 1;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// TileBuffer structure
|
||||||
|
///
|
||||||
|
pub struct TileBuffer<const N: usize, R: AsyncRangeRead + 'static> {
|
||||||
|
///
|
||||||
|
/// Array of tiles. Size of this array usually shuld not be greated than 5
|
||||||
|
tiles: [Tile<R>; N],
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Mapping between relative tile index (0..N) to global tile index (0..tile_total_count)
|
||||||
|
/// example:
|
||||||
|
/// tiles: [{index: 12, data: Some}, {index: 13, data: Some}, {index: 14, data: Some}, {index: 15, data: None}]
|
||||||
|
/// tile_mapping: [12, 13, 14, 15]
|
||||||
|
///
|
||||||
|
/// means:
|
||||||
|
/// |
|
||||||
|
/// 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16
|
||||||
|
/// == XX == ++
|
||||||
|
/// | - offset pointer
|
||||||
|
/// == - buffer loaded
|
||||||
|
/// ++ - buffer is loading now
|
||||||
|
/// XX - buffer loaded and current (relative index is 1; global index is 13)
|
||||||
|
tile_mapping: [usize; N],
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Pointer of the current tile.
|
||||||
|
/// example:
|
||||||
|
/// if tile_pointer is 0:
|
||||||
|
/// 0 1 2 3 4 5 6 7 8
|
||||||
|
/// X = = =
|
||||||
|
/// note: other tiles would load further data (good for sequential forward read)
|
||||||
|
///
|
||||||
|
/// example:
|
||||||
|
/// if tile_pointer is 2:
|
||||||
|
/// 0 1 2 3 4 5 6 7 8
|
||||||
|
/// = = X =
|
||||||
|
/// note: most of other tiles would keep past data (good for random seeking within some distance from current offset)
|
||||||
|
tile_pointer: usize,
|
||||||
|
|
||||||
|
/// Size of one tile in bytes
|
||||||
|
tile_size: usize,
|
||||||
|
|
||||||
|
/// Effectivly total_size / tile_size
|
||||||
|
tile_total_count: usize,
|
||||||
|
|
||||||
|
/// Current offset in bytes
|
||||||
|
offset: usize,
|
||||||
|
|
||||||
|
/// Total size in bytes
|
||||||
|
total_size: usize,
|
||||||
|
|
||||||
|
/// Pending to poll next indexes with waker
|
||||||
|
pending: Arc<PollPendingQueue>,
|
||||||
|
inner: R,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize, R: AsyncRangeRead> TileBuffer<N, R> {
|
||||||
|
///
|
||||||
|
pub fn new(inner: R) -> Self {
|
||||||
|
Self::new_with_tile_size_and_offset(inner, DEFAULT_TILE_SIZE, N / 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
///
|
||||||
|
pub fn new_with_tile_size(inner: R, tile_size: usize) -> Self {
|
||||||
|
Self::new_with_tile_size_and_offset(inner, tile_size, N / 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
///
|
||||||
|
pub fn new_with_tile_size_and_offset(inner: R, tile_size: usize, tile_pointer: usize) -> Self {
|
||||||
|
assert!(N <= 32, "Maximum number of tiles cannot be greater 32!");
|
||||||
|
|
||||||
|
let total_size = inner.total_size();
|
||||||
|
let tile_total_count = total_size / tile_size;
|
||||||
|
|
||||||
|
let tile_total_count = if (total_size % tile_size) > 0 {
|
||||||
|
tile_total_count + 1
|
||||||
|
} else {
|
||||||
|
tile_total_count
|
||||||
|
};
|
||||||
|
|
||||||
|
let pending = Arc::new(PollPendingQueue::default());
|
||||||
|
|
||||||
|
Self {
|
||||||
|
tiles: (0..N)
|
||||||
|
.map(|i| {
|
||||||
|
let mut tile = Tile::new(i, tile_size, waker::create_waker(pending.clone(), i));
|
||||||
|
let offset = i * tile_size;
|
||||||
|
let length = usize::min(offset + tile_size, total_size) - offset;
|
||||||
|
tile.stage(&inner, offset, length);
|
||||||
|
tile
|
||||||
|
})
|
||||||
|
.cast(),
|
||||||
|
tile_mapping: (0..N).cast(),
|
||||||
|
tile_pointer,
|
||||||
|
tile_size,
|
||||||
|
tile_total_count,
|
||||||
|
total_size,
|
||||||
|
offset: 0,
|
||||||
|
inner,
|
||||||
|
pending,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Set new offset
|
||||||
|
/// calling that method will recalculate mappings,
|
||||||
|
/// reuse already loaded tiles and stage the ones
|
||||||
|
/// which not loaded
|
||||||
|
pub fn set_offset(&mut self, new_offset: usize) {
|
||||||
|
self.offset = if new_offset > self.total_size {
|
||||||
|
self.total_size
|
||||||
|
} else {
|
||||||
|
new_offset
|
||||||
|
};
|
||||||
|
|
||||||
|
let (tile_begin, _) = self.current_tile();
|
||||||
|
let tile_end = tile_begin + N;
|
||||||
|
|
||||||
|
let mut free: ArrayVec<usize, N> = ArrayVec::new();
|
||||||
|
|
||||||
|
// clearing previous mappings
|
||||||
|
self.tile_mapping.iter_mut().for_each(|x| *x = usize::MAX);
|
||||||
|
|
||||||
|
// map existing ones
|
||||||
|
for (idx, b) in self.tiles.iter().enumerate() {
|
||||||
|
if b.index >= tile_begin && b.index < tile_end {
|
||||||
|
self.tile_mapping[b.index - tile_begin] = idx;
|
||||||
|
} else {
|
||||||
|
free.push(idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// map rest ones to free buffers and stage load appropriate ranges into those buffers
|
||||||
|
for m in 0..N {
|
||||||
|
if self.tile_mapping[m] == usize::MAX {
|
||||||
|
let bindex = free.pop().unwrap();
|
||||||
|
self.tiles[bindex].index = tile_begin + m;
|
||||||
|
self.tile_mapping[m] = bindex;
|
||||||
|
|
||||||
|
let offset = (tile_begin + m) * self.tile_size;
|
||||||
|
let length = usize::min(offset + self.tile_size, self.total_size) - offset;
|
||||||
|
|
||||||
|
self.tiles[bindex].stage(&self.inner, offset, length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_tiles(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<usize>> {
|
||||||
|
self.pending.register_waker(cx.waker());
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let Some(index) = self.pending.next_item() else {
|
||||||
|
break Poll::Pending;
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Poll::Ready(val) = self.tiles[index].poll(cx) {
|
||||||
|
break Poll::Ready(match val {
|
||||||
|
Ok(_) => Ok(index),
|
||||||
|
Err(err) => Err(err),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn current_tile(&self) -> (usize, usize) {
|
||||||
|
let curr_tile = self.offset / self.tile_size;
|
||||||
|
|
||||||
|
let tile_begin = if curr_tile < self.tile_pointer {
|
||||||
|
0
|
||||||
|
} else if curr_tile + self.tile_pointer < self.tile_total_count {
|
||||||
|
curr_tile - self.tile_pointer
|
||||||
|
} else if self.tile_total_count >= N {
|
||||||
|
self.tile_total_count - N
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
|
||||||
|
(tile_begin, curr_tile - tile_begin)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn current_buffer_read(&mut self, buf: &mut ReadBuf<'_>) -> Poll<usize> {
|
||||||
|
let (begin, current) = self.current_tile();
|
||||||
|
let current_tile_idx = begin + current;
|
||||||
|
|
||||||
|
let mapped = self.tile_mapping[current];
|
||||||
|
let tile = &mut self.tiles[mapped];
|
||||||
|
|
||||||
|
if tile.task.is_some() {
|
||||||
|
return Poll::Pending;
|
||||||
|
}
|
||||||
|
|
||||||
|
let begin_offset = current_tile_idx * self.tile_size;
|
||||||
|
let tile_offset = self.offset - begin_offset;
|
||||||
|
let tile_buffer_remaining = &tile.data[tile_offset..];
|
||||||
|
|
||||||
|
let upto = usize::min(buf.remaining(), tile_buffer_remaining.len());
|
||||||
|
|
||||||
|
buf.put_slice(&tile_buffer_remaining[..upto]);
|
||||||
|
|
||||||
|
Poll::Ready(upto)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize, R: AsyncRangeRead> AsyncRead for TileBuffer<N, R> {
|
||||||
|
fn poll_read(
|
||||||
|
self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &mut ReadBuf<'_>,
|
||||||
|
) -> Poll<io::Result<()>> {
|
||||||
|
// TODO: use pin-project eventually
|
||||||
|
let this = unsafe { self.get_unchecked_mut() };
|
||||||
|
|
||||||
|
while let Poll::Ready(val) = this.poll_tiles(cx) {
|
||||||
|
match val {
|
||||||
|
Ok(_index) => (),
|
||||||
|
Err(err) => return Poll::Ready(Err(err)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let remaining = buf.remaining();
|
||||||
|
while let Poll::Ready(read) = this.current_buffer_read(buf) {
|
||||||
|
this.set_offset(this.offset + read);
|
||||||
|
|
||||||
|
if read == 0 || buf.remaining() == 0 {
|
||||||
|
return Poll::Ready(Ok(()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if remaining != buf.remaining() {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
} else {
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<const N: usize, R: AsyncRangeRead> AsyncSeek for TileBuffer<N, R> {
|
||||||
|
fn start_seek(self: Pin<&mut Self>, position: io::SeekFrom) -> io::Result<()> {
|
||||||
|
let new_offset = match position {
|
||||||
|
io::SeekFrom::Start(offset) => offset as _,
|
||||||
|
io::SeekFrom::End(offset) => (self.total_size as i64 + offset).try_into().unwrap(),
|
||||||
|
io::SeekFrom::Current(offset) => (self.offset as i64 + offset).try_into().unwrap(),
|
||||||
|
};
|
||||||
|
|
||||||
|
unsafe { self.get_unchecked_mut() }.set_offset(new_offset);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_complete(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<u64>> {
|
||||||
|
Poll::Ready(Ok(self.offset as _))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Tile<R: AsyncRangeRead + 'static> {
|
||||||
|
index: usize,
|
||||||
|
data: Vec<u8>,
|
||||||
|
task: Option<R::Fut<'static>>,
|
||||||
|
waker: Waker,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<R: AsyncRangeRead + 'static> Tile<R> {
|
||||||
|
fn new(index: usize, tile_size: usize, waker: Waker) -> Self {
|
||||||
|
Self {
|
||||||
|
index,
|
||||||
|
data: Vec::with_capacity(tile_size),
|
||||||
|
task: None,
|
||||||
|
waker,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll(&mut self, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
if let Some(fut) = self.task.as_mut() {
|
||||||
|
let mut ctx = Context::from_waker(&self.waker);
|
||||||
|
|
||||||
|
// SAFTY:
|
||||||
|
let pinned = unsafe { Pin::new_unchecked(fut) };
|
||||||
|
ready!(pinned.poll(&mut ctx))?;
|
||||||
|
|
||||||
|
drop(self.task.take());
|
||||||
|
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
} else {
|
||||||
|
Poll::Pending
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stage(&mut self, inner: &R, offset: usize, length: usize) {
|
||||||
|
if self.data.len() != length {
|
||||||
|
self.data.resize(length, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let fut = inner.range_read(&mut self.data, offset);
|
||||||
|
|
||||||
|
// SAFTY: Safe because it will live within 'self lifetime
|
||||||
|
self.task = Some(unsafe { std::mem::transmute(fut) });
|
||||||
|
self.waker.wake_by_ref();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::{io, pin::Pin};
|
||||||
|
|
||||||
|
use super::{AsyncRangeRead, TileBuffer};
|
||||||
|
use futures::Future;
|
||||||
|
use tokio::io::{AsyncReadExt, AsyncSeekExt};
|
||||||
|
|
||||||
|
struct Test;
|
||||||
|
impl AsyncRangeRead for Test {
|
||||||
|
type Fut<'a> = Pin<Box<dyn Future<Output = io::Result<()>> + 'a>>
|
||||||
|
where Self: 'a;
|
||||||
|
|
||||||
|
fn total_size(&self) -> usize {
|
||||||
|
50630
|
||||||
|
}
|
||||||
|
|
||||||
|
fn range_read<'a>(&'a self, buf: &'a mut [u8], offset: usize) -> Self::Fut<'a> {
|
||||||
|
Box::pin(async move {
|
||||||
|
let mut counter = offset;
|
||||||
|
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||||
|
|
||||||
|
for val in buf.iter_mut() {
|
||||||
|
*val = counter as _;
|
||||||
|
counter += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn sequential_read_test() {
|
||||||
|
let inner = Test;
|
||||||
|
|
||||||
|
let mut buff: TileBuffer<5, _> = TileBuffer::new_with_tile_size(inner, 1024);
|
||||||
|
let mut data = Vec::new();
|
||||||
|
|
||||||
|
let x = buff.read_to_end(&mut data).await.unwrap();
|
||||||
|
|
||||||
|
let valid = (0..50630u32).map(|x| x as u8).collect::<Vec<u8>>();
|
||||||
|
|
||||||
|
assert_eq!(x, 50630);
|
||||||
|
assert_eq!(data, valid);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn random_read_test() {
|
||||||
|
let inner = Test;
|
||||||
|
|
||||||
|
let mut buff: TileBuffer<5, _> = TileBuffer::new_with_tile_size(inner, 1024);
|
||||||
|
let mut data = [0u8; 256];
|
||||||
|
let valid = (0u8..=255).collect::<Vec<u8>>();
|
||||||
|
|
||||||
|
let x = buff.read_exact(&mut data).await.unwrap();
|
||||||
|
assert_eq!(x, 256);
|
||||||
|
assert_eq!(data.as_slice(), valid.as_slice());
|
||||||
|
|
||||||
|
buff.seek(io::SeekFrom::Start(8448)).await.unwrap();
|
||||||
|
|
||||||
|
let x = buff.read_exact(&mut data).await.unwrap();
|
||||||
|
assert_eq!(x, 256);
|
||||||
|
assert_eq!(data.as_slice(), valid.as_slice());
|
||||||
|
|
||||||
|
buff.seek(io::SeekFrom::Start(7424)).await.unwrap();
|
||||||
|
|
||||||
|
let x = buff.read_exact(&mut data).await.unwrap();
|
||||||
|
assert_eq!(x, 256);
|
||||||
|
assert_eq!(data.as_slice(), valid.as_slice());
|
||||||
|
|
||||||
|
buff.seek(io::SeekFrom::Current(-1024)).await.unwrap();
|
||||||
|
|
||||||
|
let x = buff.read_exact(&mut data).await.unwrap();
|
||||||
|
assert_eq!(x, 256);
|
||||||
|
assert_eq!(data.as_slice(), valid.as_slice());
|
||||||
|
|
||||||
|
buff.seek(io::SeekFrom::Start(0)).await.unwrap();
|
||||||
|
buff.seek(io::SeekFrom::End(-454)).await.unwrap();
|
||||||
|
|
||||||
|
let x = buff.read_exact(&mut data).await.unwrap();
|
||||||
|
assert_eq!(x, 256);
|
||||||
|
assert_eq!(data.as_slice(), valid.as_slice());
|
||||||
|
}
|
||||||
|
}
|
15
src/range.rs
Normal file
15
src/range.rs
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
use std::io;
|
||||||
|
|
||||||
|
use futures::Future;
|
||||||
|
|
||||||
|
pub trait AsyncRangeRead {
|
||||||
|
type Fut<'a>: Future<Output = io::Result<()>>
|
||||||
|
where
|
||||||
|
Self: 'a;
|
||||||
|
|
||||||
|
/// Returns data total size
|
||||||
|
fn total_size(&self) -> usize;
|
||||||
|
|
||||||
|
/// Load `buf.len()` count of bytes from data starting from `offset` into `buf`
|
||||||
|
fn range_read<'a>(&'a self, buf: &'a mut [u8], offset: usize) -> Self::Fut<'a>;
|
||||||
|
}
|
88
src/waker.rs
Normal file
88
src/waker.rs
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
use std::{
|
||||||
|
sync::Arc,
|
||||||
|
task::{RawWaker, RawWakerVTable, Waker},
|
||||||
|
};
|
||||||
|
|
||||||
|
use arrayvec::ArrayVec;
|
||||||
|
use futures::task::AtomicWaker;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
|
||||||
|
use crate::{MAX_TILE_COUNT, TILE_COUNT_BITS, TILE_COUNT_MASK};
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
#[repr(align(32))]
|
||||||
|
pub(crate) struct PollPendingQueue {
|
||||||
|
waker: AtomicWaker,
|
||||||
|
items: Mutex<ArrayVec<usize, MAX_TILE_COUNT>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PollPendingQueue {
|
||||||
|
#[inline]
|
||||||
|
fn enqueue(&self, index: usize) {
|
||||||
|
self.items.lock().push(index);
|
||||||
|
self.waker.wake();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub(crate) fn register_waker(&self, waker: &Waker) {
|
||||||
|
self.waker.register(waker)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub(crate) fn next_item(&self) -> Option<usize> {
|
||||||
|
self.items.lock().pop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn create_waker<T>(arc: Arc<T>, index: usize) -> Waker {
|
||||||
|
assert!(index < MAX_TILE_COUNT);
|
||||||
|
assert!(std::mem::align_of::<T>() >= MAX_TILE_COUNT);
|
||||||
|
|
||||||
|
let ptr = Arc::into_raw(arc) as usize;
|
||||||
|
|
||||||
|
let raw_waker = RawWaker::new((ptr | index) as _, &TILE_BUFFER_WAKER_VTABLE);
|
||||||
|
unsafe { Waker::from_raw(raw_waker) }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn split_ptr_and_offset<T>(ptr_with_offset: *const ()) -> (Arc<T>, usize) {
|
||||||
|
// clearing last TILE_COUNT_BITS bits
|
||||||
|
let ptr = (ptr_with_offset as usize >> TILE_COUNT_BITS) << TILE_COUNT_BITS;
|
||||||
|
|
||||||
|
(
|
||||||
|
unsafe { Arc::from_raw(ptr as _) },
|
||||||
|
// masking offset bits only
|
||||||
|
ptr_with_offset as usize & TILE_COUNT_MASK,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) static TILE_BUFFER_WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new(
|
||||||
|
|ptr_with_offset| -> RawWaker {
|
||||||
|
let (arc, offset) = split_ptr_and_offset::<PollPendingQueue>(ptr_with_offset);
|
||||||
|
|
||||||
|
// cloning
|
||||||
|
let clone = arc.clone();
|
||||||
|
|
||||||
|
// forgetting original arc, to prevent drop
|
||||||
|
std::mem::forget(arc);
|
||||||
|
|
||||||
|
// making raw aligned (by 32) ptr of cloned Arc
|
||||||
|
let clone_ptr = Arc::into_raw(clone);
|
||||||
|
|
||||||
|
let res = clone_ptr as usize | offset;
|
||||||
|
|
||||||
|
RawWaker::new(res as _, &TILE_BUFFER_WAKER_VTABLE)
|
||||||
|
},
|
||||||
|
|ptr_with_offset| {
|
||||||
|
let (arc, offset) = split_ptr_and_offset::<PollPendingQueue>(ptr_with_offset);
|
||||||
|
arc.enqueue(offset);
|
||||||
|
},
|
||||||
|
|ptr_with_offset| {
|
||||||
|
let (arc, offset) = split_ptr_and_offset::<PollPendingQueue>(ptr_with_offset);
|
||||||
|
arc.enqueue(offset);
|
||||||
|
std::mem::forget(arc);
|
||||||
|
},
|
||||||
|
|ptr_with_offset| {
|
||||||
|
let (arc, _) = split_ptr_and_offset::<PollPendingQueue>(ptr_with_offset);
|
||||||
|
drop(arc)
|
||||||
|
},
|
||||||
|
);
|
Loading…
Reference in New Issue
Block a user