-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqstr.cs
382 lines (309 loc) · 14.1 KB
/
qstr.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// Lic:
// qstr.cs
// TrickyUnits - Quick String
// version: 22.10.27
// Copyright (C) 2018, 2020, 2022 Jeroen P. Broks
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
// EndLic
using System;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Text;
using System.Collections.Generic;
namespace TrickyUnits {
/// <summary>
/// Just some quick functions to use with strings.
/// Nothing special :P
/// </summary>
public class qstr {
static qstr() {
MKL.Version("Tricky Units for C# - qstr.cs","22.10.27");
MKL.Lic ("Tricky Units for C# - qstr.cs","ZLib License");
}
/// <summary>
/// Does nothing, but calling this just forces C# to load this class.
/// </summary>
public static void Hello() { }
public static string EOLNType(string a) {
string ret = "LF";
var i = a.IndexOf('\r'); if (i < 0) return "LF";
if (i == a.Length - 1 || Mid(a,i + 2, 1) != "\n") return "CR";
if (Mid(a, i + 2) == "\n") ret = "CRLF";
return ret;
}
/// <summary>
/// Calculates MD5 hash from string.
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static string md5(string source) {
string hash;
{
using (MD5 md5Hash = MD5.Create()) {
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(source));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++) {
sBuilder.Append(data[i].ToString("x2"));
}
hash = sBuilder.ToString();
}
}
return hash;
}
public static string Str(string str,int num) {
if (num < 0) throw new Exception("Negative numbers not allowed in qstr.Str() request!");
var ret = new StringBuilder(str.Length*num);
for (int i = 0; i < num; i++) ret.Append(str);
return ret.ToString();
}
public static string Right(string s, int l = 1) {
if (s == null) return "";
if (l > s.Length) return s;
return s.Substring(s.Length - l, l);
}
public static string Left(string s, int l = 1) {
if (l > s.Length) return s;
return s.Substring(0, l);
}
public static string Mid(string s, int pos, int l = 1) {
/*
if (pos + l > s.Length) return s;
return s.Substring(pos - 1, l);
*/
// This is slower, but at least it works.... I hope!
var ret = "";
for (int i = 0; i < l && i<s.Length; i++) ret += s.Substring(i + (pos - 1), 1);
return ret;
}
public static int Len(string s) => s.Length; // The only reason why I put this one in, was for quick translations from BlitzMax.
public static string MyTrim(string s) => s.Trim(); // The only reason why I put this one in, was for Quick translations from Go, where I used this function, as the Trim feature in Go was impractical.
public static string Chr(int i) => ((char)i).ToString(); // The C# method is just impractical. Sorry!
public static string Upper(string s) => s.ToUpper(); // BlitzMax conversion
public static string Lower(string s) => s.ToLower(); // BlitzMax conversion
public static string Join(string[] sl, string sep = "") {
var ret = new StringBuilder();
foreach (var s in sl) {
if (ret.Length > 0) ret.Append(sep);
ret.Append(s);
}
return ret.ToString();
}
public static string Join(List<string> sl, string sep = "") => Join(sl.ToArray(), sep);
public static string ExtractExt(string myFilePath) {
try {
var ret = System.IO.Path.GetExtension(myFilePath);
if (ret == "") { return ""; }
return Right(ret, ret.Length - 1);
} catch (Exception fuckyou) {
System.Diagnostics.Debug.WriteLine($"ERROR: {fuckyou.Message}");
return "";
}
}
public static string StripExt(string myFilePath) {
var d = ExtractDir(myFilePath);
var f = StripDir(myFilePath);
if (d=="")
return $"{f.Substring(0, f.Length - System.IO.Path.GetExtension(f).Length)}";
return $"{d}/{f.Substring(0, f.Length - System.IO.Path.GetExtension(f).Length)}";
}
public static string ExtractDir(string myFilePath) {
try {
if (myFilePath == "") return "";
return System.IO.Path.GetDirectoryName(myFilePath).Replace("\\", "/");
} catch (Exception e) {
System.Diagnostics.Debug.WriteLine($"Error in Extractdir: {e.Message} ({myFilePath})");
return "";
}
}
public static string StripDir(string myFilePath) {
try {
return System.IO.Path.GetFileName(myFilePath);
} catch (Exception e) {
System.Diagnostics.Debug.WriteLine($"Error in ExtractDir -- {e.Message}");
return "";
}
}
public static string StripAll(string myFilePath) => StripDir(StripExt(myFilePath));
public static bool Prefixed(string mystring, string prefix) => Left(mystring, prefix.Length) == prefix;
public static bool Suffixed(string mystring, string suffix) => Right(mystring, suffix.Length) == suffix;
public static string RemPrefix(string mystring, string fix) {
var ms = mystring;
if (Prefixed(ms, fix)) ms = Right(ms, ms.Length - fix.Length);
return ms;
}
public static string RemSuffix(string mystring, string fix) {
var ms = mystring;
if (Suffixed(ms, fix)) ms = Left(ms, ms.Length - fix.Length);
return ms;
}
public static byte ASC(string s, int offs = 0) {
byte[] asciiBytes = System.Text.Encoding.ASCII.GetBytes(s);
int o = offs;
if (o >= asciiBytes.Length || o < 0) return 0;
return asciiBytes[o];
}
public static string SafeString(string a){
var ret = "";
for (int i = 0; i < a.Length;i++){
if (a[i] > 30 && a[i] < 127 && a[i]!='"') ret += Chr(a[i]);
else {
switch (a[i]) {
case '"': ret += "\\\""; break;
case '\b': ret += "\\b"; break;
case '\n': ret += "\\n"; break;
case '\r': ret += "\\r"; break;
case '\\': ret += "\\\\"; break;
default:
ret += "\\" + Right($"00{Convert.ToString(a[i], 8)}", 3);
break;
}
}
}
return ret;
}
/// <summary>
/// Returns a string with the wanted suffix if the suffix hasn't already been set yet!
/// </summary>
public static string SetSuffix(string ori,string suffix,bool casesensitive=false){
if (Suffixed(ori, suffix) || (!casesensitive && Suffixed(ori.ToUpper(), suffix.ToUpper()))) return ori;
return ori + suffix;
}
/// <summary>
/// Returns a string with the wanted prefix if the suffix hasn't already been set yet!
/// </summary>
public static string SetPrefix(string ori, string prefix, bool casesensitive = false) {
if (Prefixed(ori, prefix) || (!casesensitive && Prefixed(ori.ToUpper(), prefix.ToUpper()))) return ori;
return prefix+ori;
}
/// <summary>
/// Converts string to int if possible, and retuns 0 if not possible. You can use "$" as a prefix for hexadecimal numbers and "%" as a prefix for binary numbers.
/// </summary>
/// <returns>The integer if succesful otherwise 0.</returns>
/// <param name="s">The string to convert.</param>
public static int ToInt(string s) {
var ret = 0;
var s2i = s;
try {
switch (s[0]) {
case '$':
s2i = Right(s, s.Length - 1);
return System.Int32.Parse(s2i, System.Globalization.NumberStyles.HexNumber);
case '%':
s2i = Right(s, s.Length - 1);
ret = 0;
int bit = 1;
for (int i = s2i.Length; i > 0; i--) {
switch (Mid(s2i, i, 1)) {
case "1": ret += bit; break;
case "0": break;
default: return 0;
}
bit += bit;
}
break;
}
ret = System.Int32.Parse(s2i);
return ret;
} catch { return 0; }
}
public static bool IsInt(string s) {
var s2i = s;
try {
switch (s[0]) {
case '$':
s2i = Right(s, s.Length - 1);
System.Int32.Parse(s2i, System.Globalization.NumberStyles.HexNumber);
return true;
case '%':
s2i = Right(s, s.Length - 1);
//int bit = 1;
for (int i = s2i.Length; i > 0; i--) {
switch (Mid(s2i, i, 1)) {
case "1":
case "0": break;
default: return false;
}
}
return true;
}
System.Int32.Parse(s2i);
return true;
} catch { return false; }
}
public static string YesNo(bool b) {
if (b) return "Yes"; else return "No";
}
/// <summary>
/// Same as ToInt(), but then for long (64bit integers)
/// </summary>
public static long ToLong(string s) {
long ret = 0;
var s2i = s;
try {
switch (s[0]) {
case '$':
s2i = Right(s, s.Length - 1);
return System.Int64.Parse(s2i, System.Globalization.NumberStyles.HexNumber);
case '%':
s2i = Right(s, s.Length - 1);
ret = 0;
int bit = 1;
for (int i = s2i.Length; i > 0; i--) {
switch (Mid(s2i, i, 1)) {
case "1": ret += bit; break;
case "0": break;
default: return 0;
}
bit += bit;
}
break;
}
ret = System.Int64.Parse(s2i);
return ret;
} catch { return 0; }
}
public static double ToDouble(string s) {
double ret;
try {
ret = double.Parse(s);
} catch { return 0; }
return ret;
}
public static string[] Split(string str, string splitstring) => Regex.Split(str, splitstring);
public static string sprintf(string input, params object[] inpVars) {
// This function was authored by https://stackoverflow.com/users/598420/anirudha
// https://stackoverflow.com/questions/14482341/c-net-and-sprintf-syntax
// Now I am not fully happy about this, as it does support the basics %s and %d etc, but it has no support for %4d and stuff like that
// But it's a start :P (RegEx has never been my forte).
int i = 0;
input = Regex.Replace(input, "%.", m => ("{" + i++/*increase have to be on right side*/ + "}"));
//Console.WriteLine($"input = {input}");
return string.Format(input, inpVars);
}
public static void printf(string input, params object[] inpVars) => Console.Write(sprintf(input, inpVars));
public static void printfln(string input, params object[] inpVars) => Console.WriteLine(sprintf(input, inpVars));
public static string OrText(string One, string Two) { if (One.Trim() != "") return One; else return Two; }
static public string bsdec(string ori) {
var ret = new StringBuilder();
for(int i = 0; i < ori.Length; ++i) {
ret.Append($"{"\\"}{Right($"00{(byte)ori[i]}", 3)}");
}
return ret.ToString();
}
static public byte[] StringToBytes(string ori)=> Encoding.ASCII.GetBytes(ori);
static public string BytesToString(byte[] bytes)=> Encoding.UTF8.GetString(bytes, 0, bytes.Length);
static public string BytesToString(List<byte> bytes) => BytesToString(bytes.ToArray());
}
}