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
// MIT License
//
// Copyright (c) 2022-2024 Robin Doer
//
// 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.

#[cfg(test)]
mod tests;

use nuts_backend::{Binary, Create, Open, ReceiveHeader, HEADER_MAX_SIZE};
use std::convert::TryInto;
use std::mem;
use std::path::Path;

use crate::error::{Error, Result};
use crate::id::Id;
use crate::{read_header, write_header, DirectoryBackend};

const BLOCK_MIN_SIZE: u32 = 512;

/// [Options](nuts_backend::Create) needed to create the backend.
///
/// You must pass the path, where the directory tree should be stored, to
/// [`CreateOptions::for_path()`], if creating a `CreateOptions` instance.
///
/// Furthermore the following options can be specified:
///
/// * [`CreateOptions::with_bsize()`]: Specifies the block size of the backend.
///   This is the number of bytes, which can  be stored in an individual block.
///   The minimum block size is 512 bytes. The default is `512`.
#[derive(Clone, Debug)]
pub struct CreateOptions<P: AsRef<Path>> {
    path: P,
    bsize: u32,
}

impl<P: AsRef<Path>> CreateOptions<P> {
    /// Creates a new `CreateOptions` instance.
    ///
    /// You must pass the `path`, where the directory tree should be stored, to
    /// the function.
    ///
    /// For further options default values are applied.
    pub fn for_path(path: P) -> Self {
        CreateOptions {
            path,
            bsize: BLOCK_MIN_SIZE,
        }
    }

    /// Assigns a new block size to the options.
    ///
    /// This is the number of bytes, which can  be stored in an individual
    /// block.
    pub fn with_bsize(mut self, bsize: u32) -> Self {
        self.bsize = bsize;
        self
    }

    fn validate(&self) -> Result<()> {
        if self.bsize >= BLOCK_MIN_SIZE {
            Ok(())
        } else {
            Err(Error::InvalidBlockSize(self.bsize))
        }
    }
}

impl<P: AsRef<Path>> Create<DirectoryBackend<P>> for CreateOptions<P> {
    fn settings(&self) -> Settings {
        Settings { bsize: self.bsize }
    }

    fn build(self, header: [u8; HEADER_MAX_SIZE], overwrite: bool) -> Result<DirectoryBackend<P>> {
        self.validate()?;

        if !overwrite {
            let header_path = Id::min().to_pathbuf(self.path.as_ref());

            if header_path.exists() {
                return Err(Error::Exists);
            }
        }

        write_header(self.path.as_ref(), self.bsize, &header)?;

        Ok(DirectoryBackend {
            bsize: self.bsize,
            path: self.path,
        })
    }
}

/// [Options](nuts_backend::Open) needed to open the backend.
///
/// You must pass the path, where the directory tree is stored, to
/// [`OpenOptions::for_path()`], if creating a `OpenOptions` instance.
pub struct OpenOptions<P: AsRef<Path>> {
    path: P,
}

impl<P: AsRef<Path>> OpenOptions<P> {
    /// Creates a new `OpenOptions` instance.
    ///
    /// You must pass the `path`, where the directory tree should is stored, to
    /// the function.
    pub fn for_path(path: P) -> OpenOptions<P> {
        OpenOptions { path }
    }
}

impl<P: AsRef<Path>> ReceiveHeader<DirectoryBackend<P>> for OpenOptions<P> {
    fn get_header_bytes(&mut self, bytes: &mut [u8; HEADER_MAX_SIZE]) -> Result<()> {
        read_header(self.path.as_ref(), bytes)
    }
}

impl<P: AsRef<Path>> Open<DirectoryBackend<P>> for OpenOptions<P> {
    fn build(self, settings: Settings) -> Result<DirectoryBackend<P>> {
        Ok(DirectoryBackend {
            bsize: settings.bsize,
            path: self.path,
        })
    }
}

/// [Settings](nuts_backend::Backend::Settings) used by the backend.
#[derive(Clone, Debug)]
pub struct Settings {
    bsize: u32,
}

impl Binary for Settings {
    fn from_bytes(bytes: &[u8]) -> Option<Settings> {
        if bytes.len() == mem::size_of::<u32>() {
            let bytes = bytes.try_into().unwrap();
            let bsize = u32::from_be_bytes(bytes);

            Some(Settings { bsize })
        } else {
            None
        }
    }

    fn as_bytes(&self) -> Vec<u8> {
        self.bsize.to_be_bytes().to_vec()
    }
}