1 /**
2 * Copyright © Yurai Web Framework 2021
3 * License: MIT (https://github.com/YuraiWeb/yurai/blob/main/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module yurai.core.strings;
7 
8 import std.traits : isScalarType, isSomeString;
9 
10 import std.string : representation;
11 
12 template CharType(T)
13 if (isSomeString!T)
14 {
15   static if (is(T == string))
16   {
17     alias CharType = char;
18   }
19   else static if (is(T == wstring))
20   {
21     alias CharType = wchar;
22   }
23   else static if (is(T == dstring))
24   {
25     alias CharType = dchar;
26   }
27   else
28   {
29     static assert(0, "Invalid string type");
30   }
31 }
32 
33 template CharBufferType(T)
34 if (isSomeString!T)
35 {
36   static if (is(T == string))
37   {
38     alias CharBufferType = ubyte;
39   }
40   else static if (is(T == wstring))
41   {
42     alias CharBufferType = ushort;
43   }
44   else static if (is(T == dstring))
45   {
46     alias CharBufferType = uint;
47   }
48   else
49   {
50     static assert(0, "Invalid string type");
51   }
52 }
53 
54 T[] asStringRaw(T)(ubyte[] buf)
55 if (isScalarType!T)
56 {
57     T[] vals = new T[buf.length / T.sizeof];
58 
59     foreach (offset; 0 .. vals.length)
60     {
61         vals[offset] = (*(cast(T*)(buf.ptr + (offset * T.sizeof))));
62     }
63 
64     return vals;
65 }
66 
67 ubyte[] asBytesRaw(T)(T[] vals)
68 if (isScalarType!T)
69 {
70     ubyte[] buf = new ubyte[vals.length * T.sizeof];
71 
72     foreach (offset; 0 .. vals.length)
73     {
74         (*(cast(T*)(buf.ptr + (offset * T.sizeof)))) = vals[offset];
75     }
76 
77     return buf;
78 }
79 
80 S asString(S)(ubyte[] buf)
81 if (isSomeString!S)
82 {
83   return (asStringRaw!(CharType!S)(buf)).dup;
84 }
85 
86 ubyte[] asBytes(S)(S s)
87 if (isSomeString!S)
88 {
89   return asBytesRaw!(CharBufferType!S)(s.representation.dup);
90 }