1 /**
2  * Bit manipulation.
3  *
4  * License:
5  *   This Source Code Form is subject to the terms of
6  *   the Mozilla Public License, v. 2.0. If a copy of
7  *   the MPL was not distributed with this file, You
8  *   can obtain one at http://mozilla.org/MPL/2.0/.
9  *
10  * Authors:
11  *   Vladimir Panteleev <vladimir@thecybershadow.net>
12  *   Simon Arlott
13  */
14 
15 module ae.utils.bitmanip;
16 
17 import std.bitmanip;
18 import std.traits;
19 
20 struct BigEndian(T)
21 {
22 	private ubyte[T.sizeof] _endian_bytes;
23 	@property T _endian_value() const { return cast(T)bigEndianToNative!(OriginalType!T)(_endian_bytes); }
24 	@property void _endian_value(T value) { _endian_bytes = nativeToBigEndian(OriginalType!T(value)); }
25 	alias _endian_value this;
26 	alias opAssign = _endian_value;
27 	this(T value) { _endian_value(value); }
28 }
29 
30 struct LittleEndian(T)
31 {
32 	private ubyte[T.sizeof] _endian_bytes;
33 	@property T _endian_value() const { return cast(T)littleEndianToNative!(OriginalType!T)(_endian_bytes); }
34 	@property void _endian_value(T value) { _endian_bytes = nativeToLittleEndian(OriginalType!T(value)); }
35 	alias _endian_value this;
36 	alias opAssign = _endian_value;
37 	this(T value) { _endian_value(value); }
38 }
39 
40 unittest
41 {
42 	union U
43 	{
44 		BigEndian!ushort be;
45 		LittleEndian!ushort le;
46 		ubyte[2] bytes;
47 	}
48 	U u;
49 
50 	u.be = 0x1234;
51 	assert(u.bytes == [0x12, 0x34]);
52 
53 	u.le = 0x1234;
54 	assert(u.bytes == [0x34, 0x12]);
55 
56 	u.bytes = [0x56, 0x78];
57 	assert(u.be == 0x5678);
58 	assert(u.le == 0x7856);
59 }
60 
61 unittest
62 {
63 	enum E : uint { e }
64 	BigEndian!E be;
65 }
66 
67 unittest
68 {
69 	const e = BigEndian!int(1);
70 	assert(e == 1);
71 }