bytesize-rs / bytesize

An utility that easily makes bytes size representation and helps its arithmetic operations.
Apache License 2.0
115 stars 30 forks source link

Display for IEC units #37

Open ctron opened 1 year ago

ctron commented 1 year ago

By default the Display implementation is using SI units (e.g. KB), which looks weird when printing those:

      --http-server-request-limit <http-server-request-limit>
          The overall request limit [env: HTTP_SERVER_REQUEST_LIMIT=] [default: "262.1 KB"]
      --http-server-json-limit <http-server-json-limit>
          The JSON request limit [env: HTTP_SERVER_JSON_LIMIT=] [default: "2.1 MB"]

It would be great if there would be a newtype for defaulting to "binary format" (powers of 2, e.g. KiB).

ctron commented 1 year ago

For example:

#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Default)]
pub struct BinaryByteSize(pub ByteSize);

impl Deref for BinaryByteSize {
    type Target = ByteSize;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for BinaryByteSize {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl Display for BinaryByteSize {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0.to_string_as(true))
    }
}

impl FromStr for BinaryByteSize {
    type Err = <ByteSize as FromStr>::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        ByteSize::from_str(s).map(BinaryByteSize)
    }
}

Turns this into:

      --http-server-request-limit <http-server-request-limit>
          The overall request limit [env: HTTP_SERVER_REQUEST_LIMIT=] [default: "256.0 kiB"]
      --http-server-json-limit <http-server-json-limit>
          The JSON request limit [env: HTTP_SERVER_JSON_LIMIT=] [default: "2.0 MiB"]
MrCroxx commented 1 week ago

Planned with 2.0. 🫡