ByteSize.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. using System;
  2. using System.Globalization;
  3. namespace Optimizer {
  4. /// <summary>
  5. /// Represents a byte size value with support for decimal (KiloByte) and
  6. /// binary values (KibiByte).
  7. /// </summary>
  8. public partial struct ByteSize : IComparable<ByteSize>, IEquatable<ByteSize> {
  9. public static readonly ByteSize MinValue = ByteSize.FromBits(long.MinValue);
  10. public static readonly ByteSize MaxValue = ByteSize.FromBits(long.MaxValue);
  11. public const long BitsInByte = 8;
  12. public const string BitSymbol = "b";
  13. public const string ByteSymbol = "B";
  14. public long Bits { get; private set; }
  15. public double Bytes { get; private set; }
  16. public string LargestWholeNumberBinarySymbol {
  17. get {
  18. // Absolute value is used to deal with negative values
  19. if (Math.Abs(this.PebiBytes) >= 1)
  20. return PebiByteSymbol;
  21. if (Math.Abs(this.TebiBytes) >= 1)
  22. return TebiByteSymbol;
  23. if (Math.Abs(this.GibiBytes) >= 1)
  24. return GibiByteSymbol;
  25. if (Math.Abs(this.MebiBytes) >= 1)
  26. return MebiByteSymbol;
  27. if (Math.Abs(this.KibiBytes) >= 1)
  28. return KibiByteSymbol;
  29. if (Math.Abs(this.Bytes) >= 1)
  30. return ByteSymbol;
  31. return BitSymbol;
  32. }
  33. }
  34. public string LargestWholeNumberDecimalSymbol {
  35. get {
  36. // Absolute value is used to deal with negative values
  37. if (Math.Abs(this.PetaBytes) >= 1)
  38. return PetaByteSymbol;
  39. if (Math.Abs(this.TeraBytes) >= 1)
  40. return TeraByteSymbol;
  41. if (Math.Abs(this.GigaBytes) >= 1)
  42. return GigaByteSymbol;
  43. if (Math.Abs(this.MegaBytes) >= 1)
  44. return MegaByteSymbol;
  45. if (Math.Abs(this.KiloBytes) >= 1)
  46. return KiloByteSymbol;
  47. if (Math.Abs(this.Bytes) >= 1)
  48. return ByteSymbol;
  49. return BitSymbol;
  50. }
  51. }
  52. public double LargestWholeNumberBinaryValue {
  53. get {
  54. // Absolute value is used to deal with negative values
  55. if (Math.Abs(this.PebiBytes) >= 1)
  56. return this.PebiBytes;
  57. if (Math.Abs(this.TebiBytes) >= 1)
  58. return this.TebiBytes;
  59. if (Math.Abs(this.GibiBytes) >= 1)
  60. return this.GibiBytes;
  61. if (Math.Abs(this.MebiBytes) >= 1)
  62. return this.MebiBytes;
  63. if (Math.Abs(this.KibiBytes) >= 1)
  64. return this.KibiBytes;
  65. if (Math.Abs(this.Bytes) >= 1)
  66. return this.Bytes;
  67. return this.Bits;
  68. }
  69. }
  70. public double LargestWholeNumberDecimalValue {
  71. get {
  72. // Absolute value is used to deal with negative values
  73. if (Math.Abs(this.PetaBytes) >= 1)
  74. return this.PetaBytes;
  75. if (Math.Abs(this.TeraBytes) >= 1)
  76. return this.TeraBytes;
  77. if (Math.Abs(this.GigaBytes) >= 1)
  78. return this.GigaBytes;
  79. if (Math.Abs(this.MegaBytes) >= 1)
  80. return this.MegaBytes;
  81. if (Math.Abs(this.KiloBytes) >= 1)
  82. return this.KiloBytes;
  83. if (Math.Abs(this.Bytes) >= 1)
  84. return this.Bytes;
  85. return this.Bits;
  86. }
  87. }
  88. public ByteSize(long bits)
  89. : this() {
  90. Bits = bits;
  91. Bytes = bits / BitsInByte;
  92. }
  93. public ByteSize(double bytes)
  94. : this() {
  95. // Get ceiling because bits are whole units
  96. Bits = (long)Math.Ceiling(bytes * BitsInByte);
  97. Bytes = bytes;
  98. }
  99. public static ByteSize FromBits(long value) {
  100. return new ByteSize(value);
  101. }
  102. public static ByteSize FromBytes(double value) {
  103. return new ByteSize(value);
  104. }
  105. /// <summary>
  106. /// Converts the value of the current object to a string.
  107. /// The prefix symbol (bit, byte, kilo, mebi, gibi, tebi) used is the
  108. /// largest prefix such that the corresponding value is greater than or
  109. /// equal to one.
  110. /// </summary>
  111. public override string ToString() {
  112. return this.ToString("0.##", CultureInfo.CurrentCulture);
  113. }
  114. public string ToString(string format) {
  115. return this.ToString(format, CultureInfo.CurrentCulture);
  116. }
  117. public string ToString(string format, IFormatProvider provider, bool useBinaryByte = false) {
  118. if (!format.Contains("#") && !format.Contains("0"))
  119. format = "0.## " + format;
  120. if (provider == null) provider = CultureInfo.CurrentCulture;
  121. Func<string, bool> has = s => format.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) != -1;
  122. Func<double, string> output = n => n.ToString(format, provider);
  123. // Binary
  124. if (has("PiB"))
  125. return output(this.PebiBytes);
  126. if (has("TiB"))
  127. return output(this.TebiBytes);
  128. if (has("GiB"))
  129. return output(this.GibiBytes);
  130. if (has("MiB"))
  131. return output(this.MebiBytes);
  132. if (has("KiB"))
  133. return output(this.KibiBytes);
  134. // Decimal
  135. if (has("PB"))
  136. return output(this.PetaBytes);
  137. if (has("TB"))
  138. return output(this.TeraBytes);
  139. if (has("GB"))
  140. return output(this.GigaBytes);
  141. if (has("MB"))
  142. return output(this.MegaBytes);
  143. if (has("KB"))
  144. return output(this.KiloBytes);
  145. // Byte and Bit symbol must be case-sensitive
  146. if (format.IndexOf(ByteSize.ByteSymbol) != -1)
  147. return output(this.Bytes);
  148. if (format.IndexOf(ByteSize.BitSymbol) != -1)
  149. return output(this.Bits);
  150. if (useBinaryByte) {
  151. return string.Format("{0} {1}", this.LargestWholeNumberBinaryValue.ToString(format, provider), this.LargestWholeNumberBinarySymbol);
  152. }
  153. else {
  154. return string.Format("{0} {1}", this.LargestWholeNumberDecimalValue.ToString(format, provider), this.LargestWholeNumberDecimalSymbol);
  155. }
  156. }
  157. public override bool Equals(object value) {
  158. if (value == null)
  159. return false;
  160. ByteSize other;
  161. if (value is ByteSize)
  162. other = (ByteSize)value;
  163. else
  164. return false;
  165. return Equals(other);
  166. }
  167. public bool Equals(ByteSize value) {
  168. return this.Bits == value.Bits;
  169. }
  170. public override int GetHashCode() {
  171. return this.Bits.GetHashCode();
  172. }
  173. public int CompareTo(ByteSize other) {
  174. return this.Bits.CompareTo(other.Bits);
  175. }
  176. public ByteSize Add(ByteSize bs) {
  177. return new ByteSize(this.Bytes + bs.Bytes);
  178. }
  179. public ByteSize AddBits(long value) {
  180. return this + FromBits(value);
  181. }
  182. public ByteSize AddBytes(double value) {
  183. return this + ByteSize.FromBytes(value);
  184. }
  185. public ByteSize Subtract(ByteSize bs) {
  186. return new ByteSize(this.Bytes - bs.Bytes);
  187. }
  188. public static ByteSize operator +(ByteSize b1, ByteSize b2) {
  189. return new ByteSize(b1.Bytes + b2.Bytes);
  190. }
  191. public static ByteSize operator ++(ByteSize b) {
  192. return new ByteSize(b.Bytes + 1);
  193. }
  194. public static ByteSize operator -(ByteSize b) {
  195. return new ByteSize(-b.Bytes);
  196. }
  197. public static ByteSize operator -(ByteSize b1, ByteSize b2) {
  198. return new ByteSize(b1.Bytes - b2.Bytes);
  199. }
  200. public static ByteSize operator --(ByteSize b) {
  201. return new ByteSize(b.Bytes - 1);
  202. }
  203. public static bool operator ==(ByteSize b1, ByteSize b2) {
  204. return b1.Bits == b2.Bits;
  205. }
  206. public static bool operator !=(ByteSize b1, ByteSize b2) {
  207. return b1.Bits != b2.Bits;
  208. }
  209. public static bool operator <(ByteSize b1, ByteSize b2) {
  210. return b1.Bits < b2.Bits;
  211. }
  212. public static bool operator <=(ByteSize b1, ByteSize b2) {
  213. return b1.Bits <= b2.Bits;
  214. }
  215. public static bool operator >(ByteSize b1, ByteSize b2) {
  216. return b1.Bits > b2.Bits;
  217. }
  218. public static bool operator >=(ByteSize b1, ByteSize b2) {
  219. return b1.Bits >= b2.Bits;
  220. }
  221. public static ByteSize Parse(string s) {
  222. return Parse(s, NumberFormatInfo.CurrentInfo);
  223. }
  224. public static ByteSize Parse(string s, IFormatProvider formatProvider) {
  225. return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, formatProvider);
  226. }
  227. public static ByteSize Parse(string s, NumberStyles numberStyles, IFormatProvider formatProvider) {
  228. // Arg checking
  229. if (string.IsNullOrWhiteSpace(s))
  230. throw new ArgumentNullException("s", "String is null or whitespace");
  231. // Get the index of the first non-digit character
  232. s = s.TrimStart(); // Protect against leading spaces
  233. var num = 0;
  234. var found = false;
  235. var numberFormatInfo = NumberFormatInfo.GetInstance(formatProvider);
  236. var decimalSeparator = Convert.ToChar(numberFormatInfo.NumberDecimalSeparator);
  237. var groupSeparator = Convert.ToChar(numberFormatInfo.NumberGroupSeparator);
  238. // Pick first non-digit number
  239. for (num = 0; num < s.Length; num++)
  240. if (!(char.IsDigit(s[num]) || s[num] == decimalSeparator || s[num] == groupSeparator)) {
  241. found = true;
  242. break;
  243. }
  244. if (found == false)
  245. throw new FormatException($"No byte indicator found in value '{s}'.");
  246. int lastNumber = num;
  247. // Cut the input string in half
  248. string numberPart = s.Substring(0, lastNumber).Trim();
  249. string sizePart = s.Substring(lastNumber, s.Length - lastNumber).Trim();
  250. // Get the numeric part
  251. double number;
  252. if (!double.TryParse(numberPart, numberStyles, formatProvider, out number))
  253. throw new FormatException($"No number found in value '{s}'.");
  254. // Get the magnitude part
  255. switch (sizePart) {
  256. case "b":
  257. if (number % 1 != 0) // Can't have partial bits
  258. throw new FormatException($"Can't have partial bits for value '{s}'.");
  259. return FromBits((long)number);
  260. case "B":
  261. return FromBytes(number);
  262. }
  263. switch (sizePart.ToLowerInvariant()) {
  264. // Binary
  265. case "kib":
  266. return FromKibiBytes(number);
  267. case "mib":
  268. return FromMebiBytes(number);
  269. case "gib":
  270. return FromGibiBytes(number);
  271. case "tib":
  272. return FromTebiBytes(number);
  273. case "pib":
  274. return FromPebiBytes(number);
  275. // Decimal
  276. case "kb":
  277. return FromKiloBytes(number);
  278. case "mb":
  279. return FromMegaBytes(number);
  280. case "gb":
  281. return FromGigaBytes(number);
  282. case "tb":
  283. return FromTeraBytes(number);
  284. case "pb":
  285. return FromPetaBytes(number);
  286. default:
  287. throw new FormatException($"Bytes of magnitude '{sizePart}' is not supported.");
  288. }
  289. }
  290. public static bool TryParse(string s, out ByteSize result) {
  291. try {
  292. result = Parse(s);
  293. return true;
  294. }
  295. catch {
  296. result = new ByteSize();
  297. return false;
  298. }
  299. }
  300. public static bool TryParse(string s, NumberStyles numberStyles, IFormatProvider formatProvider, out ByteSize result) {
  301. try {
  302. result = Parse(s, numberStyles, formatProvider);
  303. return true;
  304. }
  305. catch {
  306. result = new ByteSize();
  307. return false;
  308. }
  309. }
  310. }
  311. }