Code Monkey home page Code Monkey logo

bytesize's People

Contributors

0xced avatar atifaziz avatar georgehahn avatar jamessinclairbiomni avatar jetersen avatar mburumaxwell avatar mintsoft avatar omar avatar rbarbe avatar taori avatar tyrrrz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bytesize's Issues

Change root namespace to avoid conflict

Naming a type in a namespace the same as the namespace is considered bad practice.

I'd like to change the namespace so as to avoid IDE autocomplete conflicts and to follow best practices. However, I'm not sure what to use:

  • Omar.ByteSize
  • Bytes.ByteSize

Seemingly huge number of dependencies for a "small library"

Hello,

I am trying to use this library, but the moment I do add nuget package (Visual Studio Professional 2019, 16.8.3) I am greeted with this list of "dependencies"/about to install:

image

My csproj for this particular project is actually quite straightforward:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>
</Project>

So I am trying to keep things lean in my codebase, but if I look at that window of changes about to happen to my project, I think twice "Okay, do I really need this library?"

To be honest I would expect zero dependencies from ByteSize.

Or am I missing something obvious?

Kind regards and thanks.

Recommended way to parse legacy strings

Hello and thank you for providing such a helpful library.

I am wondering if there is a recommended way of parsing legacy strings?

I don't have control over the string values but the expectation is that they should all result in the binary system's value of bytes.

So, for example, my application needs to parse strings that are formatted as such as ByteSize.Parse("4GB") but as the binary representation, so that the resulting ByteSize.Bytes field is equal to 4294967296 and not 4000000000.

There are some hacky things I can do to manipulate the string before passing it into ByteSize, but was wondering if I was missing a library feature that would enable this functionality (other than downgrading to 1.0).

Thanks!

FR: INumber interface implementation (generic math)

INumber interface is available in .net7.0 and will be available in .net8.0. I propose to implement this interface for ByteSize type in order to be able to use ByteSize type in code with generalised maths, which would be very convenient. However, this requires a lot of time and code, so I suggest to implement INumber interface in stages, and I am willing to help with this. the corresponding pull reqests will contain the name of this issue.

Support Dotnet core without the need of referencing Microsoft.NETCore.Portable.Compatibility

Hi there,

I'm using your nice library in a dotnet core 1.1 project. Unfortunately I'm seeing errors like

The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes'. [netcoreapp1.1]

I can somehow work around this by referencing Microsoft.NETCore.Portable.Compatibility but it would be nice if your library would support dotnet core directly.

Kind regards

Would like to see a "recipe" version

I love this library and would like to see a recipe version to not require a package reference that is passed downstream. A recipe will install the CS file as content and compile the logic in while continuing to allow for updates and bug fixes to be distributed via NuGet.

I publish both a dll package and a recipe/cs package for one of my libraries Naos.WiRM(https://github.com/NaosProject/Naos.WinRM) if you would like to look an example of editing the file to support both.

I have created a wrapped version of this in a NuGet package already to allow for my using it while having this conversation; (https://www.myget.org/feed/naos-nuget/package/nuget/Naos.Recipes.ByteSize). I would rather have this published here for ease of getting updates.

Please let me know if this is something you would consider providing.

Thank you,
Lawson

Binaries are not strong name signed

Hi,

This is preventing us from calling the byteSize dll from a strong name assembly file (signed code can't call unsigned code).

Can you please sign your binary?

0 defaults to bits (b) whereas all other values defaults to bytes (B)

Basically:

Console.WriteLine(ByteSize.FromBytes(0).ToString()); outputs 0b
Console.WriteLine(ByteSize.FromBytes(1).ToString()); outputs 1B

image

This looks really messy when it's used to format a whole table of results etc, it's very rare to actually "see" bits in the wild as most things are usually measured in Bytes. I'm advocating to change the default unit of "0" to be bytes.

Remove increment/decrement operators

Incrementing or decrementing a ByteSize object by 1 byte doesn't seem to fit well with the overall design. 1 byte was an arbitrary value picked. Additionally, ByteSize was modeled after DateTime/TimeSpan, both of which don't have an increment or decrement operator.

Internationalization

Hi !
Amazing job on this library, it is so usefull.

Howerver I'm strugling will one thing : does the ToString function support units in other languages ?It does support english units (KB, MB, GB), but I'm having trouble with french.
In french a byte is called an "octet", so the units are writen like "Ko", "Mo", "Go"...
image

I can do something like
myByteSize.ToString("GB").Replace("GB", "Go")
but it's not very clean.

Am I missing something ?
If not, any chance to see an internationalization feature in the future ?
Thanks :)

Unnecessary dependencies

When adding ByteSize to a project that targets the full framework (like .NET 4.5 or .NET 4.6), the following dependencies are also added:

  • System.Globalization
  • System.Resources.ResourceManager
  • System.Runtime
  • System.Runtime.Extensions

These should only be added for .NET Core installs.

Request ByteSize.MinValue 0

Hi, i want to propose a change of ByteSize.MinValue.

I've just used the property and expected it to be zero since negative amounts of data are impossible.

I just wanted to mention this, since it would be the value most consumers would probably expect this as MinValue.

OT: Nice work on this library. Much appreciated.

Everything returns 0 with ByteSize.Parse or ByteSize.TryParse

Installed the latest version from NuGet. Using Visual Studio 2015 targeting .NET 4.5 and made this code:

var m = ByteSize.Parse("1.55B").MegaBytes;
var n = ByteSize.Parse("24.44 gB").MegaBytes;

ByteSize output;
ByteSize.TryParse("24.44 gB", out output);
var o = output.MegaBytes;

All 3 variables (m,n,o) result in 0. Not sure what's the matter here.

The following example does work as intended:
var monthlyUsage = ByteSize.FromGigaBytes(10);

Support subtracting two ByteSize objects

Support subtracting two ByteSize objects to allow for the following use case:

var quota = ByteSize.FromMegaBytes(20);
var usage = ByteSize.FromMegaBytes(19);
var newFile = ByteSize.FromMegaBytes(2);

if (usage + newFile > quota) {
    var overage = usage + newFile - quota;
    throw new InvalidOperationException($"This file would put you above your quota of { quota } by { overage }");
}

Remove "AddX" method like AddKiloByte/AddKebibyte etc.

Not sure how useful AddKiloByte/AddKebibyte and their sibling methods are. These were added to mimic DateTime behavior (AddSeconds, AddMinutes, etc.), but with the addition of binary and decimal to the class, I could these being a bit redundant and excessive.

MIT license, pleeease :)

Hi @omar,

We have a discussion over at Humanizer about pulling ByteSize in. The current license is cool and all; but it makes it a tad difficult to deal with changes. So I was wondering if there is a chance you could change your license to MIT to make it a bit more liberating. It would be really appreciated by Humanizer users & me :)

Either way, thanks for the great project.

Code bug

ByteSize.FromBits(Int64.MaxValue);

The above initializes the struct with a number of bits equal to -9223372036854775808. Surrounding large numbers also don't work.

Please fix your math or change the argument type to Int32 if you handle smaller numbers only.

ByteSizeTypeConverter issue

We are using ConfigurationBinder to populate the value from the configuration section, but looks like the converter is not picked up (probably because it's defined as internal) :

image

Next call converter.CanConvertFrom(typeof(string)) returns false and the converter is not invoked.

Snippet from ConfigurationBinder :

 TypeConverter converter = TypeDescriptor.GetConverter(type);
     if (converter.CanConvertFrom(typeof(string))) {
 ...
       }

Please make the ByteSizeTypeConverter as public .

Building with sdk 7.0, targeting 6.0

Suggestion: add helpers to format pairs of `ByteSize` in progress-like scenarios

I think helpers to format pairs of 2 ByteSize in progress-like scenarios might come in handy:

(Sorry I like F#)

open ByteSizeLib


[<RequireQualifiedAccess>]
module Tuple2 = let map f (a, b) = f a, f b

[<RequireQualifiedAccess>]
module ByteSize =
    
    let ofBytes bytes = ByteSize(bytes=bytes)
    let ofBits bits = ByteSize(bits=bits)
    
    let getDecValueOfSymbol decSymbol (value: ByteSize) = 
        match decSymbol with
        | ByteSize.PetaByteSymbol -> value.PetaBytes
        | ByteSize.TeraByteSymbol -> value.TeraBytes
        | ByteSize.GigaByteSymbol -> value.GigaBytes
        | ByteSize.MegaByteSymbol -> value.MegaBytes
        | ByteSize.KiloByteSymbol -> value.KiloBytes
        | ByteSize.ByteSymbol     -> value.Bytes
        | _                       -> failwith $"{decSymbol} is not supported a decimal symbol."
    let getBinValueOfSymbol binSymbol (value: ByteSize) = 
        match binSymbol with
        | ByteSize.PebiByteSymbol -> value.PebiBytes
        | ByteSize.TebiByteSymbol -> value.TebiBytes
        | ByteSize.GibiByteSymbol -> value.GibiBytes
        | ByteSize.MebiByteSymbol -> value.MebiBytes
        | ByteSize.KibiByteSymbol -> value.KibiBytes
        | ByteSize.BitSymbol      -> double value.Bits
        | _                       -> failwith $"{binSymbol} is not supported a binary symbol."
        
    let toDecString (value: ByteSize) = value.ToString(value.LargestWholeNumberDecimalSymbol)
    let toBinString (value: ByteSize) = value.ToString(value.LargestWholeNumberBinarySymbol)
        
    let formatDecPair separator (value, maxValue: ByteSize) =
        (getDecValueOfSymbol maxValue.LargestWholeNumberDecimalSymbol value, separator, toDecString maxValue)
        |||> sprintf "%g%s%s"
        
    let formatBinPair separator (value, maxValue: ByteSize) =
        (getBinValueOfSymbol maxValue.LargestWholeNumberBinarySymbol value, separator, toBinString maxValue)
        |||> sprintf "%g%s%s"


[<EntryPoint>]
let main _ =
        
    [ 230.         , 5000000.
      512          , 4500123.
      63120.       , 666400000430.
      63120.       , 23400000435000.
      99312312120. , 12312323406706000000. ]
    |> List.map (Tuple2.map ByteSize.ofBytes)
    |> List.map (ByteSize.formatBinPair @"/")
    |> List.iter (printfn "%s")
        

[<EntryPoint>]
let main _ =
        
    [ 230.         , 5000000.
      512          , 4500123.
      63120.       , 666400000430.
      63120.       , 23400000435000.
      99312312120. , 12312323406706000000. ]
    |> List.map (Tuple2.map ByteSize.ofBytes)
    |> List.map (ByteSize.formatBinaryProgress @"/")
    |> List.iter (printfn "%s")

Output:

0.000219345/4.77 MiB
0.000488281/4.29 MiB
5.87851e-05/620.63 GiB
5.74073e-08/21.28 TiB
8.82071e-05/10935.54 PiB

Found it quite convenient

ByteSize of zero returns unexpected formatting of " b"

Console.WriteLine(new ByteSize(0).ToString());
Console.WriteLine(ByteSize.FromBytes(0).ToString());
Console.WriteLine(ByteSize.MinValue.ToString());

All of the above return (space following by a lowercase B):

 b
 b
 b

I'm guessing this is not the intended behavior? Certainly isn't desired.

[Feature request] Option to format speed (smth/s)

It would be very useful.

Because right now if I pass a custom IFormatProvider to ToString() method, it applied to number part and I am getting something like this: 80/s Mb.

Anyway, I do not insist.

Formattable ToString exception in 2.1.0

In the 2.1.0 release the ByteSize class had the IFormattable implemented and a new ToString overload to go along with it. This causes a NullReferenceException to occur in this scenario:

$"{new ByteSize()}"

Due to the string interpolation being used without any formatting specified the format value in the ToString method overload gets set to null. Since the ToString method doesn't have a null check this will fail.
If instead a ToString() is explicitly used it will work since the default ToString method overload gets used which specifies the default format string:

$"{new ByteSize()}.ToString()"

I'm thinking the easiest solution would be to have the ToString method check if the format value is null and if so default it to "0.##". For now I'm going to have to roll back the version to 2.0.0 since this has broken a lot for me.

Migrate to csproj

I'm using this library in an app that runs inside a docker container. Due to having been built with project.json format, this library requires an sdk image to run, which is significantly bigger than the runtime image. Switching to csproj should fix it.

Missing XML documentation for the library

The library currently doesn't add XML docs to the package, meaning it has zero documentation on the consumer side.

I suggest the project generates XML documentation in release mode and includes that in future package deployments.

I think it would be important to have proper documentation for this considering the many behaviors (like bytes vs decimals) etc.

Localization of TryParse function.

Hello.
first of all, thanks for providing such wonderful library, it is highly appreciated.
it would be nice if you could localize tryparse and parse functions or provide an overload that supports localization.
this line in ByteSize.cs

if (!( char .IsDigit(s[num]) || s[num] == '.'))

would cause your library to fail when running

ByteSize.Parse("1,55 GB");

although this is valid in german locale where comma is the official decimal seperator.

so I guess you could replace the dot with numberformat.NumberDecimalSeparator where numberformat is a NumberFormatInfo variable.

regards and thanks in anticipation.

Different default format when using string interpolation

Since the 2.1.0 update using string interpolation to get the string representation of a ByteSize uses a different default format. If the default ToString() method is used then the format is set to "0.##" (which is expected in most scenarios) while using string interpolation (such as "{byteSizeValue}") will default the format to null. Having the format set to null will a lot of times produce very large strings as there's no limit on the number of decimals. My suggestion is to always use "0.##" as the default just how it was prior to version 2.1.0.

Partial bytes do not exist

I'm trying to use this library to keep my code a bit more readable.

If I do this:

var memoryBuffer = MemoryPool<byte>.Shared.Rent((int) ByteSize.FromKibiBytes(128).Bytes);

I have to cast .Bytes to an integer, because the Bytes property is a double.
I can understand returning a double for almost anything. But seeing as "Bytes" in particular, is really the lowest addressable data type, there is no way to have "partial bytes". You would never be addressing "1.2 bytes".

I would therefore suggest changing the "Bytes" type to an uint or ulong (I really don't see negative bytes as a thing either, but I could be wrong there).

Add a ByteSpeed type which combines ByteSize & TimeSpan

Example:

ByteSize size = ByteSize.FromBytes(1000);
TimeSpan time = TimeSpan.FromSeconds(5);

// use dotnet operator overloading to support basic operations (/, *) for various combinations of:

ByteSpeed speed = (ByteSize) size /  (TimeSpan) time;
TimeSpan   time = (ByteSize) size / (ByteSpeed) speed;
ByteSize   size = (TimeSpan) time * (ByteSpeed) speed;

// ByteSpeed would be a new type

// It would support all the same ToString / Largest operations as ByteSize:
// - LargestWholeNumberValue / given time unit... e.g. second, minute, etc
// - LargestWholeNumberSymbol / given time unit... e.g. second, minute, etc
// with automatic formatting

Mebibytes

The units being used in this project are actually kibibyte, mebibyte, gibibyte etc instead of kilobyte, megabyte, gigabyte (MiB for mebibyte, MB for megabyte) which may cause confusion.
Kilobyte is 1000 bytes (power of 10), but a kibibyte is 1024 bytes (power of 2).

More info on what a kibibyte is:
https://en.wikipedia.org/wiki/Kibibyte

Parsing bits and Bytes

If I ByteSize.Parse("1689.1kb") I get the same value if I ByteSize.Parse("1689.1kB")
One is kilobits the other is kiloBytes, yet ByteSize seems to treat b and B the same.

Also if I ByteSize.Parse("1689.1kib") your round up 13,910,835.2 to 13,910,836, surely this should be 13,910,835?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.