/
ByteSize.cs
606 lines (488 loc) · 19 KB
/
ByteSize.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
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//The MIT License (MIT)
//Copyright (c) 2013-2014 Omar Khudeira (http://omar.io)
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
using System;
using System.Globalization;
using System.Linq;
using Humanizer.Configuration;
using Humanizer.Localisation;
using static System.Globalization.NumberStyles;
namespace Humanizer.Bytes
{
/// <summary>
/// Represents a byte size value.
/// </summary>
#pragma warning disable 1591
public struct ByteSize : IComparable<ByteSize>, IEquatable<ByteSize>, IComparable, IFormattable
{
public static readonly ByteSize MinValue = FromBits(long.MinValue);
public static readonly ByteSize MaxValue = FromBits(long.MaxValue);
public const long BitsInByte = 8;
public const long BytesInKilobyte = 1024;
public const long BytesInMegabyte = 1048576;
public const long BytesInGigabyte = 1073741824;
public const long BytesInTerabyte = 1099511627776;
public const string BitSymbol = "b";
public const string Bit = "bit";
public const string ByteSymbol = "B";
public const string Byte = "byte";
public const string KilobyteSymbol = "KB";
public const string Kilobyte = "kilobyte";
public const string MegabyteSymbol = "MB";
public const string Megabyte = "megabyte";
public const string GigabyteSymbol = "GB";
public const string Gigabyte = "gigabyte";
public const string TerabyteSymbol = "TB";
public const string Terabyte = "terabyte";
public long Bits { get; private set; }
public double Bytes { get; private set; }
public double Kilobytes { get; private set; }
public double Megabytes { get; private set; }
public double Gigabytes { get; private set; }
public double Terabytes { get; private set; }
public string LargestWholeNumberSymbol => GetLargestWholeNumberSymbol();
public string GetLargestWholeNumberSymbol(IFormatProvider provider = null)
{
var cultureFormatter = Configurator.GetFormatter(provider as CultureInfo);
// Absolute value is used to deal with negative values
if (Math.Abs(Terabytes) >= 1)
{
return cultureFormatter.DataUnitHumanize(DataUnit.Terabyte, Terabytes, toSymbol: true);
}
if (Math.Abs(Gigabytes) >= 1)
{
return cultureFormatter.DataUnitHumanize(DataUnit.Gigabyte, Gigabytes, toSymbol: true);
}
if (Math.Abs(Megabytes) >= 1)
{
return cultureFormatter.DataUnitHumanize(DataUnit.Megabyte, Megabytes, toSymbol: true);
}
if (Math.Abs(Kilobytes) >= 1)
{
return cultureFormatter.DataUnitHumanize(DataUnit.Kilobyte, Kilobytes, toSymbol: true);
}
if (Math.Abs(Bytes) >= 1)
{
return cultureFormatter.DataUnitHumanize(DataUnit.Byte, Bytes, toSymbol: true);
}
return cultureFormatter.DataUnitHumanize(DataUnit.Bit, Bits, toSymbol: true);
}
public string LargestWholeNumberFullWord => GetLargestWholeNumberFullWord();
public string GetLargestWholeNumberFullWord(IFormatProvider provider = null)
{
var cultureFormatter = Configurator.GetFormatter(provider as CultureInfo);
// Absolute value is used to deal with negative values
if (Math.Abs(Terabytes) >= 1)
{
return cultureFormatter.DataUnitHumanize(DataUnit.Terabyte, Terabytes, toSymbol: false);
}
if (Math.Abs(Gigabytes) >= 1)
{
return cultureFormatter.DataUnitHumanize(DataUnit.Gigabyte, Gigabytes, toSymbol: false);
}
if (Math.Abs(Megabytes) >= 1)
{
return cultureFormatter.DataUnitHumanize(DataUnit.Megabyte, Megabytes, toSymbol: false);
}
if (Math.Abs(Kilobytes) >= 1)
{
return cultureFormatter.DataUnitHumanize(DataUnit.Kilobyte, Kilobytes, toSymbol: false);
}
if (Math.Abs(Bytes) >= 1)
{
return cultureFormatter.DataUnitHumanize(DataUnit.Byte, Bytes, toSymbol: false);
}
return cultureFormatter.DataUnitHumanize(DataUnit.Bit, Bits, toSymbol: false);
}
public double LargestWholeNumberValue
{
get
{
// Absolute value is used to deal with negative values
if (Math.Abs(Terabytes) >= 1)
{
return Terabytes;
}
if (Math.Abs(Gigabytes) >= 1)
{
return Gigabytes;
}
if (Math.Abs(Megabytes) >= 1)
{
return Megabytes;
}
if (Math.Abs(Kilobytes) >= 1)
{
return Kilobytes;
}
if (Math.Abs(Bytes) >= 1)
{
return Bytes;
}
return Bits;
}
}
public ByteSize(double byteSize)
: this()
{
// Get ceiling because bis are whole units
Bits = (long)Math.Ceiling(byteSize * BitsInByte);
Bytes = byteSize;
Kilobytes = byteSize / BytesInKilobyte;
Megabytes = byteSize / BytesInMegabyte;
Gigabytes = byteSize / BytesInGigabyte;
Terabytes = byteSize / BytesInTerabyte;
}
public static ByteSize FromBits(long value)
{
return new ByteSize(value / (double)BitsInByte);
}
public static ByteSize FromBytes(double value)
{
return new ByteSize(value);
}
public static ByteSize FromKilobytes(double value)
{
return new ByteSize(value * BytesInKilobyte);
}
public static ByteSize FromMegabytes(double value)
{
return new ByteSize(value * BytesInMegabyte);
}
public static ByteSize FromGigabytes(double value)
{
return new ByteSize(value * BytesInGigabyte);
}
public static ByteSize FromTerabytes(double value)
{
return new ByteSize(value * BytesInTerabyte);
}
/// <summary>
/// Converts the value of the current ByteSize object to a string.
/// The metric prefix symbol (bit, byte, kilo, mega, giga, tera) used is
/// the largest metric prefix such that the corresponding value is greater
/// than or equal to one.
/// </summary>
public override string ToString()
{
return ToString(NumberFormatInfo.CurrentInfo);
}
public string ToString(IFormatProvider provider)
{
if (provider == null)
provider = CultureInfo.CurrentCulture;
return string.Format(provider, "{0:0.##} {1}", LargestWholeNumberValue, GetLargestWholeNumberSymbol(provider));
}
public string ToString(string format)
{
return ToString(format, NumberFormatInfo.CurrentInfo);
}
public string ToString(string format, IFormatProvider provider)
{
return ToString(format, provider, toSymbol: true);
}
private string ToString(string format, IFormatProvider provider, bool toSymbol)
{
if (format == null)
format = "G";
if (provider == null)
provider = CultureInfo.CurrentCulture;
if (format == "G")
format = "0.##";
if (!format.Contains("#") && !format.Contains("0"))
{
format = "0.## " + format;
}
format = format.Replace("#.##", "0.##");
var culture = provider as CultureInfo ?? CultureInfo.CurrentCulture;
bool has(string s) => culture.CompareInfo.IndexOf(format, s, CompareOptions.IgnoreCase) != -1;
string output(double n) => n.ToString(format, provider);
var cultureFormatter = Configurator.GetFormatter(provider as CultureInfo);
if (has(TerabyteSymbol))
{
format = format.Replace(TerabyteSymbol, cultureFormatter.DataUnitHumanize(DataUnit.Terabyte, Terabytes, toSymbol));
return output(Terabytes);
}
if (has(GigabyteSymbol))
{
format = format.Replace(GigabyteSymbol, cultureFormatter.DataUnitHumanize(DataUnit.Gigabyte, Gigabytes, toSymbol));
return output(Gigabytes);
}
if (has(MegabyteSymbol))
{
format = format.Replace(MegabyteSymbol, cultureFormatter.DataUnitHumanize(DataUnit.Megabyte, Megabytes, toSymbol));
return output(Megabytes);
}
if (has(KilobyteSymbol))
{
format = format.Replace(KilobyteSymbol, cultureFormatter.DataUnitHumanize(DataUnit.Kilobyte, Kilobytes, toSymbol));
return output(Kilobytes);
}
// Byte and Bit symbol look must be case-sensitive
if (format.IndexOf(ByteSymbol, StringComparison.Ordinal) != -1)
{
format = format.Replace(ByteSymbol, cultureFormatter.DataUnitHumanize(DataUnit.Byte, Bytes, toSymbol));
return output(Bytes);
}
if (format.IndexOf(BitSymbol, StringComparison.Ordinal) != -1)
{
format = format.Replace(BitSymbol, cultureFormatter.DataUnitHumanize(DataUnit.Bit, Bits, toSymbol));
return output(Bits);
}
var formattedLargeWholeNumberValue = LargestWholeNumberValue.ToString(format, provider);
formattedLargeWholeNumberValue = formattedLargeWholeNumberValue.Equals(string.Empty)
? "0"
: formattedLargeWholeNumberValue;
return string.Format("{0} {1}", formattedLargeWholeNumberValue, toSymbol ? GetLargestWholeNumberSymbol(provider) : GetLargestWholeNumberFullWord(provider));
}
/// <summary>
/// Converts the value of the current ByteSize object to a string with
/// full words. The metric prefix symbol (bit, byte, kilo, mega, giga,
/// tera) used is the largest metric prefix such that the corresponding
/// value is greater than or equal to one.
/// </summary>
public string ToFullWords(string format = null, IFormatProvider provider = null)
{
return ToString(format, provider, toSymbol: false);
}
public override bool Equals(object value)
{
if (value == null)
{
return false;
}
ByteSize other;
if (value is ByteSize)
{
other = (ByteSize)value;
}
else
{
return false;
}
return Equals(other);
}
public bool Equals(ByteSize value)
{
return Bits == value.Bits;
}
public override int GetHashCode()
{
return Bits.GetHashCode();
}
public int CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
if (!(obj is ByteSize))
{
throw new ArgumentException("Object is not a ByteSize");
}
return CompareTo((ByteSize)obj);
}
public int CompareTo(ByteSize other)
{
return Bits.CompareTo(other.Bits);
}
public ByteSize Add(ByteSize bs)
{
return new ByteSize(Bytes + bs.Bytes);
}
public ByteSize AddBits(long value)
{
return this + FromBits(value);
}
public ByteSize AddBytes(double value)
{
return this + FromBytes(value);
}
public ByteSize AddKilobytes(double value)
{
return this + FromKilobytes(value);
}
public ByteSize AddMegabytes(double value)
{
return this + FromMegabytes(value);
}
public ByteSize AddGigabytes(double value)
{
return this + FromGigabytes(value);
}
public ByteSize AddTerabytes(double value)
{
return this + FromTerabytes(value);
}
public ByteSize Subtract(ByteSize bs)
{
return new ByteSize(Bytes - bs.Bytes);
}
public static ByteSize operator +(ByteSize b1, ByteSize b2)
{
return new ByteSize(b1.Bytes + b2.Bytes);
}
public static ByteSize operator -(ByteSize b1, ByteSize b2)
{
return new ByteSize(b1.Bytes - b2.Bytes);
}
public static ByteSize operator ++(ByteSize b)
{
return new ByteSize(b.Bytes + 1);
}
public static ByteSize operator -(ByteSize b)
{
return new ByteSize(-b.Bytes);
}
public static ByteSize operator --(ByteSize b)
{
return new ByteSize(b.Bytes - 1);
}
public static bool operator ==(ByteSize b1, ByteSize b2)
{
return b1.Bits == b2.Bits;
}
public static bool operator !=(ByteSize b1, ByteSize b2)
{
return b1.Bits != b2.Bits;
}
public static bool operator <(ByteSize b1, ByteSize b2)
{
return b1.Bits < b2.Bits;
}
public static bool operator <=(ByteSize b1, ByteSize b2)
{
return b1.Bits <= b2.Bits;
}
public static bool operator >(ByteSize b1, ByteSize b2)
{
return b1.Bits > b2.Bits;
}
public static bool operator >=(ByteSize b1, ByteSize b2)
{
return b1.Bits >= b2.Bits;
}
public static bool TryParse(string s, out ByteSize result)
{
return TryParse(s, null, out result);
}
public static bool TryParse(string s, IFormatProvider formatProvider, out ByteSize result)
{
// Arg checking
if (string.IsNullOrWhiteSpace(s))
{
result = default;
return false;
}
// Acquiring culture-specific parsing info
var numberFormat = GetNumberFormatInfo(formatProvider);
const NumberStyles numberStyles = AllowDecimalPoint | AllowThousands | AllowLeadingSign;
var numberSpecialChars = new[]
{
Convert.ToChar(numberFormat.NumberDecimalSeparator),
Convert.ToChar(numberFormat.NumberGroupSeparator),
Convert.ToChar(numberFormat.PositiveSign),
Convert.ToChar(numberFormat.NegativeSign),
};
// Setup the result
result = new ByteSize();
// Get the index of the first non-digit character
s = s.TrimStart(); // Protect against leading spaces
int num;
var found = false;
// Pick first non-digit number
for (num = 0; num < s.Length; num++)
{
if (!(char.IsDigit(s[num]) || numberSpecialChars.Contains(s[num])))
{
found = true;
break;
}
}
if (found == false)
{
return false;
}
var lastNumber = num;
// Cut the input string in half
var numberPart = s.Substring(0, lastNumber).Trim();
var sizePart = s.Substring(lastNumber, s.Length - lastNumber).Trim();
// Get the numeric part
if (!double.TryParse(numberPart, numberStyles, formatProvider, out var number))
{
return false;
}
// Get the magnitude part
switch (sizePart.ToUpper())
{
case ByteSymbol:
if (sizePart == BitSymbol)
{ // Bits
if (number % 1 != 0) // Can't have partial bits
{
return false;
}
result = FromBits((long)number);
}
else
{ // Bytes
result = FromBytes(number);
}
break;
case KilobyteSymbol:
result = FromKilobytes(number);
break;
case MegabyteSymbol:
result = FromMegabytes(number);
break;
case GigabyteSymbol:
result = FromGigabytes(number);
break;
case TerabyteSymbol:
result = FromTerabytes(number);
break;
default:
return false;
}
return true;
}
private static NumberFormatInfo GetNumberFormatInfo(IFormatProvider formatProvider)
{
if (formatProvider is NumberFormatInfo numberFormat)
return numberFormat;
var culture = formatProvider as CultureInfo ?? CultureInfo.CurrentCulture;
return culture.NumberFormat;
}
public static ByteSize Parse(string s)
{
return Parse(s, null);
}
public static ByteSize Parse(string s, IFormatProvider formatProvider)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (TryParse(s, formatProvider, out var result))
{
return result;
}
throw new FormatException("Value is not in the correct format");
}
}
}
#pragma warning restore 1591