1 module dgt.util; 2 import core.stdc.math, core.stdc.stdlib; 3 4 import dgt.array; 5 import dgt.geom; 6 7 @nogc nothrow: 8 9 ///A normalized random function 10 float random() 11 { 12 return cast(float) rand() / RAND_MAX; 13 } 14 ///Generate a random float in a range 15 float randomRange(in float min, in float max) 16 { 17 return (max - min) * random() + min; 18 } 19 ///Generate a random int in a range 20 int randomRange(in int min, in int max) 21 { 22 return cast(int)randomRange(cast(float)min, cast(float)max); 23 } 24 ///Generate a vector in a range 25 Vector randomRange(in Vector a, in Vector b) 26 { 27 return Vector(randomRange(a.x, b.x), randomRange(a.y, b.y)); 28 } 29 ///Create a null terminated buffer from a string 30 Array!char nullTerminate(in string str) 31 { 32 Array!char nameNullTerminated = Array!char(str.length + 1); 33 for(size_t i = 0; i < str.length; i++) 34 nameNullTerminated.add(str[i]); 35 nameNullTerminated.add('\0'); 36 return nameNullTerminated; 37 } 38 unittest 39 { 40 for(size_t i = 0; i < 1000; i++) 41 { 42 Vector vector = randomRange(Vector(-1, -1), Vector(5, 5)); 43 assert(vector.x >= -1 && vector.y >= -1 && vector.x < 5 && vector.y < 5); 44 } 45 } 46 unittest 47 { 48 auto str = nullTerminate("Test string"); 49 auto expected = "Test string\0"; 50 for(size_t i = 0; i < expected.length; i++) 51 assert(str[i] == expected[i]); 52 }