1 module yu.bytes; 2 3 import core.stdc.string; 4 import std.traits; 5 import std.bitmanip; 6 import yu.traits; 7 8 ptrdiff_t findCharByte(T)(in T[] data, in T ch) if (isCharByte!(T)) { 9 if (data.length == 0) 10 return -1; 11 ptrdiff_t index = -1; 12 auto ptr = memchr(data.ptr, ch, data.length); 13 if (ptr !is null) { 14 index = cast(ptrdiff_t)((cast(T*) ptr) - data.ptr); 15 } 16 17 return index; 18 } 19 20 ptrdiff_t findCharBytes(T)(in T[] data, in T[] chs) if (isCharByte!(T)) { 21 if (data.length < chs.length || data.length == 0 || chs.length == 0) 22 return -1; 23 ptrdiff_t index = -1; 24 size_t rsize = 0; 25 while (rsize < data.length) { 26 auto tdata = data[rsize .. $]; 27 auto ptr = memchr(tdata.ptr, chs[0], tdata.length); 28 if (ptr is null) 29 break; 30 31 size_t fistindex = (cast(T*) ptr) - tdata.ptr; 32 if (tdata.length - fistindex < chs.length) 33 break; 34 35 size_t i = 1; 36 size_t j = fistindex + 1; 37 while (i < chs.length && j < tdata.length) { 38 if (chs[i] != tdata[j]) { 39 rsize += fistindex + 1; 40 goto next; 41 } 42 ++i; 43 ++j; 44 } 45 index = cast(ptrdiff_t)(rsize + fistindex); 46 break; 47 next: 48 continue; 49 } 50 return index; 51 } 52 53 template endianToNative(bool litte, T) { 54 static if (litte) 55 alias endianToNative = littleEndianToNative!(T, T.sizeof); 56 else 57 alias endianToNative = bigEndianToNative!(T, T.sizeof); 58 } 59 60 template nativeToEndian(bool litte, T) { 61 static if (litte) 62 alias nativeToEndian = nativeToLittleEndian!(T); 63 else 64 alias nativeToEndian = nativeToBigEndian!(T); 65 66 } 67 68 unittest { 69 string hello = "hell worlf\r\nnext"; 70 assert(findCharByte(hello, 'l') == 2); 71 assert(findCharBytes(hello, "worlf") == 5); 72 }