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
/*! Parallel bitfield access.

This module provides parallel, multiple-bit, access to a `BitSlice`. This
functionality permits the use of `BitSlice` as a library-level implementation of
the bitfield language feature found in C and C++.

The `BitField` trait is not sealed against client implementation, as there is no
useful way to automatically use a `Cursor` implementation to provide a universal
behavior. As such, the trait has some requirements that the compiler cannot
enforce for client implementations.

# Batch Behavior

The purpose of this trait is to provide access to arbitrary bit regions as if
they were an ordinary memory location. As such, it is important for
implementations of this trait to provide shift/mask register transfer behavior
where possible, for as wide a span as possible in each action. Implementations
of this trait should *not* use bit-by-bit iteration.

# Register Bit Order Preservation

As a default assumption – user orderings *may* violate this, but *should* not –
each element of slice memory used to store part of a value should not reorder
the value bits. Transfer between slice memory and a CPU register should solely
be an ordinary value load or store between memory and the register, and a
shift/mask operation to select the part of the value that is live.

# Endianness

The `_le` and `_be` methods of `BitField` refer to the order in which
`T: BitStore` elements of the slice are assigned significance when containing
fragments of a stored data value. Within any `T` element, the order of its
constituent bytes is *not* governed by the `BitField` trait method.

The provided `BitOrder` implementors `Lsb0` and `Msb0` use the local machine’s
byte ordering. Other cursors *may* implement ordering of bytes within `T`
elements differently, for instance by calling `.to_be_bytes` before store and
`from_be_bytes` after load,
!*/

use crate::{
	access::BitAccess,
	order::{
		Lsb0,
		Msb0,
	},
	slice::BitSlice,
	store::BitStore,
};

use core::mem;

use either::Either;

#[cfg(feature = "alloc")]
use crate::{
	boxed::BitBox,
	order::BitOrder,
	vec::BitVec,
};

/** Permit a specific `BitSlice` to be used for C-style bitfield access.

Orders that permit batched access to regions of memory are enabled to load data
from a `BitSlice` and store data to a `BitSlice` with faster behavior than the
default bit-by-bit traversal.

This trait transfers data between a `BitSlice` and an element. The trait
functions always place the live bit region against the least significant bit
edge of the transfer element (return value for `load`, argument for `store`).

Implementations are encouraged to preserve in-memory bit ordering, so that call
sites can provide a value pattern that the user can clearly see matches what
they expect for memory ordering. These methods merely move data from a fixed
location in an element to a variable location in the slice.

Methods should be called as `bits[start .. end].load_or_store()`, where the
range subslice selects up to but no more than the `U::BITS` element width.
**/
pub trait BitField {
	/// Load the sequence of bits from `self` into the least-significant bits of
	/// an element.
	///
	/// This can load any fundamental type which implements `BitStore`. Other
	/// Rust fundamental types which do not implement it must be recast
	/// appropriately by the user.
	///
	/// The default implementation of this function calls [`load_le`] on
	/// little-endian byte-ordered CPUs, and [`load_be`] on big-endian
	/// byte-ordered CPUs.
	///
	/// # Parameters
	///
	/// - `&self`: A read reference to some bits in memory. This slice must be
	///   trimmed to have a width no more than the `U::BITS` width of the type
	///   being loaded. This can be accomplished with range indexing on a larger
	///   slice.
	///
	/// # Returns
	///
	/// A `U` value whose least `self.len()` significant bits are filled with
	/// the bits of `self`.
	///
	/// # Panics
	///
	/// If `self` is empty, or wider than a single `U` element, this panics.
	///
	/// [`load_be`]: #tymethod.load_be
	/// [`load_le`]: #tymethod.load_le
	fn load<U>(&self) -> U
	where U: BitStore {
		#[cfg(target_endian = "little")]
		return self.load_le();

		#[cfg(target_endian = "big")]
		return self.load_be();
	}

	/// Load from `self`, using little-endian element ordering.
	///
	/// This function interprets a multi-element slice as having its least
	/// significant chunk in the low memory address, and its most significant
	/// chunk in the high memory address. Each element `T` is still interpreted
	/// from individual bytes according to the local CPU ordering.
	///
	/// # Parameters
	///
	/// - `&self`: A read reference to some bits in memory. This slice must be
	///   trimmed to have a width no more than the `U::BITS` width of the type
	///   being loaded. This can be accomplished with range indexing on a larger
	///   slice.
	///
	/// # Returns
	///
	/// A `U` value whose least `self.len()` significant bits are filled with
	/// the bits of `self`. If `self` spans multiple `T` elements, then the
	/// lowest-address `T` is interpreted as containing the least significant
	/// bits of the `U` return value, and the highest-address `T` is interpreted
	/// as containing its most significant bits.
	///
	/// # Panics
	///
	/// If `self` is empty, or wider than a single `U` element, this panics.
	fn load_le<U>(&self) -> U
	where U: BitStore;

	/// Load from `self`, using big-endian element ordering.
	///
	/// This function interprets a multi-element slice as having its most
	/// significant chunk in the low memory address, and its least significant
	/// chunk in the high memory address. Each element `T` is still interpreted
	/// from individual bytes according to the local CPU ordering.
	///
	/// # Parameters
	///
	/// - `&self`: A read reference to some bits in memory. This slice must be
	///   trimmed to have a width no more than the `U::BITS` width of the type
	///   being loaded. This can be accomplished with range indexing on a larger
	///   slice.
	///
	/// # Returns
	///
	/// A `U` value whose least `self.len()` significant bits are filled with
	/// the bits of `self`. If `self` spans multiple `T` elements, then the
	/// lowest-address `T` is interpreted as containing the most significant
	/// bits of the `U` return value, and the highest-address `T` is interpreted
	/// as containing its least significant bits.
	fn load_be<U>(&self) -> U
	where U: BitStore;

	/// Stores a sequence of bits from the user into the domain of `self`.
	///
	/// This can store any fundamental type which implements `BitStore`. Other
	/// Rust fundamental types which do not implement it must be recast
	/// appropriately by the user.
	///
	/// The default implementation of this function calls [`store_le`] on
	/// little-endian byte-ordered CPUs, and [`store_be`] on big-endian
	/// byte-ordered CPUs.
	///
	/// # Parameters
	///
	/// - `&mut self`: A write reference to some bits in memory. This slice must
	///   be trimmed to have a width no more than the `U::BITS` width of the
	///   type being stored. This can be accomplished with range indexing on a
	///   larger slice.
	/// - `value`: A value, whose `self.len()` least significant bits will be
	///   stored into `self`.
	///
	/// # Behavior
	///
	/// The `self.len()` least significant bits of `value` are written into the
	/// domain of `self`.
	///
	/// # Panics
	///
	/// If `self` is empty, or wider than a single `U` element, this panics.
	///
	/// [`store_be`]: #tymethod.store_be
	/// [`store_le`]: #tymethod.store_le
	fn store<U>(&mut self, value: U)
	where U: BitStore {
		#[cfg(target_endian = "little")]
		self.store_le(value);

		#[cfg(target_endian = "big")]
		self.store_be(value);
	}

	/// Store into `self`, using little-endian element ordering.
	///
	/// This function interprets a multi-element slice as having its least
	/// significant chunk in the low memory address, and its most significant
	/// chunk in the high memory address. Each element `T` is still interpreted
	/// from individual bytes according to the local CPU ordering.
	///
	/// # Parameters
	///
	/// - `&mut self`: A write reference to some bits in memory. This slice must
	///   be trimmed to have a width no more than the `U::BITS` width of the
	///   type being stored. This can be accomplished with range indexing on a
	///   larger slice.
	/// - `value`: A value, whose `self.len()` least significant bits will be
	///   stored into `self`.
	///
	/// # Behavior
	///
	/// The `self.len()` least significant bits of `value` are written into the
	/// domain of `self`. If `self` spans multiple `T` elements, then the
	/// lowest-address `T` is interpreted as containing the least significant
	/// bits of the `U` return value, and the highest-address `T` is interpreted
	/// as containing its most significant bits.
	///
	/// # Panics
	///
	/// If `self` is empty, or wider than a single `U` element, this panics.
	fn store_le<U>(&mut self, value: U)
	where U: BitStore;

	/// Store into `self`, using big-endian element ordering.
	///
	/// This function interprets a multi-element slice as having its most
	/// significant chunk in the low memory address, and its least significant
	/// chunk in the high memory address. Each element `T` is still interpreted
	/// from individual bytes according to the local CPU ordering.
	///
	/// # Parameters
	///
	/// - `&mut self`: A write reference to some bits in memory. This slice must
	///   be trimmed to have a width no more than the `U::BITS` width of the
	///   type being stored. This can be accomplished with range indexing on a
	///   larger slice.
	/// - `value`: A value, whose `self.len()` least significant bits will be
	///   stored into `self`.
	///
	/// # Behavior
	///
	/// The `self.len()` least significant bits of `value` are written into the
	/// domain of `self`. If `self` spans multiple `T` elements, then the
	/// lowest-address `T` is interpreted as containing the most significant
	/// bits of the `U` return value, and the highest-address `T` is interpreted
	/// as containing its least significant bits.
	///
	/// # Panics
	///
	/// If `self` is empty, or wider than a single `U` element, this panics.
	fn store_be<U>(&mut self, value: U)
	where U: BitStore;
}

impl<T> BitField for BitSlice<Lsb0, T>
where T: BitStore {
	fn load_le<U>(&self) -> U
	where U: BitStore {
		let len = self.len();
		if !(1 ..= U::BITS as usize).contains(&len) {
			panic!("Cannot load {} bits from a {}-bit region", U::BITS, len);
		}

		match self.bitptr().domain().splat() {
			/* The live bits are in the interior of a single element.

			This path only needs to load the element, shift it right by the
			distance from LSedge to the live region, and mask it for the length
			of `self`.
			*/
			Either::Right((head, elt, _)) =>
				resize((elt.load() >> *head) & mask_for::<T>(len)),
			/* The live region touches at least one element edge.

			This block reads chunks from the slice memory into an accumulator,
			from the most-significant chunk to the least-significant. Each read
			must collect the live section of the chunk into a temporary, then
			shift the accumulator left by the chunk’s bit width, then write the
			temporary into the newly-vacated least significant bits of the
			accumulator.
			*/
			Either::Left((head, body, tail)) => {
				let mut accum = 0usize;

				//  If the tail exists, it contains the most significant chunk
				//  of the value, on the LSedge side.
				if let Some((tail, t)) = tail {
					//  Load, mask, resize, and store. No other data is present.
					accum = resize(tail.load() & mask_for::<T>(*t as usize));
				}
				//  Read the body elements, from high address to low, into the
				//  accumulator.
				if let Some(elts) = body {
					for elt in elts.iter().rev() {
						let val: usize = resize(elt.load());
						accum <<= T::BITS;
						accum |= val;
					}
				}
				//  If the head exists, it contains the least significant chunk
				//  of the value, on the MSedge side.
				if let Some((h, head)) = head {
					//  Get the live region’s distance from the LSedge.
					let lsedge = *h;
					//  Find the region width (MSedge to head).
					let width = T::BITS - lsedge;
					//  Load the element, shift down to LSedge, and resize.
					let val: usize = resize(head.load() >> lsedge);
					accum <<= width;
					accum |= val;
				}

				resize(accum)
			},
		}
	}

	fn load_be<U>(&self) -> U
	where U: BitStore {
		let len = self.len();
		if !(1 ..= U::BITS as usize).contains(&len) {
			panic!("Cannot load {} bits from a {}-bit region", U::BITS, len);
		}

		match self.bitptr().domain().splat() {
			/* The live bits are in the interior of a single element.

			This path only needs to load the element, shift it right by the
			distance from LSedge to the live region, and mask it for the length
			of `self`.
			*/
			Either::Right((head, elt, _)) =>
				resize((elt.load() >> *head) & mask_for::<T>(len)),
			/* The live region touches at least one element edge.

			This block reads chunks from the slice memory into an accumulator,
			from the most-significant chunk to the least-significant. Each read
			must collect the live section of the chunk into a temporary, then
			shift the accumulator left by the chunk’s width, then write the
			temporary into the newly-vacated least significant bits of the
			accumulator.
			*/
			Either::Left((head, body, tail)) => {
				let mut accum = 0usize;

				//  If the head exists, it contains the most significant chunk
				//  of the value, on the MSedge side.
				if let Some((h, head)) = head {
					//  Load, move, resize, and store. No other data is present.
					accum = resize(head.load() >> *h);
				}
				//  Read the body elements, from low address to high, into the
				//  accumulator.
				if let Some(elts) = body {
					for elt in elts.iter() {
						let val: usize = resize(elt.load());
						accum <<= T::BITS;
						accum |= val;
					}
				}
				//  If the tail exists, it contains the least significant chunk
				//  of the value, on the LSedge side.
				if let Some((tail, t)) = tail {
					//  Get the live region’s width.
					let width = *t as usize;
					//  Load, mask, and resize.
					let val: usize = resize(tail.load() & mask_for::<T>(width));
					//  Shift the accumulator by the live width, and store.
					accum <<= width;
					accum |= val;
				}

				resize(accum)
			},
		}
	}

	fn store_le<U>(&mut self, value: U)
	where U: BitStore {
		let len = self.len();
		if !(1 ..= U::BITS as usize).contains(&len) {
			panic!("Cannot store {} bits in a {}-bit region", U::BITS, len);
		}

		let value = value & mask_for(len);
		match self.bitptr().domain().splat() {
			/* The live region is in the interior of a single element.

			The `value` is shifted left by the region’s distance from the
			LSedge, then written directly into place.
			*/
			Either::Right((head, elt, _)) => {
				//  Get the region’s distance from the LSedge.
				let lsedge = *head;
				//  Erase the live region.
				elt.clear_bits(!(mask_for::<T>(len) << lsedge));
				//  Shift the value to fit the region, and write.
				elt.set_bits(resize::<U, T>(value) << lsedge);
			},
			/* The live region touches at least one element edge.

			This block writes chunks from the value into slice memory, from the
			least-significant chunk to the most-significant. Each write moves
			a slice chunk’s width of bits from the LSedge of the value into
			memory, then shifts the value right by that width.
			*/
			Either::Left((head, body, tail)) => {
				let mut value: usize = resize(value);

				//  If the head exists, it contains the least significant chunk
				//  of the value, on the MSedge side.
				if let Some((h, head)) = head {
					//  Get the region distance from the LSedge.
					let lsedge = *h;
					//  Find the region width (MSedge to head).
					let width = T::BITS - lsedge;
					//  Take the region-width LSedge bits of the value.
					let val = value & mask_for::<usize>(width as usize);
					//  Erase the region.
					head.clear_bits(T::TRUE >> width);
					//  Shift the snippet to fit the region, and write.
					head.set_bits(resize::<usize, T>(val) << lsedge);
					//  Discard the now-written bits from the value.
					value >>= width;
				}
				//  Write into the body elements, from low address to high, from
				//  the value.
				if let Some(elts) = body {
					for elt in elts.iter() {
						elt.store(resize(value));
						value >>= T::BITS;
					}
				}
				//  If the tail exists, it contains the most significant chunk
				//  of the value, on the LSedge side.
				if let Some((tail, t)) = tail {
					//  Get the region width.
					let width = *t;
					//  Take the region-width LSedge bits of the value.
					let val = value & mask_for::<usize>(width as usize);
					//  Erase the region.
					tail.clear_bits(T::TRUE << width);
					//  Write the snippet into the region.
					tail.set_bits(resize(val));
				}
			},
		}
	}

	fn store_be<U>(&mut self, value: U)
	where U: BitStore {
		let len = self.len();
		if !(1 ..= U::BITS as usize).contains(&len) {
			panic!("Cannot store {} bits in a {}-bit region", U::BITS, len);
		}

		let value = value & mask_for(len);
		match self.bitptr().domain().splat() {
			/* The live region is in the interior of a single element.

			The `value` is shifted left by the region’s distance from the
			LSedge, then written directly into place.
			*/
			Either::Right((head, elt, _)) => {
				//  Get the region’s distance from the LSedge.
				let lsedge = *head;
				//  Erase the live region.
				elt.clear_bits(!(mask_for::<T>(len) << lsedge));
				//  Shift the value to fit the region, and write.
				elt.set_bits(resize::<U, T>(value) << lsedge);
			},
			Either::Left((head, body, tail)) => {
				let mut value: usize = resize(value);

				//  If the tail exists, it contains the least significant chunk
				//  of the value, on the LSedge side.
				if let Some((tail, t)) = tail {
					//  Get the region width.
					let width = *t;
					//  Take the region-width LSedge bits of the value.
					let val = value & mask_for::<usize>(width as usize);
					//  Erase the region.
					tail.clear_bits(T::TRUE << width);
					//  Write the snippet into the region.
					tail.set_bits(resize(val));
					//  Discard the now-written bits from the value.
					value >>= width;
				}
				//  Write into the body elements, from high address to low, from
				//  the value.
				if let Some(elts) = body {
					for elt in elts.iter().rev() {
						elt.store(resize(value));
						value >>= T::BITS;
					}
				}
				//  If the head exists, it contains the most significant chunk
				//  of the value, on the MSedge side.
				if let Some((h, head)) = head {
					//  Get the region distance from the LSedge.
					let lsedge = *h;
					//  Find the region width (MSedge to head).
					let width = T::BITS - lsedge;
					//  Take the region-width LSedge bits of the value.
					let val = value & mask_for::<usize>(width as usize);
					//  Erase the region.
					head.clear_bits(T::TRUE >> width);
					//  Shift the snippet to fit the region, and write.
					head.set_bits(resize::<usize, T>(val) << lsedge);
				}
			},
		}
	}
}

impl<T> BitField for BitSlice<Msb0, T>
where T: BitStore {
	fn load_le<U>(&self) -> U
	where U: BitStore {
		let len = self.len();
		if !(1 ..= U::BITS as usize).contains(&len) {
			panic!("Cannot load {} bits from a {}-bit region", U::BITS, len);
		}

		match self.bitptr().domain().splat() {
			/* The live bits are in the interior of a single element.

			This path only needs to load the element, shift it right by the
			distance from LSedge to the live region, and mask it for the length
			of `self`.
			*/
			Either::Right((_, elt, tail)) =>
				resize((elt.load() >> (T::BITS - *tail)) & mask_for::<T>(len)),
			/* The live region touches at least one element edge.

			This block reads chunks from the slice memory into an accumulator,
			from the most-significant chunk to the least-significant. Each read
			must collect the live section of the chunk into a temporary, then
			shift the accumulator left by the chunk’s bit width, then write the
			temporary into the newly-vacated least significant bits of the
			accumulator.
			*/
			Either::Left((head, body, tail)) => {
				let mut accum = 0usize;

				//  If the tail exists, it contains the most significant chunk
				//  of the value, on the MSedge side.
				if let Some((tail, t)) = tail {
					//  Find the live region’s distance from the LSedge.
					let lsedge = T::BITS - *t;
					//  Load, move, resize, and store. No other data is present.
					accum = resize(tail.load() >> lsedge);
				}
				//  Read the body elements, from high address to low, into the
				//  accumulator.
				if let Some(elts) = body {
					for elt in elts.iter().rev() {
						let val: usize = resize(elt.load());
						accum <<= T::BITS;
						accum |= val;
					}
				}
				//  If the head exists, it contains the least significant chunk
				//  of the value, on the LSedge side.
				if let Some((h, head)) = head {
					//  Find the region width (head to LSedge).
					let width = (T::BITS - *h) as usize;
					//  Load the element, mask, and resize.
					let val: usize = resize(head.load() & mask_for::<T>(width));
					accum <<= width;
					accum |= val;
				}

				resize(accum)
			},
		}
	}

	fn load_be<U>(&self) -> U
	where U: BitStore {
		let len = self.len();
		if !(1 ..= U::BITS as usize).contains(&len) {
			panic!("Cannot load {} bits from a {}-bit region", U::BITS, len);
		}

		match self.bitptr().domain().splat() {
			/* The live bits are in the interior of a single element.

			This path only needs to load the element, shift it right by the
			distance from LSedge to the live region, and mask it for the length
			of `self`.
			*/
			Either::Right((_, elt, tail)) =>
				resize((elt.load() >> (T::BITS - *tail)) & mask_for::<T>(len)),
			/* The live region touches at least one element edge.

			This block reads chunks from the slice memory into an accumulator,
			from the most-significant chunk to the least-significant. Each read
			must collect the live section of the chunk into a temporary, then
			shift the accumulator left by the chunk’s bit width, then write the
			temporary into the newly-vacated least significant bits of the
			accumulator.
			*/
			Either::Left((head, body, tail)) => {
				let mut accum = 0usize;

				//  If the head exists, it contains the most significant chunk
				//  of the value, on the LSedge side.
				if let Some((h, head)) = head {
					//  Find the region width (head to LSedge).
					let width = T::BITS - *h;
					//  Load, mask, resize, and store. No other data is present.
					accum = resize(head.load() & mask_for::<T>(width as usize));
				}
				//  Read the body elements, from low address to high, into the
				//  accumulator.
				if let Some(elts) = body {
					for elt in elts.iter() {
						let val: usize = resize(elt.load());
						accum <<= T::BITS;
						accum |= val;
					}
				}
				//  If the tail exists, it contains the least significant chunk
				//  of the value, on the MSedge side.
				if let Some((tail, t)) = tail {
					//  Find the live region’s distance from LSedge.
					let lsedge = T::BITS - *t;
					//  Load the element, shift down to LSedge, and resize.
					let val: usize = resize(tail.load() >> lsedge);
					accum <<= *t;
					accum |= val;
				}

				resize(accum)
			},
		}
	}

	fn store_le<U>(&mut self, value: U)
	where U: BitStore {
		let len = self.len();
		if !(1 ..= U::BITS as usize).contains(&len) {
			panic!("Cannot store {} bits in a {}-bit region", U::BITS, len);
		}

		let value = value & mask_for(len);
		match self.bitptr().domain().splat() {
			/* The live region is in the interior of a single element.

			The `value` is shifted left by the region’s distance from the
			LSedge, then written directly into place.
			*/
			Either::Right((_, elt, tail)) => {
				//  Get the region’s distance from the LSedge.
				let lsedge = T::BITS - *tail;
				//  Erase the live region.
				elt.clear_bits(!(mask_for::<T>(len) << lsedge));
				//  Shift the value to fit the region, and write.
				elt.set_bits(resize::<U, T>(value) << lsedge);
			},
			/* The live region touches at least one element edge.

			This block writes chunks from the value into slice memory, from the
			least-significant chunk to the most-significant. Each write moves a
			slice chunk’s width of bits from the LSedge of the value into
			memory, then shifts the value right by that width.
			*/
			Either::Left((head, body, tail)) => {
				let mut value: usize = resize(value);

				//  If the head exists, it contains the least significant chunk
				//  of the value, on the LSedge side.
				if let Some((h, head)) = head {
					//  Get the region width (head to LSedge).
					let width = T::BITS - *h;
					//  Take the region-width LSedge bits of the value.
					let val = value & mask_for::<usize>(width as usize);
					//  Erase the region.
					head.clear_bits(T::TRUE << width);
					//  Write the snippet into the region.
					head.set_bits(resize(val));
					//  Discard the now-written bits from the value.
					value >>= width;
				}
				//  Write into the body elements, from low address to high, from
				//  the value.
				if let Some(elts) = body {
					for elt in elts.iter() {
						elt.store(resize(value));
						value >>= T::BITS;
					}
				}
				//  If the tail exists, it contains the most significant chunk
				//  of the value, on the MSedge side.
				if let Some((tail, t)) = tail {
					//  Get the region width.
					let width = *t;
					//  Find the region distance from the LSedge.
					let lsedge = T::BITS - width;
					//  Take the region-width LSedge bits of the value.
					let val = value & mask_for::<usize>(width as usize);
					//  Erase the region.
					tail.clear_bits(T::TRUE >> width);
					//  Shift the snippet to fit the region, and write.
					tail.set_bits(resize::<usize, T>(val) << lsedge);
				}
			},
		}
	}

	fn store_be<U>(&mut self, value: U)
	where U: BitStore {
		let len = self.len();
		if !(1 ..= U::BITS as usize).contains(&len) {
			panic!("Cannot store {} bits in a {}-bit region", U::BITS, len);
		}

		let value = value & mask_for(len);
		match self.bitptr().domain().splat() {
			/* The live region is in the interior of a single element.

			The `value` is shifted left by the region’s distance from the
			LSedge, then written directly into place.
			*/
			Either::Right((_, elt, tail)) => {
				//  Get the region’s distance from the LSedge.
				let lsedge = T::BITS - *tail;
				//  Erase the live region.
				elt.clear_bits(!(mask_for::<T>(len) << lsedge));
				//  Shift the value to fit the region, and write.
				elt.set_bits(resize::<U, T>(value) << lsedge);
			},
			/* The live region touches at least one element edge.

			This block writes chunks from the value into slice memory, from the
			least-significant chunk to the most-significant. Each write moves a
			slice chunk’s width of bits from the LSedge of the value into
			memory, then shifts the value right by that width.
			*/
			Either::Left((head, body, tail)) => {
				let mut value: usize = resize(value);

				//  If the tail exists, it contains the least significant chunk
				//  of the value, on the MSedge side.
				if let Some((tail, t)) = tail {
					//  Get the region width (MSedge to tail).
					let width = *t;
					//  Find the region distance from the LSedge.
					let lsedge = T::BITS - width;
					//  Take the region-width LSedge bits of the value.
					let val = value & mask_for::<usize>(width as usize);
					//  Erase the region.
					tail.clear_bits(T::TRUE >> width);
					//  Shift the snippet to fit the region, and write.
					tail.set_bits(resize::<usize, T>(val) << lsedge);
					//  Discard the now-written bits from the value.
					value >>= width;
				}
				//  Write into the body elements, from high address to low, from
				//  the value.
				if let Some(elts) = body {
					for elt in elts.iter().rev() {
						elt.store(resize(value));
						value >>= T::BITS;
					}
				}
				//  If the head exists, it contains the most significant chunk
				//  of the value, on the LSedge side.
				if let Some((h, head)) = head {
					//  Find the region width.
					let width = T::BITS - *h;
					//  Take the region-width LSedge bits of the value.
					let val = value & mask_for::<usize>(width as usize);
					//  Erase the region.
					head.clear_bits(T::TRUE << width);
					//  Write the snippet into the region.
					head.set_bits(resize(val));
				}
			},
		}
	}
}

#[cfg(feature = "alloc")]
impl<O, T> BitField for BitBox<O, T>
where O: BitOrder, T: BitStore, BitSlice<O, T>: BitField {
	fn load_le<U>(&self) -> U
	where U: BitStore {
		self.as_bitslice().load_le()
	}

	fn load_be<U>(&self) -> U
	where U: BitStore {
		self.as_bitslice().load_be()
	}

	fn store_le<U>(&mut self, value: U)
	where U: BitStore {
		self.as_mut_bitslice().store_le(value)
	}

	fn store_be<U>(&mut self, value: U)
	where U: BitStore {
		self.as_mut_bitslice().store_be(value)
	}
}

#[cfg(feature = "alloc")]
impl<O, T> BitField for BitVec<O, T>
where O: BitOrder, T: BitStore, BitSlice<O, T>: BitField {
	fn load_le<U>(&self) -> U
	where U: BitStore {
		self.as_bitslice().load_le()
	}

	fn load_be<U>(&self) -> U
	where U: BitStore {
		self.as_bitslice().load_be()
	}

	fn store_le<U>(&mut self, value: U)
	where U: BitStore {
		self.as_mut_bitslice().store_le(value)
	}

	fn store_be<U>(&mut self, value: U)
	where U: BitStore {
		self.as_mut_bitslice().store_be(value)
	}
}

/** Safely computes an LS-edge bitmask for a value of some length.

The shift operators panic when the shift amount equals or exceeds the type
width, but this module must be able to produce a mask for exactly the type
width. This function correctly handles that case.

# Parameters

- `len`: The width in bits of the value stored in an element `T`.

# Type Parameters

- `T`: The element type for which the mask is computed.

# Returns

An LS-edge-aligned bitmask of `len` bits. All bits higher than the `len`th are
zero.
**/
#[inline]
fn mask_for<T>(len: usize) -> T
where T: BitStore {
	let len = len as u8;
	if len >= T::BITS {
		T::TRUE
	}
	else {
		!(T::TRUE << len)
	}
}

/** Resizes a value from one fundamental type to another.

This function uses `usize` as the intermediate type (as it is the largest
`BitStore` implementor on all supported targets), and either zero-extends or
truncates the source value to be valid as the destination type. This is
essentially a generic-aware version of the `as` operator.

# Parameters

- `value`: Any value to be resized.

# Type Parameters

- `T`: The source type of the value to be resized.
- `U`: The destination type to which the value will be resized.

# Returns

The result of transforming `value as U`. Where `U` is wider than `T`, this
zero-extends; where `U` is narrower, it truncates.
**/
fn resize<T, U>(value: T) -> U
where T: BitStore, U: BitStore {
	let zero = 0usize;
	let mut slab = zero.to_ne_bytes();
	let start = 0;

	/* Copy the source value into the correct region of the intermediate slab.

	The `BitStore::as_bytes` method returns the value as native-endian-order
	bytes. These bytes are then written into the correct location of the slab
	(low addresses on little-endian, high addresses on big-endian) to be
	interpreted as `usize`.
	*/
	match mem::size_of::<T>() {
		n @ 1 | n @ 2 | n @ 4 | n @ 8 => {
			#[cfg(target_endian = "big")]
			let start = mem::size_of::<usize>() - n;

			slab[start ..][.. n].copy_from_slice(value.as_bytes());
		},
		_ => unreachable!("BitStore is not implemented on types of this size"),
	}
	let mid = usize::from_ne_bytes(slab);
	//  Truncate to the correct size, then wrap in `U` through the trait method.
	match mem::size_of::<U>() {
		1 => U::from_bytes(&(mid as u8).to_ne_bytes()[..]),
		2 => U::from_bytes(&(mid as u16).to_ne_bytes()[..]),
		4 => U::from_bytes(&(mid as u32).to_ne_bytes()[..]),
		#[cfg(target_pointer_width = "64")]
		8 => U::from_bytes(&mid.to_ne_bytes()[..]),
		_ => unreachable!("BitStore is not implemented on types of this size"),
	}
}

#[allow(clippy::inconsistent_digit_grouping)]
#[cfg(test)]
mod tests {
	use super::*;
	use crate::prelude::*;

	#[test]
	fn lsb0() {
		let mut bytes = [0u8; 16];
		let bytes = bytes.bits_mut::<Lsb0>();

		bytes[1 ..][.. 4].store_le(0x0Au8);
		assert_eq!(bytes[1 ..][.. 4].load_le::<u8>(), 0x0Au8);
		assert_eq!(bytes.as_slice()[0], 0b000_1010_0u8);

		bytes[1 ..][.. 4].store_be(0x05u8);
		assert_eq!(bytes[1 ..][.. 4].load_be::<u8>(), 0x05u8);
		assert_eq!(bytes.as_slice()[0], 0b000_0101_0u8);

		bytes[1 ..][.. 4].store_le(0u8);

		//  expected byte pattern: 0x34 0x12
		//  bits: 0011_0100 __01_0010
		//  idx:  7654 3210 fedc ba98
		let u16b = u16::from_ne_bytes(0x1234u16.to_le_bytes());
		bytes[5 ..][.. 14].store_le(u16b);
		assert_eq!(bytes[5 ..][.. 14].load_le::<u16>(), 0x1234u16);
		assert_eq!(
			&bytes.as_slice()[.. 3],
			&[0b100_00000, 0b010_0011_0, 0b00000_01_0],
			//  210          a98 7654 3          dc b
		);
		//  the load/store orderings only affect the order of elements, not of
		//  bits within the element.
		bytes[5 ..][.. 14].store_be(u16b);
		assert_eq!(bytes[5 ..][.. 14].load_be::<u16>(), 0x1234u16);
		assert_eq!(
			&bytes.as_slice()[.. 3],
			&[0b01_0_00000, 0b010_0011_0, 0b00000_100],
			//  dc b          a98 7654 3          210
		);

		let mut shorts = [0u16; 8];
		let shorts = shorts.bits_mut::<Lsb0>();

		shorts[3 ..][.. 12].store_le(0x0123u16);
		assert_eq!(shorts[3 ..][.. 12].load_le::<u16>(), 0x0123u16);
		assert_eq!(shorts.as_slice()[0], 0b0_0001_0010_0011_000u16);

		shorts[3 ..][.. 12].store_be(0x0123u16);
		assert_eq!(shorts[3 ..][.. 12].load_be::<u16>(), 0x0123u16);
		assert_eq!(shorts.as_slice()[0], 0b0_0001_0010_0011_000u16);

		let mut ints = [0u32; 4];
		let ints = ints.bits_mut::<Lsb0>();

		ints[1 ..][.. 28].store_le(0x0123_4567u32);
		assert_eq!(ints[1 ..][.. 28].load_le::<u32>(), 0x0123_4567u32);
		assert_eq!(ints.as_slice()[0], 0b000_0001_0010_0011_0100_0101_0110_0111_0u32);

		ints[1 ..][.. 28].store_be(0x0123_4567u32);
		assert_eq!(ints[1 ..][.. 28].load_be::<u32>(), 0x0123_4567u32);
		assert_eq!(ints.as_slice()[0], 0b000_0001_0010_0011_0100_0101_0110_0111_0u32);

		/*
		#[cfg(target_pointer_width = "64")] {

		let mut longs = [0u64; 2];
		let longs = longs.bits_mut::<Lsb0>();

		}
		*/
	}

	#[test]
	fn msb0() {
		let mut bytes = [0u8; 16];
		let bytes = bytes.bits_mut::<Msb0>();

		bytes[1 ..][.. 4].store_le(0x0Au8);
		assert_eq!(bytes[1 ..][.. 4].load_le::<u8>(), 0x0Au8);
		assert_eq!(bytes.as_slice()[0], 0b0_1010_000u8);

		bytes[1 ..][.. 4].store_be(0x05u8);
		assert_eq!(bytes[1 ..][.. 4].load_be::<u8>(), 0x05u8);
		assert_eq!(bytes.as_slice()[0], 0b0_0101_000u8);

		bytes[1 ..][.. 4].store_le(0u8);

		//  expected byte pattern: 0x34 0x12
		//  bits: 0011_0100 __01_0010
		//  idx:  7654 3210 fedc ba98
		let u16b = u16::from_ne_bytes(0x1234u16.to_le_bytes());
		bytes[5 ..][.. 14].store_le(u16b);
		assert_eq!(bytes[5 ..][.. 14].load_le::<u16>(), 0x1234u16);
		assert_eq!(
			&bytes.as_slice()[.. 3],
			&[0b00000_100, 0b010_0011_0, 0b01_0_00000],
			//        210    a98 7654 3    dc b
		);
		//  the load/store orderings only affect the order of elements, not of
		//  bits within the element.
		bytes[5 ..][.. 14].store_be(u16b);
		assert_eq!(bytes[5 ..][.. 14].load_be::<u16>(), 0x1234u16);
		assert_eq!(
			&bytes.as_slice()[.. 3],
			&[0b00000_01_0, 0b010_0011_0, 0b100_00000],
			//        dc b    a98 7654 3    210
		);

		let mut shorts = [0u16; 8];
		let shorts = shorts.bits_mut::<Msb0>();

		shorts[3 ..][.. 12].store_le(0x0123u16);
		assert_eq!(shorts[3 ..][.. 12].load_le::<u16>(), 0x0123u16);
		assert_eq!(shorts.as_slice()[0], 0b000_0001_0010_0011_0u16);

		shorts[3 ..][.. 12].store_be(0x0123u16);
		assert_eq!(shorts[3 ..][.. 12].load_be::<u16>(), 0x0123u16);
		assert_eq!(shorts.as_slice()[0], 0b000_0001_0010_0011_0u16);

		let mut ints = [0u32; 4];
		let ints = ints.bits_mut::<Msb0>();

		ints[1 ..][.. 28].store_le(0x0123_4567u32);
		assert_eq!(ints[1 ..][.. 28].load_le::<u32>(), 0x0123_4567u32);
		assert_eq!(ints.as_slice()[0], 0b0_0001_0010_0011_0100_0101_0110_0111_000u32);

		ints[1 ..][.. 28].store_be(0x0123_4567u32);
		assert_eq!(ints[1 ..][.. 28].load_be::<u32>(), 0x0123_4567u32);
		assert_eq!(ints.as_slice()[0], 0b0_0001_0010_0011_0100_0101_0110_0111_000u32);

		/*
		#[cfg(target_pointer_width = "64")] {

		let mut longs = [0u64; 2];
		let longs = longs.bits_mut::<Msb0>();

		}
		*/
	}
}

#[cfg(test)]
mod permutation_tests;