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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use core::hash::Hash;

use core::fmt;

use core::ops::{Add, Sub, AddAssign, SubAssign};

use num_traits::identities;
use num_traits::{Bounded, WrappingAdd, WrappingSub, CheckedAdd, Zero, One};

#[cfg(feature="use-serde")]
use serde::{Deserialize, Serialize};

#[cfg(feature="use-serde")]
pub trait AddressDiffAmount: Copy + Clone + PartialEq + PartialOrd + Eq + Ord + identities::Zero + identities::One + Serialize + for<'de> Deserialize<'de> {}
#[cfg(not(feature="use-serde"))]
pub trait AddressDiffAmount: Copy + Clone + PartialEq + PartialOrd + Eq + Ord + identities::Zero + identities::One {}

impl AddressDiffAmount for u64 {}
impl AddressDiffAmount for u32 {}
impl AddressDiffAmount for u16 {}
impl AddressDiffAmount for usize {}

/// a struct describing the differece between some pair of `A: Address`. this is primarily useful
/// in describing the size of an instruction, or the relative offset of a branch.
///
/// for any address type `A`, the following must hold:
/// ```rust
/// use yaxpeax_arch::AddressBase;
/// fn diff_check<A: AddressBase + core::fmt::Debug>(left: A, right: A) {
///     let diff = left.diff(&right);
///     if let Some(offset) = diff {
///         assert_eq!(left.wrapping_offset(offset), right);
///     }
/// }
/// ```
///
/// which is to say, `yaxpeax` assumes associativity holds when `diff` yields a `Some`.
#[cfg(feature="use-serde")]
#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Serialize, Deserialize)]
pub struct AddressDiff<T: AddressBase> {
    // the AddressDiffAmount trait fools `Deserialize`'s proc macro, so we have to explicitly write
    // the bound serde should use.
    #[serde(bound(deserialize = "T::Diff: AddressDiffAmount"))]
    amount: T::Diff,
}
/// a struct describing the differece between some pair of `A: Address`. this is primarily useful
/// in describing the size of an instruction, or the relative offset of a branch.
///
/// for any address type `A`, the following must hold:
/// ```rust
/// use yaxpeax_arch::AddressBase;
/// fn diff_check<A: AddressBase + core::fmt::Debug>(left: A, right: A) {
///     let diff = left.diff(&right);
///     if let Some(offset) = diff {
///         assert_eq!(left.wrapping_offset(offset), right);
///     }
/// }
/// ```
///
/// which is to say, `yaxpeax` assumes associativity holds when `diff` yields a `Some`.
#[cfg(not(feature="use-serde"))]
#[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord)]
pub struct AddressDiff<T: AddressBase> {
    amount: T::Diff,
}

impl<T: Address> AddressDiff<T> {
    pub fn from_const(amount: T::Diff) -> Self {
        AddressDiff { amount }
    }
    pub fn to_const(&self) -> T::Diff {
        self.amount
    }
}

impl<T: Address> fmt::Debug for AddressDiff<T> where T::Diff: fmt::Debug {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "AddressDiff({:?})", self.amount)
    }
}

impl<T: Address> AddressDiff<T> {
    pub fn one() -> Self {
        AddressDiff {
            amount: <T as AddressBase>::Diff::one(),
        }
    }

    pub fn zero() -> Self {
        AddressDiff {
            amount: <T as AddressBase>::Diff::zero(),
        }
    }
}

impl Sub<AddressDiff<u16>> for u16 {
    type Output = Self;

    fn sub(self, other: AddressDiff<Self>) -> Self::Output {
        self - other.amount
    }
}

impl Sub<AddressDiff<u32>> for u32 {
    type Output = Self;

    fn sub(self, other: AddressDiff<Self>) -> Self::Output {
        self - other.amount
    }
}

impl Sub<AddressDiff<u64>> for u64 {
    type Output = Self;

    fn sub(self, other: AddressDiff<Self>) -> Self::Output {
        self - other.amount
    }
}

impl Sub<AddressDiff<usize>> for usize {
    type Output = Self;

    fn sub(self, other: AddressDiff<Self>) -> Self::Output {
        self - other.amount
    }
}

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

    fn add(self, other: AddressDiff<Self>) -> Self::Output {
        self + other.amount
    }
}

impl Add<AddressDiff<u32>> for u32 {
    type Output = Self;

    fn add(self, other: AddressDiff<Self>) -> Self::Output {
        self + other.amount
    }
}

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

    fn add(self, other: AddressDiff<Self>) -> Self::Output {
        self + other.amount
    }
}

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

    fn add(self, other: AddressDiff<Self>) -> Self::Output {
        self + other.amount
    }
}

impl SubAssign<AddressDiff<u16>> for u16 {
    fn sub_assign(&mut self, other: AddressDiff<Self>) {
        *self -= other.amount;
    }
}

impl SubAssign<AddressDiff<u32>> for u32 {
    fn sub_assign(&mut self, other: AddressDiff<Self>) {
        *self -= other.amount;
    }
}

impl SubAssign<AddressDiff<u64>> for u64 {
    fn sub_assign(&mut self, other: AddressDiff<Self>) {
        *self -= other.amount;
    }
}

impl SubAssign<AddressDiff<usize>> for usize {
    fn sub_assign(&mut self, other: AddressDiff<Self>) {
        *self -= other.amount;
    }
}

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

impl AddAssign<AddressDiff<u32>> for u32 {
    fn add_assign(&mut self, other: AddressDiff<Self>) {
        *self += other.amount;
    }
}

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

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

pub trait AddressBase where Self:
    AddressDisplay +
    Copy + Clone + Sized + Hash +
    Ord + Eq + PartialEq + Bounded +
    Add<AddressDiff<Self>, Output=Self> + Sub<AddressDiff<Self>, Output=Self> +
    AddAssign<AddressDiff<Self>> + SubAssign<AddressDiff<Self>> +
    identities::Zero +
    Hash {
    type Diff: AddressDiffAmount;
    fn to_linear(&self) -> usize;

    /// compute the `AddressDiff` beetween `self` and `other`.
    ///
    /// may return `None` if the two addresses aren't comparable. for example, if a pair of
    /// addresses are a data-space address and code-space address, there may be no scalar that can
    /// describe the difference between them.
    fn diff(&self, other: &Self) -> Option<AddressDiff<Self>>;
    /*
    {
        Some(AddressDiff { amount: self.wrapping_sub(other) })
    }
    */

    fn wrapping_offset(&self, other: AddressDiff<Self>) -> Self;
    /*
    {
        self.wrapping_add(&other.amount)
    }
    */

    fn checked_offset(&self, other: AddressDiff<Self>) -> Option<Self>;
    /*
    {
        self.checked_add(&other.amount)
    }
    */
}

#[cfg(all(feature="use-serde", feature="address-parse"))]
pub trait Address where Self:
    AddressBase +
    Serialize + for<'de> Deserialize<'de> +
    AddrParse {
}

#[cfg(all(feature="use-serde", not(feature="address-parse")))]
pub trait Address where Self:
    AddressBase +
    Serialize + for<'de> Deserialize<'de> {
}

#[cfg(all(not(feature="use-serde"), feature="address-parse"))]
pub trait Address where Self:
    AddressBase + AddrParse {
}

#[cfg(all(not(feature="use-serde"), not(feature="address-parse")))]
pub trait Address where Self: AddressBase { }

impl AddressBase for u16 {
    type Diff = Self;
    fn to_linear(&self) -> usize { *self as usize }

    fn diff(&self, other: &Self) -> Option<AddressDiff<Self>> {
        Some(AddressDiff { amount: self.wrapping_sub(other) })
    }
    fn wrapping_offset(&self, other: AddressDiff<Self>) -> Self {
        self.wrapping_add(&other.amount)
    }

    fn checked_offset(&self, other: AddressDiff<Self>) -> Option<Self> {
        self.checked_add(&other.amount)
    }
}

impl Address for u16 {}

impl AddressBase for u32 {
    type Diff = Self;
    fn to_linear(&self) -> usize { *self as usize }

    fn diff(&self, other: &Self) -> Option<AddressDiff<Self>> {
        Some(AddressDiff { amount: self.wrapping_sub(other) })
    }
    fn wrapping_offset(&self, other: AddressDiff<Self>) -> Self {
        self.wrapping_add(&other.amount)
    }

    fn checked_offset(&self, other: AddressDiff<Self>) -> Option<Self> {
        self.checked_add(&other.amount)
    }
}

impl Address for u32 {}

impl AddressBase for u64 {
    type Diff = Self;
    fn to_linear(&self) -> usize { *self as usize }

    fn diff(&self, other: &Self) -> Option<AddressDiff<Self>> {
        Some(AddressDiff { amount: self.wrapping_sub(other) })
    }
    fn wrapping_offset(&self, other: AddressDiff<Self>) -> Self {
        self.wrapping_add(&other.amount)
    }

    fn checked_offset(&self, other: AddressDiff<Self>) -> Option<Self> {
        self.checked_add(&other.amount)
    }
}

impl Address for u64 {}

impl AddressBase for usize {
    type Diff = Self;
    fn to_linear(&self) -> usize { *self }

    fn diff(&self, other: &Self) -> Option<AddressDiff<Self>> {
        Some(AddressDiff { amount: self.wrapping_sub(other) })
    }
    fn wrapping_offset(&self, other: AddressDiff<Self>) -> Self {
        self.wrapping_add(&other.amount)
    }

    fn checked_offset(&self, other: AddressDiff<Self>) -> Option<Self> {
        self.checked_add(&other.amount)
    }
}

impl Address for usize {}

pub trait AddressDisplay {
    type Show: fmt::Display;
    fn show(&self) -> Self::Show;
}

impl AddressDisplay for usize {
    type Show = AddressDisplayUsize;

    fn show(&self) -> AddressDisplayUsize {
        AddressDisplayUsize(*self)
    }
}

#[repr(transparent)]
pub struct AddressDisplayUsize(usize);

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

impl AddressDisplay for u64 {
    type Show = AddressDisplayU64;

    fn show(&self) -> AddressDisplayU64 {
        AddressDisplayU64(*self)
    }
}

#[repr(transparent)]
pub struct AddressDisplayU64(u64);

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

impl AddressDisplay for u32 {
    type Show = AddressDisplayU32;

    fn show(&self) -> AddressDisplayU32 {
        AddressDisplayU32(*self)
    }
}

#[repr(transparent)]
pub struct AddressDisplayU32(u32);

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

impl AddressDisplay for u16 {
    type Show = AddressDisplayU16;

    fn show(&self) -> AddressDisplayU16 {
        AddressDisplayU16(*self)
    }
}

#[repr(transparent)]
pub struct AddressDisplayU16(u16);

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

/*
 * TODO: this should be FromStr.
 * that would require newtyping address primitives, though
 *
 * this is not out of the question, BUT is way more work than
 * i want to put in right now
 *
 * this is one of those "clean it up later" situations
 */
#[cfg(feature="address-parse")]
use core::str::FromStr;

#[cfg(feature="address-parse")]
pub trait AddrParse: Sized {
    type Err;
    fn parse_from(s: &str) -> Result<Self, Self::Err>;
}

#[cfg(feature="address-parse")]
impl AddrParse for usize {
    type Err = core::num::ParseIntError;
    fn parse_from(s: &str) -> Result<Self, Self::Err> {
        if s.starts_with("0x") {
            usize::from_str_radix(&s[2..], 16)
        } else {
            usize::from_str(s)
        }
    }
}

#[cfg(feature="address-parse")]
impl AddrParse for u64 {
    type Err = core::num::ParseIntError;
    fn parse_from(s: &str) -> Result<Self, Self::Err> {
        if s.starts_with("0x") {
            u64::from_str_radix(&s[2..], 16)
        } else {
            u64::from_str(s)
        }
    }
}

#[cfg(feature="address-parse")]
impl AddrParse for u32 {
    type Err = core::num::ParseIntError;
    fn parse_from(s: &str) -> Result<Self, Self::Err> {
        if s.starts_with("0x") {
            u32::from_str_radix(&s[2..], 16)
        } else {
            u32::from_str(s)
        }
    }
}

#[cfg(feature="address-parse")]
impl AddrParse for u16 {
    type Err = core::num::ParseIntError;
    fn parse_from(s: &str) -> Result<Self, Self::Err> {
        if s.starts_with("0x") {
            u16::from_str_radix(&s[2..], 16)
        } else {
            u16::from_str(s)
        }
    }
}