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
// Copyright 2021-2023 Colin Finck <colin@reactos.org>
// SPDX-License-Identifier: MIT OR Apache-2.0
//
//! Supplementary helper types.

use core::fmt;
use core::num::NonZeroU64;
use core::ops::{Add, AddAssign};

use binrw::BinRead;
use derive_more::{Binary, Display, From, LowerHex, Octal, UpperHex};

use crate::error::{NtfsError, Result};
use crate::ntfs::Ntfs;

/// An absolute nonzero byte position on the NTFS filesystem.
/// Can be used to seek, but even more often in [`NtfsError`] variants to assist with debugging.
///
/// Note that there may be cases when no valid position can be given for the current situation.
/// For example, this may happen when a reader is on a sparse Data Run or it has been seeked to a
/// position outside the valid range.
/// Therefore, this structure internally uses an [`Option`] of a [`NonZeroU64`] to alternatively
/// store a `None` value if no valid position can be given.
#[derive(Clone, Copy, Debug, Eq, From, Ord, PartialEq, PartialOrd)]
pub struct NtfsPosition(Option<NonZeroU64>);

impl NtfsPosition {
    const NONE_STR: &'static str = "<NONE>";

    pub(crate) const fn new(position: u64) -> Self {
        Self(NonZeroU64::new(position))
    }

    pub(crate) const fn none() -> Self {
        Self(None)
    }

    /// Returns the stored position, or `None` if there is no valid position.
    pub const fn value(&self) -> Option<NonZeroU64> {
        self.0
    }
}

impl Add<u16> for NtfsPosition {
    type Output = Self;

    fn add(self, other: u16) -> Self {
        self + other as u64
    }
}

impl Add<u64> for NtfsPosition {
    type Output = Self;

    fn add(self, other: u64) -> Self {
        let new_value = self
            .0
            .and_then(|position| NonZeroU64::new(position.get().wrapping_add(other)));
        Self(new_value)
    }
}

impl Add<usize> for NtfsPosition {
    type Output = Self;

    fn add(self, other: usize) -> Self {
        self + other as u64
    }
}

impl AddAssign<u16> for NtfsPosition {
    fn add_assign(&mut self, other: u16) {
        *self = *self + other;
    }
}

impl AddAssign<u64> for NtfsPosition {
    fn add_assign(&mut self, other: u64) {
        *self = *self + other;
    }
}

impl AddAssign<usize> for NtfsPosition {
    fn add_assign(&mut self, other: usize) {
        *self = *self + other;
    }
}

impl fmt::Binary for NtfsPosition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Some(position) => fmt::Binary::fmt(&position, f),
            None => fmt::Display::fmt(Self::NONE_STR, f),
        }
    }
}

impl fmt::Display for NtfsPosition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Some(position) => fmt::Display::fmt(&position, f),
            None => fmt::Display::fmt(Self::NONE_STR, f),
        }
    }
}

impl fmt::LowerHex for NtfsPosition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Some(position) => fmt::LowerHex::fmt(&position, f),
            None => fmt::Display::fmt(Self::NONE_STR, f),
        }
    }
}

impl fmt::Octal for NtfsPosition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Some(position) => fmt::Octal::fmt(&position, f),
            None => fmt::Display::fmt(Self::NONE_STR, f),
        }
    }
}

impl fmt::UpperHex for NtfsPosition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Some(position) => fmt::UpperHex::fmt(&position, f),
            None => fmt::Display::fmt(Self::NONE_STR, f),
        }
    }
}

impl From<NonZeroU64> for NtfsPosition {
    fn from(value: NonZeroU64) -> Self {
        Self(Some(value))
    }
}

/// A Logical Cluster Number (LCN).
///
/// NTFS divides a filesystem into clusters of a given size (power of two), see [`Ntfs::cluster_size`].
/// The LCN is an absolute cluster index into the filesystem.
#[derive(
    Binary,
    BinRead,
    Clone,
    Copy,
    Debug,
    Display,
    Eq,
    From,
    LowerHex,
    Octal,
    Ord,
    PartialEq,
    PartialOrd,
    UpperHex,
)]
pub struct Lcn(u64);

impl Lcn {
    /// Performs a checked addition of the given Virtual Cluster Number (VCN), returning a new LCN.
    pub fn checked_add(&self, vcn: Vcn) -> Option<Lcn> {
        if vcn.0 >= 0 {
            self.0.checked_add(vcn.0 as u64).map(Into::into)
        } else {
            self.0
                .checked_sub(vcn.0.wrapping_neg() as u64)
                .map(Into::into)
        }
    }

    /// Returns the absolute byte position of this LCN within the filesystem.
    pub fn position(&self, ntfs: &Ntfs) -> Result<NtfsPosition> {
        let value = self
            .0
            .checked_mul(ntfs.cluster_size() as u64)
            .ok_or(NtfsError::LcnTooBig { lcn: *self })?;
        Ok(NtfsPosition::new(value))
    }

    /// Returns the stored Logical Cluster Number.
    pub fn value(&self) -> u64 {
        self.0
    }
}

/// A Virtual Cluster Number (VCN).
///
/// NTFS divides a filesystem into clusters of a given size (power of two), see [`Ntfs::cluster_size`].
/// The VCN is a cluster index into the filesystem that is relative to a Logical Cluster Number (LCN)
/// or relative to the start of an attribute value.
#[derive(
    Binary,
    BinRead,
    Clone,
    Copy,
    Debug,
    Display,
    Eq,
    From,
    LowerHex,
    Octal,
    Ord,
    PartialEq,
    PartialOrd,
    UpperHex,
)]
pub struct Vcn(i64);

impl Vcn {
    /// Converts this VCN into a byte offset (with respect to the cluster size of the provided [`Ntfs`] filesystem).
    pub fn offset(&self, ntfs: &Ntfs) -> Result<i64> {
        self.0
            .checked_mul(ntfs.cluster_size() as i64)
            .ok_or(NtfsError::VcnTooBig { vcn: *self })
    }

    /// Returns the stored Virtual Cluster Number.
    pub fn value(&self) -> i64 {
        self.0
    }
}