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() { 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 } 28 29 struct LittleEndian(T) 30 { 31 private ubyte[T.sizeof] _endian_bytes; 32 @property T _endian_value() { return cast(T)littleEndianToNative!(OriginalType!T)(_endian_bytes); } 33 @property void _endian_value(T value) { _endian_bytes = nativeToLittleEndian(OriginalType!T(value)); } 34 alias _endian_value this; 35 alias opAssign = _endian_value; 36 } 37 38 unittest 39 { 40 union U 41 { 42 BigEndian!ushort be; 43 LittleEndian!ushort le; 44 ubyte[2] bytes; 45 } 46 U u; 47 48 u.be = 0x1234; 49 assert(u.bytes == [0x12, 0x34]); 50 51 u.le = 0x1234; 52 assert(u.bytes == [0x34, 0x12]); 53 54 u.bytes = [0x56, 0x78]; 55 assert(u.be == 0x5678); 56 assert(u.le == 0x7856); 57 } 58 59 unittest 60 { 61 enum E : uint { e } 62 BigEndian!E be; 63 }