| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="DataSizeConverter.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | namespace MyNet.Primitives.Conversion; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Provides a converter for file size units, allowing conversion between different file size units such as bytes, kilob |
| | | 11 | | /// </summary> |
| | | 12 | | public sealed class DataSizeConverter : IUnitConverter<DataSizeUnit> |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// Converts a file size value from one unit to another. The conversion is performed by calculating the difference i |
| | | 16 | | /// </summary> |
| | | 17 | | /// <param name="value">The file size value to convert.</param> |
| | | 18 | | /// <param name="from">The unit of the input value.</param> |
| | | 19 | | /// <param name="to">The unit to convert the value to.</param> |
| | | 20 | | /// <returns>The converted file size value.</returns> |
| | | 21 | | public double Convert(double value, DataSizeUnit from, DataSizeUnit to) |
| | | 22 | | { |
| | 105 | 23 | | var diff = to - from; |
| | | 24 | | |
| | 105 | 25 | | return diff switch |
| | 105 | 26 | | { |
| | 9 | 27 | | 0 => value, |
| | 72 | 28 | | > 0 => value / Pow1024(diff), |
| | 24 | 29 | | _ => value * Pow1024(-diff) |
| | 105 | 30 | | }; |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | /// <summary> |
| | | 34 | | /// Calculates the power of 1024 for a given exponent. This method multiplies 1024 by itself the specified number of |
| | | 35 | | /// </summary> |
| | | 36 | | /// <param name="exp">The exponent to raise 1024 to.</param> |
| | | 37 | | /// <returns>The result of 1024 raised to the specified exponent.</returns> |
| | | 38 | | private static double Pow1024(int exp) |
| | | 39 | | { |
| | 96 | 40 | | double result = 1; |
| | | 41 | | const double baseValue = 1024; |
| | | 42 | | |
| | 600 | 43 | | for (var i = 0; i < exp; i++) |
| | 204 | 44 | | result *= baseValue; |
| | | 45 | | |
| | 96 | 46 | | return result; |
| | | 47 | | } |
| | | 48 | | } |
| | | 49 | | |