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
#![doc = include_str!("../doc/field.md")]

use core::{
	mem,
	ptr,
};

use funty::Integral;
use tap::Pipe;
use wyz::comu::{
	Const,
	Mut,
};

use crate::{
	array::BitArray,
	devel as dvl,
	domain::{
		Domain,
		PartialElement,
	},
	mem::bits_of,
	order::{
		BitOrder,
		Lsb0,
		Msb0,
	},
	slice::BitSlice,
	store::BitStore,
	view::BitViewSized,
};
#[cfg(feature = "alloc")]
use crate::{
	boxed::BitBox,
	vec::BitVec,
};

mod io;
mod tests;

#[doc = include_str!("../doc/field/BitField.md")]
pub trait BitField {
	#[inline]
	#[cfg(not(tarpaulin_include))]
	#[doc = include_str!("../doc/field/BitField_load.md")]
	fn load<I>(&self) -> I
	where I: Integral {
		if cfg!(target_endian = "little") {
			self.load_le::<I>()
		}
		else if cfg!(target_endian = "big") {
			self.load_be::<I>()
		}
		else {
			match option_env!("CARGO_PKG_REPOSITORY") {
				Some(env) => unreachable!(
					"This architecture is not supported! Please consider \
					 filing an issue at {}",
					env
				),
				None => unreachable!(
					"This architecture is not supported! Please consider \
					 filing an issue"
				),
			}
		}
	}

	#[inline]
	#[cfg(not(tarpaulin_include))]
	#[doc = include_str!("../doc/field/BitField_store.md")]
	fn store<I>(&mut self, value: I)
	where I: Integral {
		if cfg!(target_endian = "little") {
			self.store_le::<I>(value);
		}
		else if cfg!(target_endian = "big") {
			self.store_be::<I>(value);
		}
		else {
			match option_env!("CARGO_PKG_REPOSITORY") {
				Some(env) => unreachable!(
					"This architecture is not supported! Please consider \
					 filing an issue at {}",
					env
				),
				None => unreachable!(
					"This architecture is not supported! Please consider \
					 filing an issue"
				),
			}
		}
	}

	#[doc = include_str!("../doc/field/BitField_load_le.md")]
	fn load_le<I>(&self) -> I
	where I: Integral;

	#[doc = include_str!("../doc/field/BitField_load_be.md")]
	fn load_be<I>(&self) -> I
	where I: Integral;

	#[doc = include_str!("../doc/field/BitField_store_le.md")]
	fn store_le<I>(&mut self, value: I)
	where I: Integral;

	#[doc = include_str!("../doc/field/BitField_store_be.md")]
	fn store_be<I>(&mut self, value: I)
	where I: Integral;
}

#[doc = include_str!("../doc/field/BitField_Lsb0.md")]
impl<T> BitField for BitSlice<T, Lsb0>
where T: BitStore
{
	#[inline]
	#[doc = include_str!("../doc/field/BitField_Lsb0_load_le.md")]
	fn load_le<I>(&self) -> I
	where I: Integral {
		let len = self.len();
		check::<I>("load", len);

		match self.domain() {
			//  In Lsb0, the head counts distance from LSedge to first live bit.
			Domain::Enclave(elem) => get(elem, elem.head().into_inner()),
			Domain::Region { head, body, tail } => {
				let mut accum = I::ZERO;

				if let Some(elem) = tail {
					accum = get(elem, 0);
				}

				for elem in body.iter().rev().map(BitStore::load_value) {
					maybe_shift_left(&mut accum, bits_of::<T>());
					accum |= resize::<T::Mem, I>(elem);
				}

				if let Some(elem) = head {
					let shamt = elem.head().into_inner();
					maybe_shift_left(
						&mut accum,
						bits_of::<T>() - shamt as usize,
					);
					accum |= get::<_, _, I>(elem, shamt);
				}

				accum
			},
		}
		.pipe(|elem| sign(elem, len))
	}

	#[inline]
	#[doc = include_str!("../doc/field/BitField_Lsb0_load_be.md")]
	fn load_be<I>(&self) -> I
	where I: Integral {
		let len = self.len();
		check::<I>("load", len);

		match self.domain() {
			Domain::Enclave(elem) => get(elem, elem.head().into_inner()),
			Domain::Region { head, body, tail } => {
				let mut accum = I::ZERO;

				if let Some(elem) = head {
					accum = get(elem, elem.head().into_inner());
				}

				for elem in body.iter().map(BitStore::load_value) {
					maybe_shift_left(&mut accum, bits_of::<T>());
					accum |= resize::<T::Mem, I>(elem);
				}

				if let Some(elem) = tail {
					let shamt = elem.tail().into_inner() as usize;
					maybe_shift_left(&mut accum, shamt);
					accum |= get::<_, _, I>(elem, 0);
				}

				accum
			},
		}
		.pipe(|elem| sign(elem, len))
	}

	#[inline]
	#[doc = include_str!("../doc/field/BitField_Lsb0_store_le.md")]
	fn store_le<I>(&mut self, mut value: I)
	where I: Integral {
		check::<I>("store", self.len());

		match self.domain_mut() {
			Domain::Enclave(elem) => {
				let shamt = elem.head().into_inner();
				set(elem, value, shamt);
			},
			Domain::Region { head, body, tail } => {
				if let Some(elem) = head {
					let shamt = elem.head().into_inner();
					set(elem, value, shamt);
					let rshamt = bits_of::<T>() - shamt as usize;
					maybe_shift_right(&mut value, rshamt);
				}

				for elem in body.iter_mut() {
					elem.store_value(resize(value));
					maybe_shift_right(&mut value, bits_of::<T>());
				}

				if let Some(elem) = tail {
					set(elem, value, 0);
				}
			},
		}
	}

	#[inline]
	#[doc = include_str!("../doc/field/BitField_Lsb0_store_be.md")]
	fn store_be<I>(&mut self, mut value: I)
	where I: Integral {
		check::<I>("store", self.len());

		match self.domain_mut() {
			Domain::Enclave(elem) => {
				let shamt = elem.head().into_inner();
				set(elem, value, shamt);
			},
			Domain::Region { head, body, tail } => {
				if let Some(elem) = tail {
					let shamt = elem.tail().into_inner() as usize;
					set(elem, value, 0);
					maybe_shift_right(&mut value, shamt);
				}

				for elem in body.iter_mut().rev() {
					elem.store_value(resize(value));
					maybe_shift_right(&mut value, bits_of::<T>());
				}

				if let Some(elem) = head {
					let shamt = elem.head().into_inner();
					set(elem, value, shamt);
				}
			},
		}
	}
}

#[doc = include_str!("../doc/field/BitField_Msb0.md")]
impl<T> BitField for BitSlice<T, Msb0>
where T: BitStore
{
	#[inline]
	#[doc = include_str!("../doc/field/BitField_Msb0_load_le.md")]
	fn load_le<I>(&self) -> I
	where I: Integral {
		let len = self.len();
		check::<I>("load", len);

		match self.domain() {
			Domain::Enclave(elem) => {
				let shamt = bits_of::<T>() as u8 - elem.tail().into_inner();
				get(elem, shamt)
			},
			Domain::Region { head, body, tail } => {
				let mut accum = I::ZERO;

				if let Some(elem) = tail {
					let shamt = bits_of::<T>() as u8 - elem.tail().into_inner();
					accum = get(elem, shamt);
				}

				for elem in body.iter().rev().map(BitStore::load_value) {
					maybe_shift_left(&mut accum, bits_of::<T>());
					accum |= resize::<T::Mem, I>(elem);
				}

				if let Some(elem) = head {
					let shamt =
						bits_of::<T>() - elem.head().into_inner() as usize;
					maybe_shift_left(&mut accum, shamt);
					accum |= get::<_, _, I>(elem, 0);
				}

				accum
			},
		}
		.pipe(|elem| sign(elem, len))
	}

	#[inline]
	#[doc = include_str!("../doc/field/BitField_Msb0_load_be.md")]
	fn load_be<I>(&self) -> I
	where I: Integral {
		let len = self.len();
		check::<I>("load", len);

		match self.domain() {
			Domain::Enclave(elem) => {
				let shamt = bits_of::<T>() as u8 - elem.tail().into_inner();
				get(elem, shamt)
			},
			Domain::Region { head, body, tail } => {
				let mut accum = I::ZERO;

				if let Some(elem) = head {
					accum = get(elem, 0);
				}

				for elem in body.iter().map(BitStore::load_value) {
					maybe_shift_left(&mut accum, bits_of::<T>());
					accum |= resize::<T::Mem, I>(elem);
				}

				if let Some(elem) = tail {
					let shamt = elem.tail().into_inner();
					maybe_shift_left(&mut accum, shamt as usize);
					accum |= get::<_, _, I>(elem, bits_of::<T>() as u8 - shamt);
				}

				accum
			},
		}
		.pipe(|elem| sign(elem, len))
	}

	#[inline]
	#[doc = include_str!("../doc/field/BitField_Msb0_store_le.md")]
	fn store_le<I>(&mut self, mut value: I)
	where I: Integral {
		check::<I>("store", self.len());

		match self.domain_mut() {
			Domain::Enclave(elem) => {
				let shamt = bits_of::<T>() as u8 - elem.tail().into_inner();
				set(elem, value, shamt);
			},
			Domain::Region { head, body, tail } => {
				if let Some(elem) = head {
					let shamt =
						bits_of::<T>() - elem.head().into_inner() as usize;
					set(elem, value, 0);
					maybe_shift_right(&mut value, shamt);
				}

				for elem in body.iter_mut() {
					elem.store_value(resize(value));
					maybe_shift_right(&mut value, bits_of::<T>());
				}

				if let Some(elem) = tail {
					let shamt = bits_of::<T>() as u8 - elem.tail().into_inner();
					set(elem, value, shamt);
				}
			},
		}
	}

	#[inline]
	#[doc = include_str!("../doc/field/BitField_Msb0_store_be.md")]
	fn store_be<I>(&mut self, mut value: I)
	where I: Integral {
		check::<I>("store", self.len());

		match self.domain_mut() {
			Domain::Enclave(elem) => {
				let shamt = bits_of::<T>() as u8 - elem.tail().into_inner();
				set(elem, value, shamt);
			},
			Domain::Region { head, body, tail } => {
				if let Some(elem) = tail {
					let tail = elem.tail().into_inner() as usize;
					let shamt = bits_of::<T>() - tail;
					set(elem, value, shamt as u8);
					maybe_shift_right(&mut value, tail);
				}

				for elem in body.iter_mut().rev() {
					elem.store_value(resize(value));
					maybe_shift_right(&mut value, bits_of::<T>());
				}

				if let Some(elem) = head {
					set(elem, value, 0);
				}
			},
		}
	}
}

#[doc = include_str!("../doc/field/impl_BitArray.md")]
impl<A, O> BitField for BitArray<A, O>
where
	O: BitOrder,
	A: BitViewSized,
	BitSlice<A::Store, O>: BitField,
{
	#[inline(always)]
	fn load_le<I>(&self) -> I
	where I: Integral {
		let mut accum = I::ZERO;

		for elem in self.as_raw_slice().iter().map(BitStore::load_value).rev() {
			maybe_shift_left(&mut accum, bits_of::<A::Store>());
			accum |= resize::<_, I>(elem);
		}

		sign(accum, self.len())
	}

	#[inline(always)]
	fn load_be<I>(&self) -> I
	where I: Integral {
		let mut accum = I::ZERO;

		for elem in self.as_raw_slice().iter().map(BitStore::load_value) {
			maybe_shift_left(&mut accum, bits_of::<A::Store>());
			accum |= resize::<_, I>(elem);
		}

		sign(accum, self.len())
	}

	#[inline(always)]
	fn store_le<I>(&mut self, mut value: I)
	where I: Integral {
		for slot in self.as_raw_mut_slice() {
			slot.store_value(resize(value));
			maybe_shift_right(&mut value, bits_of::<A::Store>());
		}
	}

	#[inline(always)]
	fn store_be<I>(&mut self, mut value: I)
	where I: Integral {
		for slot in self.as_raw_mut_slice().iter_mut().rev() {
			slot.store_value(resize(value));
			maybe_shift_right(&mut value, bits_of::<A::Store>());
		}
	}
}

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

	#[inline(always)]
	fn load_be<I>(&self) -> I
	where I: Integral {
		self.as_bitslice().load_be()
	}

	#[inline(always)]
	fn store_le<I>(&mut self, value: I)
	where I: Integral {
		self.as_mut_bitslice().store_le(value)
	}

	#[inline(always)]
	fn store_be<I>(&mut self, value: I)
	where I: Integral {
		self.as_mut_bitslice().store_be(value)
	}
}

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

	#[inline(always)]
	fn load_be<I>(&self) -> I
	where I: Integral {
		self.as_bitslice().load_be()
	}

	#[inline(always)]
	fn store_le<I>(&mut self, value: I)
	where I: Integral {
		self.as_mut_bitslice().store_le(value)
	}

	#[inline(always)]
	fn store_be<I>(&mut self, value: I)
	where I: Integral {
		self.as_mut_bitslice().store_be(value)
	}
}

/** Asserts that a bit-slice is not longer than a memory element.

## Type Parameters

- `I`: The integer type being stored into or loaded out of a bit-slice.

## Parameters

- `action`: the verb being performed. One of `"load"` or `"store"`.
- `len`: the length of the bit-slice under test.

## Panics

This panics if `len` is not in `1 ..= U::BITS`.
**/
fn check<I>(action: &'static str, len: usize)
where I: Integral {
	assert!(
		(1 ..= bits_of::<I>()).contains(&len),
		"cannot {} {} bits from a {}-bit region",
		action,
		bits_of::<I>(),
		len,
	);
}

/// Shifts a value to the left, if it can support the shift amount.
fn maybe_shift_left<T: Integral>(elem: &mut T, shamt: usize) {
	if bits_of::<T>() > shamt {
		*elem <<= shamt;
	}
}

/// Shifts a value to the right, if it can support the shift amount.
fn maybe_shift_right<T: Integral>(elem: &mut T, shamt: usize) {
	if bits_of::<T>() > shamt {
		*elem >>= shamt;
	}
}

#[doc = include_str!("../doc/field/get.md")]
fn get<T, O, I>(elem: PartialElement<Const, T, O>, shamt: u8) -> I
where
	T: BitStore,
	O: BitOrder,
	I: Integral,
{
	resize::<T::Mem, I>(elem.load_value() >> shamt)
}

#[doc = include_str!("../doc/field/set.md")]
fn set<T, O, I>(mut elem: PartialElement<Mut, T, O>, value: I, shamt: u8)
where
	T: BitStore,
	O: BitOrder,
	I: Integral,
{
	elem.store_value(resize::<I, T::Mem>(value) << shamt);
}

#[doc = include_str!("../doc/field/sign.md")]
fn sign<I>(elem: I, width: usize) -> I
where I: Integral {
	if dvl::is_unsigned::<I>() {
		return elem;
	}
	//  Find the number of high bits that are not loaded.
	let shamt = bits_of::<I>() - width;
	//  Shift left, so that the highest loaded bit is now in the sign position.
	let shl: I = elem << shamt;
	//  Shift right with sign extension back to the original place.
	shl >> shamt
}

#[doc = include_str!("../doc/field/resize.md")]
fn resize<T, U>(value: T) -> U
where
	T: Integral,
	U: Integral,
{
	let mut out = U::ZERO;
	let size_t = mem::size_of::<T>();
	let size_u = mem::size_of::<U>();

	unsafe {
		resize_inner::<T, U>(&value, &mut out, size_t, size_u);
	}

	out
}

/// Performs little-endian byte-order register resizing.
#[cfg(target_endian = "little")]
unsafe fn resize_inner<T, U>(
	src: &T,
	dst: &mut U,
	size_t: usize,
	size_u: usize,
) {
	//  In LE, the least-significant byte is the base address, so resizing is
	//  just a `memmove` into a zeroed slot, taking only the lesser width.
	ptr::copy_nonoverlapping(
		src as *const T as *const u8,
		dst as *mut U as *mut u8,
		size_t.min(size_u),
	);
}

/// Performs big-endian byte-order register resizing.
#[cfg(target_endian = "big")]
unsafe fn resize_inner<T, U>(
	src: &T,
	dst: &mut U,
	size_t: usize,
	size_u: usize,
) {
	let src = src as *const T as *const u8;
	let dst = dst as *mut U as *mut u8;

	//  In BE, shrinking a value requires moving the source base-pointer up in
	//  memory (to a higher address, lower significance),
	if size_t > size_u {
		ptr::copy_nonoverlapping(src.add(size_t - size_u), dst, size_u);
	}
	//  While expanding a value requires moving the *destination* base-pointer
	//  up (and leaving the lower address, higher significance bytes zeroed).
	else {
		ptr::copy_nonoverlapping(src, dst.add(size_u - size_t), size_t);
	}
}