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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

// Allow the clippy error cast_lossless in this module.
// Otherwise, clippy will suggest that "as u64" be converted to "64::from".
// Unfortunately, the locations it suggests are all in macros, and u64
// does not implement From<usize>. It is preferable to use the macros
// uniformly for both usize and the other u* types.
// I don't think that casting from usize to u64 could be lossy, unless the
// code is running on a machine with 128 bit pointers, so this is not a
// pressing worry.
#![allow(cast_lossless)]

use consts::SECTOR_SIZE;

use std::fmt;
use std::iter::Sum;
use std::ops::{Div, Mul, Rem, Add};

use serde;

/// a kernel defined block size constant for a DM meta device
/// defined in drivers/md/persistent-data/dm-space-map-metadata.h line 12
const META_BLOCK_SIZE: Sectors = Sectors(8);

// division by self
macro_rules! self_div {
    ($T: ident) => {
        impl Div<$T> for $T {
            type Output = u64;
            fn div(self, rhs: $T) -> u64 {
                self.0 / *rhs
            }
        }
    }
}

// macros for implementing serialize and deserialize on all types
macro_rules! serde {
    ($T: ident) => {
        impl serde::Serialize for $T {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
                where S: serde::Serializer
            {
                serializer.serialize_u64(**self)
            }
        }

        impl <'de> serde::Deserialize<'de> for $T {
            fn deserialize<D>(deserializer: D) -> Result<$T, D::Error>
                where D: serde::de::Deserializer<'de>
            {
                Ok($T(serde::Deserialize::deserialize(deserializer)?))
            }
        }
    }
}

// macros for implementing Sum on all types
macro_rules! sum {
    ($T: ident) => {
        impl Sum for $T {
            fn sum<I: Iterator<Item = $T>>(iter: I) -> $T {
                iter.fold($T::default(), Add::add)
            }
        }
    }
}

// macros for unsigned operations on Sectors and Bytes
macro_rules! unsigned_div {
    ($t: ty, $T: ident) => {
        impl Div<$t> for $T {
            type Output = $T;
            fn div(self, rhs: $t) -> $T {
                $T(self.0 / rhs as u64)
            }
        }
    }
}

macro_rules! unsigned_mul {
    ($t: ty, $T: ident) => {
        impl Mul<$t> for $T {
            type Output = $T;
            fn mul(self, rhs: $t) -> $T {
                $T(self.0 * rhs as u64)
            }
        }

        impl Mul<$T> for $t {
            type Output = $T;
            fn mul(self, rhs: $T) -> $T {
                $T(self as u64 * rhs.0)
            }
        }
    }
}

macro_rules! unsigned_rem {
    ($t: ty, $T: ident) => {
        impl Rem<$t> for $T {
            type Output = $T;
            fn rem(self, rhs: $t) -> $T {
                $T(self.0 % rhs as u64)
            }
        }
    }
}

macro_rules! checked_add {
    ($T: ident) => {
        /// Add two items of type $T, return None if overflow.
        pub fn checked_add(&self, other: $T) -> Option<$T> {
            self.0.checked_add(other.0).map($T)
        }
    }
}

custom_derive! {
    #[derive(NewtypeAdd, NewtypeAddAssign,
             NewtypeDeref,
             NewtypeFrom,
             NewtypeSub, NewtypeSubAssign,
             Debug, Default, Clone, Copy, Eq, PartialEq, PartialOrd, Ord)]
    /// A type for Data Blocks as used by the thin pool.
    pub struct DataBlocks(pub u64);
}

self_div!(DataBlocks);
serde!(DataBlocks);

unsigned_mul!(u64, DataBlocks);
unsigned_mul!(u32, DataBlocks);
unsigned_mul!(u16, DataBlocks);
unsigned_mul!(u8, DataBlocks);
unsigned_mul!(usize, DataBlocks);

impl fmt::Display for DataBlocks {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} data blocks", self.0)
    }
}

custom_derive! {
    #[derive(NewtypeAdd, NewtypeAddAssign,
             NewtypeDeref,
             NewtypeFrom,
             NewtypeSub,
             Debug, Clone, Copy, Eq, PartialEq, PartialOrd, Ord)]
    /// A type for Meta Data blocks as used by the thin pool.
    /// MetaBlocks have a kernel defined constant size of META_BLOCK_SIZE
    pub struct MetaBlocks(pub u64);
}

impl MetaBlocks {
    /// Return the number of Sectors in the MetaBlocks.
    pub fn sectors(self) -> Sectors {
        self.0 * META_BLOCK_SIZE
    }
}

self_div!(MetaBlocks);
serde!(MetaBlocks);

unsigned_mul!(u64, MetaBlocks);
unsigned_mul!(u32, MetaBlocks);
unsigned_mul!(u16, MetaBlocks);
unsigned_mul!(u8, MetaBlocks);
unsigned_mul!(usize, MetaBlocks);

impl fmt::Display for MetaBlocks {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} meta blocks", self.0)
    }
}

custom_derive! {
    #[derive(NewtypeAdd, NewtypeAddAssign,
             NewtypeDeref,
             NewtypeFrom,
             NewtypeSub, NewtypeSubAssign,
             Debug, Default, Clone, Copy, Eq, PartialEq, PartialOrd, Ord)]
    /// Structure to represent bytes
    pub struct Bytes(pub u64);
}

impl Bytes {
    /// Return the number of Sectors fully contained in these bytes.
    pub fn sectors(self) -> Sectors {
        Sectors(self.0 / SECTOR_SIZE as u64)
    }

    checked_add!(Bytes);
}

self_div!(Bytes);
serde!(Bytes);
sum!(Bytes);

unsigned_mul!(u64, Bytes);
unsigned_mul!(u32, Bytes);
unsigned_mul!(u16, Bytes);
unsigned_mul!(u8, Bytes);
unsigned_mul!(usize, Bytes);

impl fmt::Display for Bytes {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} bytes", self.0)
    }
}

custom_derive! {
    #[derive(NewtypeAdd, NewtypeAddAssign,
             NewtypeDeref,
             NewtypeFrom,
             NewtypeSub, NewtypeSubAssign,
             Debug, Default, Clone, Copy, Eq, PartialEq, PartialOrd, Ord)]
    /// A separate type to store counts and offsets expressed in
    /// 512-byte sectors.
    pub struct Sectors(pub u64);
}

impl Sectors {
    /// The number of bytes in these sectors.
    pub fn bytes(&self) -> Bytes {
        Bytes(self.0 * SECTOR_SIZE as u64)
    }

    /// The number of whole metablocks contained in these sectors.
    pub fn metablocks(&self) -> MetaBlocks {
        MetaBlocks(*self / META_BLOCK_SIZE)
    }

    checked_add!(Sectors);
}


self_div!(Sectors);
serde!(Sectors);
sum!(Sectors);

unsigned_div!(u64, Sectors);
unsigned_div!(u32, Sectors);
unsigned_div!(u16, Sectors);
unsigned_div!(u8, Sectors);
unsigned_div!(usize, Sectors);

unsigned_mul!(u64, Sectors);
unsigned_mul!(u32, Sectors);
unsigned_mul!(u16, Sectors);
unsigned_mul!(u8, Sectors);
unsigned_mul!(usize, Sectors);

unsigned_rem!(u64, Sectors);
unsigned_rem!(u32, Sectors);
unsigned_rem!(u16, Sectors);
unsigned_rem!(u8, Sectors);
unsigned_rem!(usize, Sectors);

impl fmt::Display for Sectors {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} sectors", self.0)
    }
}


/// This 4-tuple consists of starting offset (sectors), length
/// (sectors), target type (string, e.g. "linear"), and
/// params(string). See target documentation for the format of each
/// target type's params field.
pub type TargetLine = (Sectors, Sectors, String, String);

/// The same as TargetLine, except generalized for argument rather than
/// return type.
pub type TargetLineArg<T1, T2> = (Sectors, Sectors, T1, T2);

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    /// Verify that Sectors can be multiplied by a usize.
    /// The real test is that this tests compiles at all.
    fn test_usize() {
        assert_eq!(Sectors(0) * 32usize, Sectors(0));
    }
}