forked from KSP-KOS/KOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringValue.cs
More file actions
490 lines (414 loc) · 17.6 KB
/
StringValue.cs
File metadata and controls
490 lines (414 loc) · 17.6 KB
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using kOS.Safe.Encapsulation.Suffixes;
using kOS.Safe.Exceptions;
using kOS.Safe.Utilities;
using kOS.Safe.Serialization;
using System.Collections.Generic;
using System.Collections;
namespace kOS.Safe.Encapsulation
{
/// <summary>
/// The class is a simple wrapper around the string class to
/// implement the Structure and IIndexable interface on
/// strings. Currently, strings are only boxed with this
/// class temporarily when suffix/indexing support is
/// necessary.
/// </summary>
[KOSNomenclature("String")]
public class StringValue : PrimitiveStructure, IIndexable, IConvertible, IEnumerable<string>
{
// internalString is *almost* immutable.
// It is supposed to be immutable (readonly keyword here) except that
// it can't be and also fit the design pattern kOS uses for Serializable structures.
// That pattern is to load from a dump by creating an instance with a dummy
// constructor first, then populate it with LoadDump(). To populate it with LoadDump(),
// the internal representation cannot be readonly. Populating from a dump should be
// the only place the immutability rule is violated.
private string internalString;
public static StringValue Empty { get; } = new StringValue();
public static StringValue None { get; } = new StringValue("None");
public StringValue():
this (string.Empty)
{
}
public StringValue(string stringValue)
{
internalString = stringValue;
RegisterInitializer(StringInitializeSuffixes);
}
public StringValue(StringValue stringValue)
{
internalString = stringValue.ToString();
RegisterInitializer(StringInitializeSuffixes);
}
public StringValue(char ch)
{
internalString = new string(new char[] {ch});
RegisterInitializer(StringInitializeSuffixes);
}
public override object ToPrimitive()
{
return ToString();
}
public ScalarValue Length
{
get { return internalString.Length; }
}
public string Substring(ScalarValue start, ScalarValue count)
{
return internalString.Substring(start, count);
}
public bool Contains(string s)
{
return internalString.IndexOf(s, StringComparison.OrdinalIgnoreCase) >= 0;
}
public bool EndsWith(string s)
{
return internalString.EndsWith(s, StringComparison.OrdinalIgnoreCase);
}
public ScalarValue IndexOf(string s)
{
return internalString.IndexOf(s, StringComparison.OrdinalIgnoreCase);
}
// IndexOf with a start position.
// This was named FindAt because IndexOfAt made little sense.
public ScalarValue FindAt(string s, ScalarValue start)
{
return internalString.IndexOf(s, start, StringComparison.OrdinalIgnoreCase);
}
public string Insert(ScalarValue location, string s)
{
return internalString.Insert(location, s);
}
public int LastIndexOf(string s)
{
return internalString.LastIndexOf(s, StringComparison.OrdinalIgnoreCase);
}
public int FindLastAt(string s, int start)
{
return internalString.LastIndexOf(s, start, StringComparison.OrdinalIgnoreCase);
}
public string PadLeft(int width)
{
return internalString.PadLeft(width);
}
public string PadRight(int width)
{
return internalString.PadRight(width);
}
public string Remove(int start, int count)
{
return internalString.Remove(start, count);
}
public string Replace(string oldString, string newString)
{
return Regex.Replace(internalString, Regex.Escape(oldString), newString, RegexOptions.IgnoreCase);
}
public string ToLower()
{
return internalString.ToLower();
}
public string ToUpper()
{
return internalString.ToUpper();
}
public bool StartsWith(string s)
{
return internalString.StartsWith(s, StringComparison.OrdinalIgnoreCase);
}
public string Trim()
{
return internalString.Trim();
}
public string TrimEnd()
{
return internalString.TrimEnd();
}
public string TrimStart()
{
return internalString.TrimStart();
}
/// <summary>
/// A wrapper around ToScalar to handle the fact that a kOS suffix can't
/// handle being called with zero or one args (optional arg), but can handle
/// a var-args list like this:
/// </summary>
/// <param name="args"></param>
/// <returns></returns>
public ScalarValue ToScalarVarArgsWrapper(params Structure [] args)
{
if (args.Length > 1)
throw new KOSArgumentMismatchException(1, args.Length, "TONUMBER must be called with zero or one argument, no more.");
if (args.Length == 0)
return ToScalar();
else
{
return ToScalar((ScalarValue)args[0]); // should throw error if args[0] isn't ScalarValue.
}
}
/// <summary>
/// Parse the string into a number
/// </summary>
/// <param name="defaultIfError">If the string parse fails, return this value instead. Note that if
/// this optional value is left off, a KOSexception will be thrown on parsing errors instead.</param>
/// <returns></returns>
public ScalarValue ToScalar(ScalarValue defaultIfError = null)
{
ScalarValue result;
if (ScalarValue.TryParse(internalString, out result))
{
return result;
}
else if (defaultIfError != null)
{
return defaultIfError;
}
throw new KOSNumberParseException(internalString);
}
public Structure GetIndex(int index)
{
return new StringValue(internalString[index]);
}
public Structure GetIndex(Structure index)
{
if (index is ScalarValue)
{
int i = Convert.ToInt32(index); // allow expressions like (1.0) to be indexes
return new StringValue(internalString[i]);
}
throw new KOSCastException(index.GetType(), typeof(ScalarValue));
}
// Required by the interface but unimplemented, because strings are immutable.
public void SetIndex(Structure index, Structure value)
{
throw new KOSException("Strings are immutable; they can not be modified using the syntax \"SET string[1] TO 'a'\", etc.");
}
// Required by the interface but unimplemented, because strings are immutable.
public void SetIndex(int index, Structure value)
{
throw new KOSException("Strings are immutable; they can not be modified using the syntax \"SET string[1] TO 'a'\", etc.");
}
public IEnumerator<string> GetEnumerator ()
{
for (int i = 0; i < internalString.Length; i++) {
yield return internalString[i].ToString();
}
}
System.Collections.IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
// As the regular Split, except returning a ListValue rather than an array.
public ListValue SplitToList(string separator)
{
string[] split = Regex.Split(internalString, Regex.Escape(separator), RegexOptions.IgnoreCase);
ListValue returnList = new ListValue();
foreach (string s in split)
returnList.Add(new StringValue(s));
return returnList;
}
public BooleanValue MatchesPattern(string pattern)
{
return new BooleanValue(Regex.IsMatch(internalString, pattern, RegexOptions.IgnoreCase));
}
public StringValue Format(params Structure[] args)
{
if (args.Length == 0)
return this;
return new StringValue(string.Format(CultureInfo.InvariantCulture, this, args));
}
private void StringInitializeSuffixes()
{
AddSuffix("LENGTH", new NoArgsSuffix<ScalarValue>( () => Length));
AddSuffix("SUBSTRING", new TwoArgsSuffix<StringValue, ScalarValue, ScalarValue>( (one, two) => Substring(one, two)));
AddSuffix("CONTAINS", new OneArgsSuffix<BooleanValue, StringValue>( one => Contains(one)));
AddSuffix("ENDSWITH", new OneArgsSuffix<BooleanValue, StringValue>( one => EndsWith(one)));
AddSuffix("FINDAT", new TwoArgsSuffix<ScalarValue, StringValue, ScalarValue>( (one, two) => FindAt(one, two)));
AddSuffix("INSERT", new TwoArgsSuffix<StringValue, ScalarValue, StringValue>( (one, two) => Insert(one, two)));
AddSuffix("FINDLASTAT", new TwoArgsSuffix<ScalarValue, StringValue, ScalarValue>( (one, two) => FindLastAt(one, two)));
AddSuffix("PADLEFT", new OneArgsSuffix<StringValue, ScalarValue>( one => PadLeft(one)));
AddSuffix("PADRIGHT", new OneArgsSuffix<StringValue, ScalarValue>( one => PadRight(one)));
AddSuffix("REMOVE", new TwoArgsSuffix<StringValue, ScalarValue, ScalarValue>( (one, two) => Remove(one, two)));
AddSuffix("REPLACE", new TwoArgsSuffix<StringValue, StringValue, StringValue>( (one, two) => Replace(one, two)));
AddSuffix("SPLIT", new OneArgsSuffix<ListValue, StringValue>( one => SplitToList(one)));
AddSuffix("STARTSWITH", new OneArgsSuffix<BooleanValue, StringValue>( one => StartsWith(one)));
AddSuffix("TOLOWER", new NoArgsSuffix<StringValue>(() => ToLower()));
AddSuffix("TOUPPER", new NoArgsSuffix<StringValue>(() => ToUpper()));
AddSuffix("TRIM", new NoArgsSuffix<StringValue>(() => Trim()));
AddSuffix("TRIMEND", new NoArgsSuffix<StringValue>(() => TrimEnd()));
AddSuffix("TRIMSTART", new NoArgsSuffix<StringValue>(() => TrimStart()));
AddSuffix("MATCHESPATTERN", new OneArgsSuffix<BooleanValue, StringValue>( one => MatchesPattern(one)));
AddSuffix(new[] { "TONUMBER", "TOSCALAR" }, new VarArgsSuffix<ScalarValue, Structure>(ToScalarVarArgsWrapper));
AddSuffix("FORMAT", new VarArgsSuffix<StringValue, Structure>(Format));
// Aliased "IndexOf" with "Find" to match "FindAt" (since IndexOfAt doesn't make sense, but I wanted to stick with common/C# names when possible)
AddSuffix(new[] { "INDEXOF", "FIND" }, new OneArgsSuffix<ScalarValue, StringValue> ( one => IndexOf(one)));
AddSuffix(new[] { "LASTINDEXOF", "FINDLAST" }, new OneArgsSuffix<ScalarValue, StringValue> ( s => LastIndexOf(s)));
AddSuffix("ITERATOR", new NoArgsSuffix<Enumerator>( () => new Enumerator(GetEnumerator()) ));
}
public static bool operator ==(StringValue val1, StringValue val2)
{
Type compareType = typeof(StringValue);
if (compareType.IsInstanceOfType(val1))
{
return val1.Equals(val2); // val1 is not null, we can use the built in equals function
}
return !compareType.IsInstanceOfType(val2); // val1 is null, return true if val2 is null and false if not null
}
public static bool operator !=(StringValue val1, StringValue val2)
{
return !(val1 == val2);
}
public static bool operator >(StringValue val1, StringValue val2)
{
int compareNum = string.Compare(val1, val2, StringComparison.OrdinalIgnoreCase);
return compareNum > 0;
}
public static bool operator <(StringValue val1, StringValue val2)
{
int compareNum = string.Compare(val1, val2, StringComparison.OrdinalIgnoreCase);
return compareNum < 0;
}
public static bool operator >=(StringValue val1, StringValue val2)
{
int compareNum = string.Compare(val1, val2, StringComparison.OrdinalIgnoreCase);
return compareNum >= 0;
}
public static bool operator <=(StringValue val1, StringValue val2)
{
int compareNum = string.Compare(val1, val2, StringComparison.OrdinalIgnoreCase);
return compareNum <= 0;
}
// Implicitly converts to a string (i.e., unboxes itself automatically)
public static implicit operator string(StringValue value)
{
return value.internalString;
}
public static implicit operator StringValue(string value)
{
return new StringValue(value);
}
public static StringValue operator +(StringValue val1, StringValue val2)
{
return new StringValue(val1.ToString() + val2.ToString());
}
public static StringValue operator +(StringValue val1, Structure val2)
{
return new StringValue(val1.ToString() + val2.ToString());
}
public static StringValue operator +(Structure val1, StringValue val2)
{
return new StringValue(val1.ToString() + val2.ToString());
}
public override string ToString()
{
return this;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
if (obj is StringValue || obj is string)
{
return string.Equals(internalString, obj.ToString(), StringComparison.OrdinalIgnoreCase);
}
return false;
}
public override int GetHashCode()
{
return internalString.GetHashCode();
}
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.Object;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
if (string.IsNullOrEmpty(internalString)) return false;
return true;
}
byte IConvertible.ToByte(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(byte));
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(char));
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(DateTime));
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(Decimal));
}
double IConvertible.ToDouble(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(Double));
}
short IConvertible.ToInt16(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(Int16));
}
int IConvertible.ToInt32(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(Int32));
}
long IConvertible.ToInt64(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(Int64));
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(SByte));
}
float IConvertible.ToSingle(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(Single));
}
string IConvertible.ToString(IFormatProvider provider)
{
return internalString;
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
if (conversionType == typeof(StringValue))
return this;
else if (conversionType == typeof(BooleanValue))
return new BooleanValue(string.IsNullOrEmpty(internalString) ? false : true);
else if (conversionType.IsSubclassOf(typeof(Structure)))
throw new KOSCastException(typeof(StringValue), conversionType);
return Convert.ChangeType(internalString, conversionType);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(UInt16));
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(UInt32));
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
throw new KOSCastException(typeof(StringValue), typeof(UInt64));
}
// Required for all IDumpers for them to work, but can't enforced by the interface because it's static:
public static StringValue CreateFromDump(SafeSharedObjects shared, Dump d)
{
var newObj = new StringValue();
newObj.LoadDump(d);
return newObj;
}
public override Dump Dump()
{
DumpWithHeader dump = new DumpWithHeader();
dump.Add("value", internalString);
return dump;
}
public override void LoadDump(Dump dump)
{
internalString = Convert.ToString(dump["value"]);
}
}
}