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
mod compare;

pub use compare::compare;
pub use idx_file::{Avltriee, AvltrieeHolder, AvltrieeIter, FileMmap, Found, IdxFile};
pub use various_data_file::DataAddress;

use std::{
    cmp::Ordering,
    num::NonZeroU32,
    ops::{Deref, DerefMut},
    path::Path,
};

use async_trait::async_trait;
use various_data_file::VariousDataFile;

pub trait DataAddressHolder<T> {
    fn data_address(&self) -> &DataAddress;
    fn new(data_address: DataAddress, input: &[u8]) -> T;
}

impl DataAddressHolder<DataAddress> for DataAddress {
    fn data_address(&self) -> &DataAddress {
        &self
    }

    fn new(data_address: DataAddress, _: &[u8]) -> DataAddress {
        data_address
    }
}

pub struct IdxBinary<T> {
    index: IdxFile<T>,
    data_file: VariousDataFile,
}

impl<T> AsRef<Avltriee<T>> for IdxBinary<T> {
    fn as_ref(&self) -> &Avltriee<T> {
        self
    }
}
impl<T> AsMut<Avltriee<T>> for IdxBinary<T> {
    fn as_mut(&mut self) -> &mut Avltriee<T> {
        self
    }
}

impl<T> Deref for IdxBinary<T> {
    type Target = IdxFile<T>;
    fn deref(&self) -> &Self::Target {
        &self.index
    }
}
impl<T> DerefMut for IdxBinary<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.index
    }
}

#[async_trait(?Send)]
impl<T: DataAddressHolder<T>> AvltrieeHolder<T, &[u8]> for IdxBinary<T> {
    fn cmp(&self, left: &T, right: &&[u8]) -> Ordering {
        self.cmp(left, right)
    }

    fn search_end(&self, input: &&[u8]) -> Found {
        self.index.search_end(|data| self.cmp(data, input))
    }

    fn value(&mut self, input: &[u8]) -> T {
        T::new(self.data_file.insert(input).address().clone(), input)
    }

    async fn delete_before_update(&mut self, row: NonZeroU32, delete_node: &T) {
        let is_unique = unsafe { self.index.is_unique(row) };
        futures::join!(
            async {
                if is_unique {
                    self.data_file.delete(delete_node.data_address());
                }
            },
            async {
                self.index.delete(row);
            }
        );
        self.index.allocate(row);
    }
}

impl<T: DataAddressHolder<T>> IdxBinary<T> {
    /// Opens the file and creates the IdxBinary<T>.
    /// # Arguments
    /// * `path` - Path of file to save data
    /// * `allocation_lot` - Extends the specified size when the file size becomes insufficient due to data addition.
    /// If you expect to add a lot of data, specifying a larger size will improve performance.
    pub fn new<P: AsRef<Path>>(path: P, allocation_lot: u32) -> Self {
        let path = path.as_ref();
        Self {
            index: IdxFile::new(
                {
                    let mut path = path.to_path_buf();
                    path.push(".i");
                    path
                },
                allocation_lot,
            ),
            data_file: VariousDataFile::new({
                let mut path = path.to_path_buf();
                path.push(".d");
                path
            }),
        }
    }

    /// Returns the value of the specified row. Returns None if the row does not exist.
    pub fn bytes(&self, row: NonZeroU32) -> Option<&'static [u8]> {
        self.index
            .value(row)
            .map(|value| self.data_file.bytes(&value.data_address()))
    }

    /// Updates the byte string of the specified row.
    /// If row does not exist, it will be expanded automatically..
    pub async fn update(&mut self, row: NonZeroU32, content: &[u8])
    where
        T: Copy,
    {
        self.index.allocate(row);
        unsafe {
            Avltriee::update_holder(self, row, content).await;
        }
    }

    /// Compare the stored data and the byte sequence.
    pub fn cmp(&self, data: &T, content: &[u8]) -> Ordering {
        compare(self.data_file.bytes(data.data_address()), content)
    }
}