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
/// Module containing range mappings.
mod range;

/// Module containing in-memory IO handlers for testing.
pub mod mem_io_handle;

mod macros;
/// Module containing world implementation.
mod world;

/// Module containing tests.
#[cfg(test)]
mod tests;

use std::ops::Deref;

use async_trait::async_trait;
use futures_lite::AsyncRead;

pub use world::{iter::Iter, iter::Lazy, Chunk, Chunks, Dim, Select, World};

#[doc(hidden)]
pub use futures_lite::StreamExt;

/// Represents types stored directly in a dimensional world.
pub trait Data: Sized + Send + Sync + Unpin {
    /// Count of dimensions.
    const DIMS: usize;

    /// The current version of this data type.
    const VERSION: u32;

    /// Gets the value of required dimension.
    ///
    /// Dimension index starts from 0, which should be
    /// a unique data such as the only id.
    fn dim(&self, dim: usize) -> u64;

    /// Decode this type from given `Read` and dimensional values,
    /// in the given data version.
    fn decode<B: bytes::Buf>(version: u32, dims: &[u64], buf: B) -> std::io::Result<Self>;

    /// Encode this type into bytes buffer, in
    /// latest data version.
    ///
    /// _To implementors: You don't need to encode dimensional values.
    /// They will be encoded automatically._
    fn encode<B: bytes::BufMut>(&self, buf: B) -> std::io::Result<()>;
}

const ARRAY_VERSION: u32 = 0;

impl<const DIMS: usize> Data for [u64; DIMS] {
    const DIMS: usize = DIMS;
    const VERSION: u32 = ARRAY_VERSION;

    #[inline]
    fn dim(&self, dim: usize) -> u64 {
        self[dim]
    }

    #[inline]
    fn decode<B: bytes::Buf>(_version: u32, dims: &[u64], _buf: B) -> std::io::Result<Self> {
        let mut this = [0; DIMS];
        this.copy_from_slice(dims);
        Ok(this)
    }

    #[inline]
    fn encode<B: bytes::BufMut>(&self, _buf: B) -> std::io::Result<()> {
        Ok(())
    }
}

/// Trait representing IO handlers for dimensional worlds.
#[async_trait]
pub trait IoHandle: Send + Sync {
    /// Type of reader.
    type Read<'a>: AsyncRead + Unpin + Send + Sync + 'a
    where
        Self: 'a;

    /// Hints if the chunk with given position is valid.
    ///
    /// If the chunk is hinted by valid, the world will
    /// load it from this handler.
    #[inline]
    fn hint_is_valid(&self, pos: &[usize]) -> bool {
        let _ = pos;
        true
    }

    /// Gets reader and data version for given chunk position.
    async fn read_chunk<const DIMS: usize>(
        &self,
        pos: [usize; DIMS],
    ) -> std::io::Result<(u32, Self::Read<'_>)>;
}

impl<P, T> IoHandle for P
where
    T: IoHandle + 'static,
    P: Deref<Target = T> + Send + Sync,
{
    type Read<'a> = T::Read<'a> where Self: 'a;

    #[inline]
    fn hint_is_valid(&self, pos: &[usize]) -> bool {
        self.deref().hint_is_valid(pos)
    }

    #[doc = " Gets reader for given chunk position."]
    #[must_use]
    #[allow(clippy::type_complexity, clippy::type_repetition_in_bounds)]
    #[inline]
    fn read_chunk<'life0, 'async_trait, const DIMS: usize>(
        &'life0 self,
        pos: [usize; DIMS],
    ) -> ::core::pin::Pin<
        Box<
            dyn ::core::future::Future<Output = std::io::Result<(u32, Self::Read<'_>)>>
                + ::core::marker::Send
                + 'async_trait,
        >,
    >
    where
        'life0: 'async_trait,
        Self: 'async_trait,
    {
        self.deref().read_chunk(pos)
    }
}

/// Represents error variants produced by this crate.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// IO Error.
    #[error("io err: {0}")]
    Io(std::io::Error),
    /// Requesting value not found.
    #[error("requesting value not found")]
    ValueNotFound,
    /// Requesting value was moved to another chunk buffer.
    /// This is usually due to the target data was not suitable
    /// in the chunk after its modification.
    #[error("requesting value was moved to another chunk buffer")]
    ValueMoved,
    /// Given value out of range.
    #[error("value {value} out of range [{}, {}]", range.0, range.1)]
    ValueOutOfRange { range: (u64, u64), value: u64 },
}

/// Type alias for result produced by this crate.
type Result<T> = std::result::Result<T, Error>;