1 /* 2 * Hunt - A refined core library for D programming language. 3 * 4 * Copyright (C) 2018-2019 HuntLabs 5 * 6 * Website: https://www.huntlabs.net/ 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 12 module hunt.util.TypeUtils; 13 14 import std.string; 15 import std.typecons; 16 17 /** 18 */ 19 alias Pair(F, S) = Tuple!(F, "first", S, "second"); 20 Pair!(F, S) makePair(F, S)(F first, S second) { 21 return tuple!("first", "second")(first, second); 22 } 23 24 unittest { 25 Pair!(string, int) p = makePair("age", 20); 26 27 assert(p.first == "age"); 28 assert(p.second == 20); 29 } 30 31 /** 32 */ 33 struct TypeUtils { 34 35 static string getSimpleName(TypeInfo info) { 36 if(info is null) 37 return "null"; 38 string name = info.toString(); 39 ptrdiff_t index = lastIndexOf(name, '.'); 40 if(index == -1) 41 return name; 42 else 43 return name[index+1 .. $]; 44 } 45 46 /** 47 * Returns the number of zero bits preceding the highest-order 48 * ("leftmost") one-bit in the two's complement binary representation 49 * of the specified {@code int} value. Returns 32 if the 50 * specified value has no one-bits in its two's complement representation, 51 * in other words if it is equal to zero. 52 * 53 * <p>Note that this method is closely related to the logarithm base 2. 54 * For all positive {@code int} values x: 55 * <ul> 56 * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)} 57 * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)} 58 * </ul> 59 * 60 * @param i the value whose number of leading zeros is to be computed 61 * @return the number of zero bits preceding the highest-order 62 * ("leftmost") one-bit in the two's complement binary representation 63 * of the specified {@code int} value, or 32 if the value 64 * is equal to zero. 65 */ 66 static int numberOfLeadingZeros(int i) { 67 // HD, Figure 5-6 68 if (i == 0) 69 return 32; 70 int n = 1; 71 if (i >>> 16 == 0) { 72 n += 16; 73 i <<= 16; 74 } 75 if (i >>> 24 == 0) { 76 n += 8; 77 i <<= 8; 78 } 79 if (i >>> 28 == 0) { 80 n += 4; 81 i <<= 4; 82 } 83 if (i >>> 30 == 0) { 84 n += 2; 85 i <<= 2; 86 } 87 n -= i >>> 31; 88 return n; 89 } 90 }