1 /** 2 * Copyright © DiamondMVC 2019 3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE) 4 * Author: Jacob Jensen (bausshf) 5 */ 6 module diamond.core.senc; 7 8 /** 9 * Template for the SENC encoding implementation. 10 * SENC is a simple byte to string encoder. 11 * Params: 12 * unused = Unused boolean to instantiate SENCImpl; 13 */ 14 private template SENCImpl(bool unused) 15 { 16 public: 17 import std.conv : to; 18 19 /** 20 * Encodes a string to a SENC encoded string. 21 * Params: 22 * s = The string to encode. 23 * Returns: 24 * Returns the encoded string. 25 */ 26 string encode(string s) 27 { 28 return encode(cast(ubyte[])s); 29 } 30 31 /** 32 * Encodes a buffer to a SENC encoded buffer. 33 * Params: 34 * data = The buffer to encode. 35 * Returns: 36 * Returns the encoded string. 37 */ 38 string encode(ubyte[] data) 39 { 40 auto buf = new char[data.length * 2]; 41 42 size_t i; 43 44 foreach (b; data) 45 { 46 auto hex = to!string(b, 16); 47 48 if (hex.length == 1) 49 { 50 buf[i] = '0'; 51 i++; 52 buf[i] = hex[0]; 53 i++; 54 } 55 else 56 { 57 buf[i] = hex[0]; 58 i++; 59 buf[i] = hex[1]; 60 i++; 61 } 62 } 63 64 return cast(string)buf; 65 } 66 67 /** 68 * Decodes an encoded string to a string result. 69 * Params: 70 * data = The data to decode. 71 * Returns: 72 * Returns the decoded string. 73 */ 74 string decodeToString(string data) 75 { 76 return cast(string)decode(data); 77 } 78 79 /** 80 * Decodes an encoded string to a buffer result. 81 * Params: 82 * data = The data to decode. 83 * Returns: 84 * Returns the decoded buffer. 85 */ 86 ubyte[] decode(string data) 87 { 88 auto buf = new ubyte[data.length / 2]; 89 90 size_t i; 91 size_t c; 92 93 foreach (ref b; buf) 94 { 95 buf[c] = to!ubyte(data[i .. i + 2], 16); 96 97 c++; 98 i += 2; 99 } 100 101 return buf; 102 } 103 } 104 105 /// An instance of the SENC implementation. 106 public alias SENC = SENCImpl!false;