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 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
use std::{
convert::{TryFrom, TryInto},
fmt::{self, Display},
ops::Deref,
str,
};
use thiserror::Error;
/// the soft derivation is upper bounded, this is the value
const SOFT_DERIVATION_UPPER_BOUND: u32 = 0x8000_0000;
/// a derivation value that can be used to derive keys
///
/// There is 2 kind of derivations, the soft and the hard derivations.
/// [`SoftDerivation`] are expected to allow derivation of the private
/// keys and of the public keys. [`HardDerivation`] are expected to allow
/// only the derivation of the private keys.
///
/// [`SoftDerivation`]: ./struct.SoftDerivation.html
/// [`HardDerivation`]: ./struct.HardDerivation.html
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Derivation(u32);
/// wrapper to guarantee the given derivation is a soft derivation
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SoftDerivation(Derivation);
/// wrapper to guarantee the given derivation is a soft derivation
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HardDerivation(Derivation);
/// iterator to create derivation values
///
/// # Examples
///
/// ```
/// # use chain_path_derivation::{Derivation, DerivationRange};
/// let range = DerivationRange::new(..20);
/// for (expected, derivation) in (0..20).zip(range) {
/// assert_eq!(derivation, Derivation::new(expected));
/// }
/// ```
#[derive(Debug)]
pub struct DerivationRange {
range: std::ops::Range<Derivation>,
}
/// iterator to create derivation values
///
/// # Examples
///
/// ```
/// # use chain_path_derivation::{Derivation, SoftDerivation, SoftDerivationRange};
/// let range = SoftDerivationRange::new(..20);
/// for (expected, derivation) in (0..20).zip(range) {
/// assert_eq!(
/// derivation,
/// SoftDerivation::new_unchecked(Derivation::new(expected))
/// );
/// }
/// ```
#[derive(Debug, Clone)]
pub struct SoftDerivationRange {
range: std::ops::Range<SoftDerivation>,
}
/// iterator to create derivation values
///
/// # Examples
///
/// ```
/// # use chain_path_derivation::{Derivation, HardDerivation, HardDerivationRange};
/// let range = HardDerivationRange::new(..0x8000_0020);
/// for (expected, derivation) in (0x8000_0000..0x8000_0020).zip(range) {
/// assert_eq!(
/// derivation,
/// HardDerivation::new_unchecked(Derivation::new(expected))
/// );
/// }
/// ```
#[derive(Debug, Clone)]
pub struct HardDerivationRange {
range: std::ops::Range<HardDerivation>,
}
#[derive(Debug, Error)]
pub enum DerivationError {
#[error("Not a valid derivation for a soft derivation ({0})")]
InvalidSoftDerivation(Derivation),
#[error("Not a valid derivation for a hard derivation ({0})")]
InvalidHardDerivation(Derivation),
}
impl Derivation {
/// create a new derivation with the given index
#[inline]
pub const fn new(v: u32) -> Self {
Self(v)
}
/// test if the given derivation is a soft derivation
///
/// # Example
///
/// ```
/// # use chain_path_derivation::Derivation;
/// let derivation = Derivation::new(42);
/// assert!(derivation.is_soft_derivation());
/// ```
#[inline]
pub fn is_soft_derivation(self) -> bool {
self.0 < SOFT_DERIVATION_UPPER_BOUND
}
/// test if the given derivation is a hard derivation
///
/// # Example
///
/// ```
/// # use chain_path_derivation::Derivation;
/// let derivation = Derivation::new(0x8000_0010);
/// assert!(derivation.is_hard_derivation());
/// ```
#[inline]
pub fn is_hard_derivation(self) -> bool {
!self.is_soft_derivation()
}
/// returns the max derivation index value
///
/// ```
/// # use chain_path_derivation::Derivation;
/// let max = Derivation::max_value();
/// assert_eq!(max, Derivation::new(4294967295));
/// ```
#[inline]
pub const fn max_value() -> Self {
Self::new(u32::max_value())
}
/// returns the min derivation index value
///
/// ```
/// # use chain_path_derivation::Derivation;
/// let min = Derivation::min_value();
/// assert_eq!(min, Derivation::new(0));
/// ```
#[inline]
pub const fn min_value() -> Self {
Self::new(u32::min_value())
}
/// calculate `derivation + rhs`
///
/// Returns the tuple of the addition along with a boolean indicating whether
/// an arithmetic overflow would occur. If an overflow would have occurred
/// then the wrapped value is returned.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use chain_path_derivation::Derivation;
/// assert_eq!(
/// Derivation::new(5).overflowing_add(2),
/// (Derivation::new(7), false)
/// );
/// assert_eq!(
/// Derivation::max_value().overflowing_add(1),
/// (Derivation::new(0), true)
/// );
/// ```
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub const fn overflowing_add(self, rhs: u32) -> (Self, bool) {
let (v, b) = self.0.overflowing_add(rhs);
(Self(v), b)
}
/// saturating integer addition. Computes `self + rhs`, saturating
/// at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use chain_path_derivation::Derivation;
/// assert_eq!(Derivation::new(100).saturating_add(1), Derivation::new(101));
/// assert_eq!(Derivation::max_value().saturating_add(2048), Derivation::max_value());
/// ```
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub fn saturating_add(self, rhs: u32) -> Self {
Self(self.0.saturating_add(rhs))
}
/// checked integer addition. Computes `self + rhs`, returning `None` if overflow
/// would occurred.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use chain_path_derivation::Derivation;
/// assert_eq!(Derivation::new(100).checked_add(1), Some(Derivation::new(101)));
/// assert_eq!(Derivation::max_value().checked_add(2048), None);
/// ```
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub fn checked_add(self, rhs: u32) -> Option<Self> {
self.0.checked_add(rhs).map(Self)
}
/// Wrapping (modular) addition. Computes `self + rhs`, wrapping around the boundary
/// of the type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use chain_path_derivation::Derivation;
/// assert_eq!(Derivation::new(100).wrapping_add(1), Derivation::new(101));
/// assert_eq!(Derivation::max_value().wrapping_add(1), Derivation::new(0));
/// ```
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub const fn wrapping_add(self, rhs: u32) -> Self {
Self(self.0.wrapping_add(rhs))
}
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
fn saturating_sub(self, rhs: u32) -> Self {
Self(self.0.saturating_sub(rhs))
}
}
impl SoftDerivation {
/// construct a soft derivation from the given derivation without
/// checking the derivation is actually a soft derivation.
///
/// this function does not perform any verification and if the value
/// is not correct it will create a cascade of issues, be careful when
/// utilizing this function.
#[inline]
pub const fn new_unchecked(derivation: Derivation) -> Self {
Self(derivation)
}
/// build a soft derivation from the given `Derivation`. If the value
/// is not a soft derivation it will return an error
///
/// # Example
///
/// ```
/// # use chain_path_derivation::{Derivation, SoftDerivation, DerivationError};
/// # fn func() -> Result<(), DerivationError> {
/// let derivation = Derivation::new(42);
/// let derivation = SoftDerivation::new(derivation)?;
///
/// println!("derivation: {}", derivation);
/// # Ok(())
/// # }
/// #
/// # func().unwrap();
/// ```
#[inline]
pub fn new(derivation: Derivation) -> Result<Self, DerivationError> {
if derivation.is_soft_derivation() {
Ok(Self::new_unchecked(derivation))
} else {
Err(DerivationError::InvalidSoftDerivation(derivation))
}
}
/// returns the max derivation index value
///
/// ```
/// # use chain_path_derivation::{Derivation, SoftDerivation};
/// let max = SoftDerivation::max_value();
/// assert_eq!(max, SoftDerivation::new_unchecked(Derivation::new(0x7FFF_FFFF)));
/// ```
#[inline]
pub const fn max_value() -> Self {
Self::new_unchecked(Derivation::new(SOFT_DERIVATION_UPPER_BOUND - 1))
}
/// returns the min derivation index value
///
/// ```
/// # use chain_path_derivation::{Derivation, SoftDerivation};
/// let min = SoftDerivation::min_value();
/// assert_eq!(min, SoftDerivation::new_unchecked(Derivation::new(0)));
/// ```
#[inline]
pub const fn min_value() -> Self {
Self::new_unchecked(Derivation::min_value())
}
/// calculate `self + rhs`
///
/// Returns the tuple of the addition along with a boolean indicating whether
/// an arithmetic overflow would occur. If an overflow would have occurred
/// then the wrapped value is returned.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use chain_path_derivation::{Derivation, SoftDerivation};
/// assert_eq!(
/// SoftDerivation::new_unchecked(Derivation::new(5)).overflowing_add(2),
/// (SoftDerivation::new_unchecked(Derivation::new(7)), false)
/// );
/// assert_eq!(
/// SoftDerivation::max_value().overflowing_add(1),
/// (SoftDerivation::new_unchecked(Derivation::new(0)), true)
/// );
/// ```
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub fn overflowing_add(self, rhs: u32) -> (Self, bool) {
let (v, b) = self.0.overflowing_add(rhs);
if v.is_soft_derivation() {
(Self::new_unchecked(v), b)
} else {
(
Self::new_unchecked(Derivation::new(v.0 - SOFT_DERIVATION_UPPER_BOUND)),
true,
)
}
}
/// saturating integer addition. Computes `self + rhs`, saturating
/// at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use chain_path_derivation::{Derivation, SoftDerivation};
/// assert_eq!(
/// SoftDerivation::new_unchecked(Derivation::new(100)).saturating_add(1),
/// SoftDerivation::new_unchecked(Derivation::new(101))
/// );
/// assert_eq!(
/// SoftDerivation::max_value().saturating_add(2048),
/// SoftDerivation::max_value(),
/// );
/// ```
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub fn saturating_add(self, rhs: u32) -> Self {
let d = self.0.saturating_add(rhs);
// allow `unwrap_or`, it's 32bits of integer or a function pointer
#[allow(clippy::or_fun_call)]
Self::new(d).unwrap_or(Self::max_value())
}
/// checked integer addition. Computes `self + rhs`, returning `None` if overflow
/// would occurred.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use chain_path_derivation::{Derivation, SoftDerivation};
/// assert_eq!(
/// SoftDerivation::new_unchecked(Derivation::new(100)).checked_add(1),
/// Some(SoftDerivation::new_unchecked(Derivation::new(101)))
/// );
/// assert_eq!(
/// SoftDerivation::max_value().checked_add(2048),
/// None,
/// );
/// ```
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub fn checked_add(self, rhs: u32) -> Option<Self> {
let d = self.0.checked_add(rhs)?;
Self::new(d).ok()
}
/// Wrapping (modular) addition. Computes `self + rhs`, wrapping around the boundary
/// of the type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use chain_path_derivation::{Derivation, SoftDerivation};
/// assert_eq!(
/// SoftDerivation::new_unchecked(Derivation::new(100)).wrapping_add(1),
/// SoftDerivation::new_unchecked(Derivation::new(101))
/// );
/// assert_eq!(
/// SoftDerivation::max_value().wrapping_add(1),
/// SoftDerivation::new_unchecked(Derivation::new(0)),
/// );
/// ```
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub fn wrapping_add(self, rhs: u32) -> Self {
let (d, _) = self.overflowing_add(rhs);
d
}
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
fn saturating_sub(self, rhs: u32) -> Self {
let d = self.0.saturating_sub(rhs);
// allow `unwrap_or`, it's 32bits of integer or a function pointer
#[allow(clippy::or_fun_call)]
Self::new(d).unwrap_or(Self::min_value())
}
}
impl HardDerivation {
/// construct a hard derivation from the given derivation without
/// checking the derivation is actually a hard derivation.
///
/// this function does not perform any verification and if the value
/// is not correct it will create a cascade of issues, be careful when
/// utilizing this function.
#[inline]
pub const fn new_unchecked(derivation: Derivation) -> Self {
Self(derivation)
}
/// build a hard derivation from the given `Derivation`. If the value
/// is not a hard derivation it will return an error
///
/// # Example
///
/// ```
/// # use chain_path_derivation::{Derivation, HardDerivation, DerivationError};
/// # fn func() -> Result<(), DerivationError> {
/// let derivation = Derivation::new(0x8000_0001);
/// let derivation = HardDerivation::new(derivation)?;
///
/// println!("derivation: {}", derivation);
/// # Ok(())
/// # }
/// #
/// # func().unwrap();
/// ```
#[inline]
pub fn new(derivation: Derivation) -> Result<Self, DerivationError> {
if derivation.is_hard_derivation() {
Ok(Self::new_unchecked(derivation))
} else {
Err(DerivationError::InvalidHardDerivation(derivation))
}
}
/// returns the max derivation index value
///
/// ```
/// # use chain_path_derivation::{Derivation, HardDerivation};
/// let max = HardDerivation::max_value();
/// assert_eq!(max, HardDerivation::new_unchecked(Derivation::new(0xFFFF_FFFF)));
/// ```
#[inline]
pub const fn max_value() -> Self {
Self::new_unchecked(Derivation::max_value())
}
/// returns the min derivation index value
///
/// ```
/// # use chain_path_derivation::{Derivation, HardDerivation};
/// let min = HardDerivation::min_value();
/// assert_eq!(min, HardDerivation::new_unchecked(Derivation::new(0x8000_0000)));
/// ```
#[inline]
pub const fn min_value() -> Self {
Self::new_unchecked(Derivation::new(SOFT_DERIVATION_UPPER_BOUND))
}
/// calculate `self + rhs`
///
/// Returns the tuple of the addition along with a boolean indicating whether
/// an arithmetic overflow would occur. If an overflow would have occurred
/// then the wrapped value is returned.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use chain_path_derivation::{Derivation, HardDerivation};
/// assert_eq!(
/// HardDerivation::new_unchecked(Derivation::new(0x8000_0005)).overflowing_add(2),
/// (HardDerivation::new_unchecked(Derivation::new(0x8000_0007)), false)
/// );
/// assert_eq!(
/// HardDerivation::max_value().overflowing_add(1),
/// (HardDerivation::new_unchecked(Derivation::new(0x8000_0000)), true)
/// );
/// ```
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub fn overflowing_add(self, rhs: u32) -> (Self, bool) {
let (v, b) = self.0.overflowing_add(rhs);
if v.is_hard_derivation() {
(Self::new_unchecked(v), b)
} else {
(
Self::new_unchecked(Derivation::new(v.0 + SOFT_DERIVATION_UPPER_BOUND)),
true,
)
}
}
/// saturating integer addition. Computes `self + rhs`, saturating
/// at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use chain_path_derivation::{Derivation, HardDerivation};
/// assert_eq!(
/// HardDerivation::new_unchecked(Derivation::new(0x8000_0100)).saturating_add(1),
/// HardDerivation::new_unchecked(Derivation::new(0x8000_0101))
/// );
/// assert_eq!(
/// HardDerivation::max_value().saturating_add(2048),
/// HardDerivation::max_value(),
/// );
/// ```
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub fn saturating_add(self, rhs: u32) -> Self {
let d = self.0.saturating_add(rhs);
// allow `unwrap_or`, it's 32bits of integer or a function pointer
#[allow(clippy::or_fun_call)]
Self::new(d).unwrap_or(Self::max_value())
}
/// checked integer addition. Computes `self + rhs`, returning `None` if overflow
/// would occurred.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use chain_path_derivation::{Derivation, HardDerivation};
/// assert_eq!(
/// HardDerivation::new_unchecked(Derivation::new(0x8000_0100)).checked_add(1),
/// Some(HardDerivation::new_unchecked(Derivation::new(0x8000_0101)))
/// );
/// assert_eq!(
/// HardDerivation::max_value().checked_add(2048),
/// None,
/// );
/// ```
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub fn checked_add(self, rhs: u32) -> Option<Self> {
let d = self.0.checked_add(rhs)?;
Self::new(d).ok()
}
/// Wrapping (modular) addition. Computes `self + rhs`, wrapping around the boundary
/// of the type.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use chain_path_derivation::{Derivation, HardDerivation};
/// assert_eq!(
/// HardDerivation::new_unchecked(Derivation::new(0x8000_0100)).wrapping_add(1),
/// HardDerivation::new_unchecked(Derivation::new(0x8000_0101))
/// );
/// assert_eq!(
/// HardDerivation::max_value().wrapping_add(1),
/// HardDerivation::new_unchecked(Derivation::new(0x8000_0000)),
/// );
/// ```
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub fn wrapping_add(self, rhs: u32) -> Self {
let (d, _) = self.overflowing_add(rhs);
d
}
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
fn saturating_sub(self, rhs: u32) -> Self {
let d = self.0.saturating_sub(rhs);
// allow `unwrap_or`, it's 32bits of integer or a function pointer
#[allow(clippy::or_fun_call)]
Self::new(d).unwrap_or(Self::min_value())
}
}
impl DerivationRange {
/// create a derivation range from the given range
pub fn new<R, T>(range: R) -> Self
where
R: std::ops::RangeBounds<T>,
T: Into<Derivation> + Copy,
{
use std::ops::Bound;
let start = match range.start_bound() {
Bound::Unbounded => Derivation::min_value(),
Bound::Included(b) => (*b).into(),
Bound::Excluded(b) => (*b).into().saturating_add(1),
};
let end = match range.end_bound() {
Bound::Unbounded => Derivation::max_value(),
Bound::Included(b) => (*b).into().saturating_add(1),
Bound::Excluded(b) => (*b).into(),
};
let range = std::ops::Range { start, end };
Self { range }
}
}
impl SoftDerivationRange {
/// create a SoftDerivation range from the given range
///
/// # panics
///
/// this function will panic if the bounds are not valid SoftDerivation
/// values.
pub fn new<R, T>(range: R) -> Self
where
R: std::ops::RangeBounds<T>,
T: TryInto<SoftDerivation> + Copy,
<T as std::convert::TryInto<SoftDerivation>>::Error: std::error::Error,
{
use std::ops::Bound;
let start = match range.start_bound() {
Bound::Unbounded => Ok(SoftDerivation::min_value()),
Bound::Included(b) => (*b).try_into(),
Bound::Excluded(b) => (*b).try_into().map(|v| v.saturating_add(1)),
};
let end = match range.end_bound() {
Bound::Unbounded => Ok(SoftDerivation::max_value()),
Bound::Included(b) => (*b).try_into().map(|v| v.saturating_add(1)),
Bound::Excluded(b) => (*b).try_into(),
};
let start =
start.unwrap_or_else(|e| panic!("min bound is not a valid SoftDerivation, {:?}", e));
let end =
end.unwrap_or_else(|e| panic!("max bound is not a valid SoftDerivation, {:?}", e));
let range = std::ops::Range { start, end };
Self { range }
}
}
impl HardDerivationRange {
/// create a HardDerivation range from the given range
///
/// # panics
///
/// this function will panic if the bounds are not valid HardDerivation
/// values.
pub fn new<R, T>(range: R) -> Self
where
R: std::ops::RangeBounds<T>,
T: TryInto<HardDerivation> + Copy,
<T as std::convert::TryInto<HardDerivation>>::Error: std::error::Error,
{
use std::ops::Bound;
let start = match range.start_bound() {
Bound::Unbounded => Ok(HardDerivation::min_value()),
Bound::Included(b) => (*b).try_into(),
Bound::Excluded(b) => (*b).try_into().map(|v| v.saturating_add(1)),
};
let end = match range.end_bound() {
Bound::Unbounded => Ok(HardDerivation::max_value()),
Bound::Included(b) => (*b).try_into().map(|v| v.saturating_add(1)),
Bound::Excluded(b) => (*b).try_into(),
};
let start =
start.unwrap_or_else(|e| panic!("min bound is not a valid HardDerivation, {:?}", e));
let end =
end.unwrap_or_else(|e| panic!("max bound is not a valid HardDerivation, {:?}", e));
let range = std::ops::Range { start, end };
Self { range }
}
}
/* Iterator **************************************************************** */
impl Iterator for DerivationRange {
type Item = Derivation;
fn next(&mut self) -> Option<Self::Item> {
let start = self.range.start;
if self.range.contains(&start) {
self.range.start = start.saturating_add(1);
Some(start)
} else {
None
}
}
}
impl Iterator for SoftDerivationRange {
type Item = SoftDerivation;
fn next(&mut self) -> Option<Self::Item> {
let start = self.range.start;
if self.range.contains(&start) {
self.range.start = start.saturating_add(1);
Some(start)
} else {
None
}
}
}
impl Iterator for HardDerivationRange {
type Item = HardDerivation;
fn next(&mut self) -> Option<Self::Item> {
let start = self.range.start;
if self.range.contains(&start) {
self.range.start = start.saturating_add(1);
Some(start)
} else {
None
}
}
}
impl ExactSizeIterator for DerivationRange {
fn len(&self) -> usize {
let Derivation(start) = self.range.start;
let Derivation(end) = self.range.end;
(end - start) as usize
}
}
impl ExactSizeIterator for SoftDerivationRange {
fn len(&self) -> usize {
let Derivation(start) = self.range.start.0;
let Derivation(end) = self.range.end.0;
(end - start) as usize
}
}
impl ExactSizeIterator for HardDerivationRange {
fn len(&self) -> usize {
let Derivation(start) = self.range.start.0;
let Derivation(end) = self.range.end.0;
(end - start) as usize
}
}
impl DoubleEndedIterator for DerivationRange {
fn next_back(&mut self) -> Option<Self::Item> {
let next_back = self.range.end.saturating_sub(0);
if self.range.contains(&next_back) {
self.range.end = next_back;
Some(next_back)
} else {
None
}
}
}
impl DoubleEndedIterator for SoftDerivationRange {
fn next_back(&mut self) -> Option<Self::Item> {
let next_back = self.range.end.saturating_sub(0);
if self.range.contains(&next_back) {
self.range.end = next_back;
Some(next_back)
} else {
None
}
}
}
impl DoubleEndedIterator for HardDerivationRange {
fn next_back(&mut self) -> Option<Self::Item> {
let next_back = self.range.end.saturating_sub(0);
if self.range.contains(&next_back) {
self.range.end = next_back;
Some(next_back)
} else {
None
}
}
}
impl std::iter::FusedIterator for DerivationRange {}
impl std::iter::FusedIterator for SoftDerivationRange {}
impl std::iter::FusedIterator for HardDerivationRange {}
/* Default ***************************************************************** */
impl Default for SoftDerivation {
fn default() -> Self {
Self::min_value()
}
}
impl Default for HardDerivation {
fn default() -> Self {
Self::min_value()
}
}
/* Display ***************************************************************** */
impl Display for Derivation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.is_soft_derivation() {
self.0.fmt(f)
} else {
write!(f, "'{}", self.0 - SOFT_DERIVATION_UPPER_BOUND)
}
}
}
impl Display for SoftDerivation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl Display for HardDerivation {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
/* FromStr ***************************************************************** */
#[derive(Error, Debug)]
pub enum ParseDerivationError {
#[error("Not a valid derivation value")]
NaN(
#[source]
#[from]
std::num::ParseIntError,
),
#[error("Not a valid derivation")]
InvalidDerivation(
#[source]
#[from]
DerivationError,
),
}
impl str::FromStr for Derivation {
type Err = ParseDerivationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Some(s) = s.strip_prefix('\'') {
s.parse::<u32>()
.map(|v| v + SOFT_DERIVATION_UPPER_BOUND)
.map(Derivation)
.map_err(ParseDerivationError::NaN)
} else {
s.parse().map(Derivation).map_err(ParseDerivationError::NaN)
}
}
}
impl str::FromStr for SoftDerivation {
type Err = ParseDerivationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let derivation = s.parse()?;
Ok(Self::new(derivation)?)
}
}
impl str::FromStr for HardDerivation {
type Err = ParseDerivationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let derivation = s.parse()?;
Ok(Self::new(derivation)?)
}
}
/* Conversion ************************************************************** */
impl From<u32> for Derivation {
fn from(v: u32) -> Derivation {
Derivation(v)
}
}
impl From<Derivation> for u32 {
fn from(d: Derivation) -> Self {
d.0
}
}
impl From<SoftDerivation> for Derivation {
fn from(d: SoftDerivation) -> Self {
d.0
}
}
impl From<HardDerivation> for Derivation {
fn from(d: HardDerivation) -> Self {
d.0
}
}
impl TryFrom<Derivation> for SoftDerivation {
type Error = DerivationError;
fn try_from(value: Derivation) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl TryFrom<Derivation> for HardDerivation {
type Error = DerivationError;
fn try_from(value: Derivation) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl TryFrom<u32> for SoftDerivation {
type Error = DerivationError;
fn try_from(value: u32) -> Result<Self, Self::Error> {
Self::new(Derivation::new(value))
}
}
impl TryFrom<u32> for HardDerivation {
type Error = DerivationError;
fn try_from(value: u32) -> Result<Self, Self::Error> {
Self::new(Derivation::new(value))
}
}
/* Deref ******************************************************************* */
impl Deref for Derivation {
type Target = u32;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Deref for SoftDerivation {
type Target = u32;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
impl Deref for HardDerivation {
type Target = u32;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::{Arbitrary, Gen};
impl Arbitrary for Derivation {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
Derivation(u32::arbitrary(g))
}
}
impl Arbitrary for SoftDerivation {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let derivation = Derivation(u32::arbitrary(g) % SOFT_DERIVATION_UPPER_BOUND);
Self::new(derivation).expect("Generated an invalid value for soft derivation")
}
}
impl Arbitrary for HardDerivation {
fn arbitrary<G: Gen>(g: &mut G) -> Self {
let derivation = Derivation(
u32::arbitrary(g) % SOFT_DERIVATION_UPPER_BOUND + SOFT_DERIVATION_UPPER_BOUND,
);
Self::new(derivation).expect("Generated an invalid value for hard derivation")
}
}
#[test]
fn derivation_iterator_1() {
let range = DerivationRange::new(..8);
let expected = vec![
Derivation::new(0),
Derivation::new(1),
Derivation::new(2),
Derivation::new(3),
Derivation::new(4),
Derivation::new(5),
Derivation::new(6),
Derivation::new(7),
];
for (address, expected) in range.zip(expected) {
assert_eq!(address, expected);
}
}
#[test]
fn derivation_iterator_2() {
let range = DerivationRange::new(4..8);
let expected = vec![
Derivation::new(4),
Derivation::new(5),
Derivation::new(6),
Derivation::new(7),
];
for (address, expected) in range.zip(expected) {
assert_eq!(address, expected);
}
}
#[test]
fn derivation_iterator_3() {
let range = DerivationRange::new(4..=8);
let expected = vec![
Derivation::new(4),
Derivation::new(5),
Derivation::new(6),
Derivation::new(7),
Derivation::new(8),
];
for (address, expected) in range.zip(expected) {
assert_eq!(address, expected);
}
}
#[test]
fn derivation_iterator_4() {
let range = DerivationRange::new::<_, u32>(..);
assert_eq!(range.len(), u32::max_value() as usize);
}
#[test]
fn to_string() {
assert_eq!(Derivation(0).to_string(), "0");
assert_eq!(Derivation(9289).to_string(), "9289");
assert_eq!(Derivation(SOFT_DERIVATION_UPPER_BOUND).to_string(), "'0");
assert_eq!(
Derivation(SOFT_DERIVATION_UPPER_BOUND + 9289).to_string(),
"'9289"
);
}
#[quickcheck]
fn fmt_parse_derivation(derivation: Derivation) -> bool {
let s = derivation.to_string();
let v = s.parse::<Derivation>().unwrap();
v == derivation
}
#[quickcheck]
fn fmt_parse_soft_derivation(derivation: SoftDerivation) -> bool {
let s = derivation.to_string();
let v = s.parse::<SoftDerivation>().unwrap();
v == derivation
}
#[quickcheck]
fn fmt_parse_hard_derivation(derivation: HardDerivation) -> bool {
let s = derivation.to_string();
let v = s.parse::<HardDerivation>().unwrap();
v == derivation
}
}