-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFITSKey.cs
435 lines (377 loc) · 17 KB
/
FITSKey.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
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
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Complex = System.Numerics.Complex;
using static System.BitConverter;
using static FITS_CS.ExtendedBitConverter;
namespace FITS_CS
{
[DebuggerDisplay(@"\{Header: {Header}, Value: {Value}, Comment: {Comment}\}")]
[DataContract]
public class FitsKey
{
public enum FitsKeyLayout : byte
{
Fixed = 1,
//NonFixed = 2,
}
public const int KeySize = 80;
public const int KeyHeaderSize = 8;
public const int ReservedSize = 2;
public const int StringQuotePos = 20;
public const int NumericValueMaxLengthFixed = 20;
public static FitsKey End => new FitsKey("END", FitsKeywordType.Comment, "");
public static FitsKey Empty => new FitsKey();
[field: DataMember]
private byte[]? RawValue { get;}
[field: DataMember]
public string? Header
{
get;
}
[field: DataMember]
public string Comment { get; } = "";
[field: DataMember]
public string Value { get; } = "";
[field: DataMember]
public FitsKeywordType Type
{
get;
}
public byte[] Data => Encoding.ASCII.GetBytes(KeyString.ToArray());
public string KeyString => $"{Header, -8}{Body}";
public bool IsEmpty => string.IsNullOrWhiteSpace(Header) &&
string.IsNullOrWhiteSpace(Value) &&
string.IsNullOrWhiteSpace(Comment);
public string Body
{
get
{
var isUsual = Type != FitsKeywordType.Blank && Type != FitsKeywordType.Comment;
var body = string.Empty;
if (!string.IsNullOrWhiteSpace(Value))
{
if (isUsual)
body += "= ";
body += Value;
}
if (!string.IsNullOrWhiteSpace(Comment))
body += " / " + Comment;
body = string.Format($"{{0, {(isUsual ? -1 : 1) * (KeySize - KeyHeaderSize)}}}", body)
.Substring(0, KeySize - KeyHeaderSize);
return body;
}
}
public FitsKey(byte[] data, int offset = 0)
{
if (data == null)
throw new ArgumentNullException($"{nameof(data)} is null");
if (data.Length < KeySize + offset)
throw new ArgumentException($"{nameof(data)} has wrong length");
var keyString = new string(Encoding.ASCII.GetChars(data, offset, KeySize));
int maxPos = NumericValueMaxLengthFixed;
Header = keyString.Substring(0, KeyHeaderSize).Trim();
var indexSlash = -1;
var isInQuotes = false;
for (var i = KeyHeaderSize; i < KeySize; i++)
if (keyString[i] == '\'')
isInQuotes = !isInQuotes;
else if (keyString[i] == '/' && !isInQuotes)
{
indexSlash = i;
break;
}
Comment = indexSlash >= KeyHeaderSize ? keyString.Substring(indexSlash + 2).Trim() : "";
if (keyString[KeyHeaderSize] == '=')
{
Value = indexSlash >= KeyHeaderSize
? keyString.Substring(KeyHeaderSize + 2, indexSlash - KeyHeaderSize - 3)
: keyString.Substring(KeyHeaderSize + 2).TrimEnd();
var trimVal = Value.Trim();
if (string.IsNullOrWhiteSpace(trimVal))
{
Type = FitsKeywordType.Blank;
RawValue = new byte[0];
}
else if (trimVal is "F" or "T")
{
Type = FitsKeywordType.Logical;
RawValue = GetBytes(trimVal == "T");
}
else if (trimVal.Contains('\''))
{
Type = FitsKeywordType.String;
var match = Regex.Match(trimVal, "'(.*)'").Groups[1].Value.Replace("''", "'");
RawValue = new byte[match.Length * sizeof(char)];
match.AsSpan().GetBytes(RawValue);
}
else if (Value.Length > maxPos + 1 &&
double.TryParse(Value.Substring(0, maxPos),
NumberStyles.Any, NumberFormatInfo.InvariantInfo, out var real) &&
double.TryParse(Value.Substring(maxPos),
NumberStyles.Any, NumberFormatInfo.InvariantInfo, out var img))
{
Type = FitsKeywordType.Complex;
RawValue = new byte[sizeof(double) * 2];
new Complex(real, img).GetBytes(RawValue);
}
else if (int.TryParse(trimVal, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out var intVal))
{
Type = FitsKeywordType.Integer;
RawValue = GetBytes(intVal);
}
else if (double.TryParse(trimVal, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out var dVal))
{
Type = FitsKeywordType.Float;
RawValue = GetBytes((float)dVal);
}
else throw new ArgumentException("Keyword value is of unknown format.");
}
else
{
Value = keyString.AsSpan(KeyHeaderSize).Trim().ToString();
RawValue = new byte[Value.Length * sizeof(char)];
Value.AsSpan().GetBytes(RawValue);
Type = FitsKeywordType.Comment;
}
}
public FitsKey(string header, FitsKeywordType type, object? value,
string comment = "",
// ReSharper disable once UnusedParameter.Local
FitsKeyLayout layout = FitsKeyLayout.Fixed)
{
if (header is null)
throw new ArgumentNullException(nameof(header));
if (header.Length > KeyHeaderSize)
throw new ArgumentException($"\"{nameof(header)}\" is too long");
Header = header.Trim();
Type = type;
var maxValuePos = NumericValueMaxLengthFixed;
var dblDecPrecision = maxValuePos - 7;
const string complexSep = "";
var strQuotePos = StringQuotePos - 2 - ReservedSize - KeyHeaderSize;
switch (type)
{
case FitsKeywordType.Logical:
if (value is bool bVal)
{
Value = string.Format($"{{0, {maxValuePos}}}", bVal ? 'T' : 'F');
RawValue = GetBytes(bVal);
}
else throw new ArgumentException($"\"{nameof(value)}\" should be of type {typeof(bool)}.");
break;
case FitsKeywordType.Integer:
if (value is int iVal)
{
Value = string.Format($"{{0, {maxValuePos}}}", iVal);
RawValue = GetBytes(iVal);
}
else throw new ArgumentException($"\"{nameof(value)}\" should be of type {typeof(int)}.");
break;
case FitsKeywordType.Float:
if (value is float fVal)
{
Value = string.Format($"{{0, {maxValuePos}}}", fVal.ToString("E8"));
RawValue = GetBytes(fVal);
}
else if (value is double dVal)
{
if (Math.Abs(dVal) >= 1e100 || Math.Abs(dVal) <= 1e-100)
throw new OverflowException($"{typeof(double)} with exponent" +
" greater than 99 or smaller than -99 " +
"cannot be represented in fixed mode.");
Value = string.Format($"{{0, {maxValuePos}}}", FormatDouble(dVal, dblDecPrecision));
RawValue = GetBytes((float)dVal);
}
else throw new ArgumentException($"\"{nameof(value)}\" should be of type" +
$" {typeof(float)} or {typeof(double)}.");
break;
case FitsKeywordType.Complex:
if (value is Complex cVal)
{
if (Math.Abs(cVal.Real) >= 1e100 ||
Math.Abs(cVal.Real) <= 1e-100 ||
Math.Abs(cVal.Imaginary) >= 1e100 ||
Math.Abs(cVal.Imaginary) <= 1e-100)
throw new OverflowException($"{typeof(Complex)} with exponent" +
" greater than 99 or smaller than -99 " +
"cannot be represented in fixed mode.");
Value = string.Format($"{{0, {maxValuePos}}}{complexSep}{{1, {maxValuePos}}}",
FormatDouble(cVal.Real, dblDecPrecision),
FormatDouble(cVal.Imaginary, dblDecPrecision));
RawValue = cVal.GetBytes();
}
else throw new ArgumentException($"\"{nameof(value)}\" should be of type" +
$" {typeof(Complex)}.");
break;
case FitsKeywordType.String:
if (value is string sVal)
{
var srcVal = sVal;
sVal = sVal.Replace("\'", "''").TrimEnd();
if (sVal.Length > KeySize - KeyHeaderSize - ReservedSize - 2)
throw new ArgumentException($"String \"{nameof(value)}\" is too long.");
Value = string.Format($"'{{0, {-strQuotePos}}}'", sVal);
if (Value.Length < maxValuePos)
Value += new string(' ', maxValuePos - Value.Length);
RawValue = srcVal.GetBytes();
}
else throw new ArgumentException($"\"{nameof(value)}\" should be of type" +
$" {typeof(string)}.");
break;
case FitsKeywordType.Comment:
if (header != "COMMENT" && header != "HISTORY" && header != "END")
throw new ArgumentException($"\"{nameof(header)}\" should be either \"COMMENT\" or \"HISTORY\" or \"END\".");
if (value is string commVal)
Value = commVal.Substring(0, Math.Min(commVal.Length, KeySize - KeyHeaderSize));
else throw new ArgumentException($"\"{nameof(value)}\" should be of type {typeof(string)}.");
RawValue = Value.GetBytes();
break;
case FitsKeywordType.Blank:
if (value is string blankVal)
Value = blankVal.Substring(0, Math.Min(blankVal.Length, KeySize - KeyHeaderSize));
else if (value is null)
Value = "";
else throw new ArgumentException($"\"{nameof(value)}\" should be of type {typeof(string)}.");
RawValue = Value.GetBytes();
break;
default:
throw new NotSupportedException($"Unsupported \"{nameof(type)}\".");
}
if (!string.IsNullOrWhiteSpace(comment))
{
var remSpace = KeySize - KeyHeaderSize;
if (type != FitsKeywordType.Blank && type != FitsKeywordType.Comment)
remSpace -= ReservedSize + Value.Length;
if (remSpace > 0)
Comment = comment.Substring(0, Math.Min(comment.Length, remSpace));
}
}
private FitsKey()
{ }
/// <summary>
/// Inefficient way to access strongly typed raw value.
/// Relies on <code>dynamic</code>.
/// </summary>
/// <typeparam name="T">Type of the contained value</typeparam>
/// <returns>Raw value cast to the type.</returns>
[return:MaybeNull]
public T GetValue<T>()
{
if (RawValue is null)
{
return default;
}
if (typeof(T) == typeof(bool)
&& Type == FitsKeywordType.Logical)
{
return Unsafe.As<byte, T>(ref RawValue[0]);
}
if (typeof(T) == typeof(int)
&& Type == FitsKeywordType.Integer)
{
return Unsafe.As<byte, T>(ref RawValue[0]);
}
if (typeof(T) == typeof(float)
&& Type == FitsKeywordType.Float)
{
return Unsafe.As<byte, T>(ref RawValue[0]);
}
if (typeof(T) == typeof(double)
&& Type == FitsKeywordType.Float)
{
var floatVal = Unsafe.As<byte, float>(ref RawValue[0]);
var dblVal = (double) floatVal;
return Unsafe.As<double, T>(ref dblVal);
}
if (typeof(T) == typeof(Complex)
&& Type == FitsKeywordType.Complex)
{
var cmplVal = ToComplex(RawValue);
return Unsafe.As<Complex, T>(ref cmplVal);
}
if (typeof(T) == typeof(string)
&& Type is FitsKeywordType.Comment or FitsKeywordType.String)
{
var strVal = ExtendedBitConverter.ToString(RawValue);
return Unsafe.As<string, T>(ref strVal);
}
throw new ArgumentException(
"Generic type does not match the keyword type and conversion is impossible."
);
}
public override string ToString() => KeyString;
public override bool Equals(object? obj)
{
if (obj is FitsKey key)
return Type.Equals(key.Type) &&
string.Equals(Header, key.Header) &&
Value.Equals(key.Value) &&
Comment.Equals(key.Comment);
return false;
}
public override int GetHashCode()
=> KeyString.GetHashCode();
public static bool IsFitsKey(ReadOnlySpan<byte>data)
{
if (data.IsEmpty)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Length < KeySize)
{
throw new ArgumentException($"{nameof(data)} has wrong length");
}
data = data.Slice(0, KeySize);
Span<char> strBuff = stackalloc char[KeySize];
// TODO : Verify this
GetAsciiChars(data, strBuff);
var strRep = strBuff.ToString();
var isKey = string.IsNullOrWhiteSpace(strRep) ||
strRep.StartsWith("HISTORY ") ||
strRep.StartsWith("COMMENT ") ||
strRep.StartsWith("END");
isKey |= Regex.IsMatch(strRep, $@"^[A-Za-z\ \-_0-9]{{{KeyHeaderSize}}}=\ ");
return isKey;
}
public static bool IsEmptyKey(ReadOnlySpan<byte> data)
{
if (data.Length < KeySize)
{
throw new ArgumentOutOfRangeException(nameof(data));
}
foreach (var b in data.Slice(0, KeySize))
{
if (b == 0 || b == (byte) ' ')
{
continue;
}
return false;
}
return true;
}
public static FitsKey CreateComment(string text)
=> new FitsKey("COMMENT", FitsKeywordType.Comment, text);
public static FitsKey CreateHistory(string text)
=> new FitsKey("HISTORY", FitsKeywordType.Comment, text);
public static FitsKey CreateDate(string header, DateTime date,
string comment = "", string format = "yyyy/MM/dd HH:mm:ss.fff")
=> new FitsKey(header, FitsKeywordType.String, string.Format($"{{0:{format}}}", date), comment);
public static bool operator ==(FitsKey? key1, FitsKey? key2)
=> key1?.Equals(key2) ?? false;
public static bool operator !=(FitsKey? key1, FitsKey? key2)
=> !(key1 == key2);
private static string FormatDouble(double input, int decPlaces)
{
var format = $"E{decPlaces}";
var str = input.ToString(format);
return Regex.Replace(str, "([+-])[0-9]([0-9]{2})$", "$1$2");
}
}
}