From 2942d2419f846d34b5d1c234dbb6ff19158cf5cb Mon Sep 17 00:00:00 2001 From: merkrafter Date: Mon, 1 Nov 2021 21:15:00 +0100 Subject: [PATCH] Introduce enum for byte size units --- src/bin/hexyl.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/bin/hexyl.rs b/src/bin/hexyl.rs index 55f072c..2fea1df 100644 --- a/src/bin/hexyl.rs +++ b/src/bin/hexyl.rs @@ -4,6 +4,7 @@ extern crate clap; use std::convert::TryFrom; use std::fs::File; use std::io::{self, prelude::*, SeekFrom}; +use std::num::NonZeroI64; use clap::{App, AppSettings, Arg}; @@ -320,6 +321,42 @@ impl Into for PositiveI64 { } } +enum Unit { + Byte, + Kilobyte, + Megabyte, + Gigabyte, + Terabyte, + Kibibyte, + Mebibyte, + Gibibyte, + Tebibyte, + /// a customizable amount of bytes + Block { + custom_size: Option, + }, +} + +impl Unit { + const fn get_multiplier(self) -> i64 { + match self { + Self::Byte => 1, + Self::Kilobyte => 1000i64.pow(1), + Self::Megabyte => 1000i64.pow(2), + Self::Gigabyte => 1000i64.pow(3), + Self::Terabyte => 1000i64.pow(4), + Self::Kibibyte => 1024i64.pow(1), + Self::Mebibyte => 1024i64.pow(2), + Self::Gibibyte => 1024i64.pow(3), + Self::Tebibyte => 1024i64.pow(4), + Self::Block { + custom_size: Some(size), + } => size.get(), + Self::Block { custom_size: None } => DEFAULT_BLOCK_SIZE, + } + } +} + const HEX_PREFIX: &str = "0x"; #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] @@ -472,6 +509,20 @@ fn parse_byte_offset(n: &str, block_size: PositiveI64) -> Result