Este é um porto de bytesize para Delphi/FreePascal.
TByteSize é um "registro" de utilitário que facilita a representação do tamanho do bytes no código, removendo a ambiguidade do valor que está sendo representado.
TByteSize é para bytes qual System.TimeSpan.TTimeSpan é tempo.
Este projeto foi criado usando o Delphi 10 Seattle Atualize 1, mas deve compilar em qualquer versão Delphi de 2009 e FreePasCal 3.0.0 para cima.
Sem TByteSize :
const
MaxFileSizeMBs = 1.5 ;
// I need it in KBs!
var
kilobytes: Double;
begin
kilobytes := MaxFileSizeMBs * 1024 ;
end ; Com ByteSize :
var
MaxFileSize: TByteSize;
begin
MaxFileSize := TByteSize.FromMegaBytes( 1.5 );
end ;
// I have it in KBs!
MaxFileSize.KiloBytes; TByteSize se comporta como qualquer outro record apoiado por um valor numérico.
// Add
var
monthlyUsage, currentUsage, total, delta, : TByteSize;
begin
monthlyUsage := TByteSize.FromGigaBytes( 10 );
currentUsage := TByteSize.FromMegaBytes( 512 );
total := monthlyUsage + currentUsage;
total.Add(ByteSize.FromKiloBytes( 10 ));
total.AddGigaBytes( 10 );
// Subtract
delta := total.Subtract(TByteSize.FromKiloBytes( 10 ));
delta := delta - TByteSize.FromGigaBytes( 100 );
delta := delta.AddMegaBytes(- 100 );
end ; Você pode criar um "objeto" ByteSize a partir de bits , bytes , kilobytes , megabytes , gigabytes e terabytes .
TByteSize.Create( 1.5 ); // Constructor takes in bytes
// Static Constructors
TByteSize.FromBits( 10 ); // Bits are whole numbers only
TByteSize.FromBytes( 1.5 ); // Same as constructor
TByteSize.FromKiloBytes( 1.5 );
TByteSize.FromMegaBytes( 1.5 );
TByteSize.FromGigaBytes( 1.5 );
TByteSize.FromTeraBytes( 1.5 );
TByteSize.FromPetaBytes( 1.5 );
Um "objeto" TByteSize contém representações em bits , bytes , kilobytes , megabytes , gigabytes , terabytes e petabytes .
var
maxFileSize: TByteSize;
begin
maxFileSize := TByteSize.FromKiloBytes( 10 );
maxFileSize.Bits; // 81920
maxFileSize.Bytes; // 10240
maxFileSize.KiloBytes; // 10
maxFileSize.MegaBytes; // 0.009765625
maxFileSize.GigaBytes; // 9.53674316e-6
maxFileSize.TeraBytes; // 9.31322575e-9
end ; Um "objeto" TByteSize também contém duas propriedades que representam o maior símbolo e valor de prefixo métrico.
var
maxFileSize: TByteSize;
begin
maxFileSize := TByteSize.FromKiloBytes( 10 );
maxFileSize.LargestWholeNumberSymbol; // "KB"
maxFileSize.LargestWholeNumberValue; // 10
end ; Todas as operações de análise de string ( String to TByteSize ) estão localizadas para usar o número decimal do separador do localidade atualmente definida.
TByteSize vem com um método útil ToString que usa o maior prefixo métrico cujo valor é maior ou igual a 1.
TByteSize.FromBits( 7 ).ToString; // 7 b
TByteSize.FromBits( 8 ).ToString; // 1 B
TByteSize.FromKiloBytes(. 5 ).ToString; // 512 B
TByteSize.FromKiloBytes( 1000 ).ToString; // 1000 KB
TByteSize.FromKiloBytes( 1024 ).ToString; // 1 MB
TByteSize.FromGigabytes(. 5 ).ToString; // 512 MB
TByteSize.FromGigabytes( 1024 ).ToString; // 1 TB O método ToString aceita um único parâmetro string para formatar a saída. O formatador pode conter o símbolo do valor a ser exibido: b , B , KB , MB , GB , TB , PB . O formatador usa o método FormatFloat embutido. O formato do número padrão é #.## que arredonda o número para dois lugares decimais.
Você pode incluir formatos de símbolo e número.
var
b: TByteSize;
begin
b := TByteSize.FromKiloBytes( 10.505 );
// Default number format is #.##
b.ToString( ' KB ' ); // 10.52 KB
b.ToString( ' MB ' ); // .01 MB
b.ToString( ' b ' ); // 86057 b
// Default symbol is the largest metric prefix value >= 1
b.ToString( ' #.# ' ); // 10.5 KB
// All valid values of double.ToString(string format) are acceptable
b.ToString( ' 0.0000 ' ); // 10.5050 KB
b.ToString( ' 000.00 ' ); // 010.51 KB
// You can include number format and symbols
b.ToString( ' #.#### MB ' ); // .0103 MB
b.ToString( ' 0.00 GB ' ); // 0 GB
b.ToString( ' #.## B ' ); // 10757.12 B
end ; ByteSize possui um método Parse e TryParse .
Como outros métodos TryParse , ByteSize.TryParse Retorna o valor boolean indicando se a análise foi ou não bem -sucedida. Se o valor for analisado, ele será emitido para o parâmetro out fornecido.
var
output: TByteSize;
begin
TByteSize.TryParse( ' 1.5mb ' , output);
// Invalid
TByteSize.Parse( ' 1.5 b ' ); // Can't have partial bits
// Valid
TByteSize.Parse( ' 5b ' );
TByteSize.Parse( ' 1.55B ' );
TByteSize.Parse( ' 1.55KB ' );
TByteSize.Parse( ' 1.55 kB ' ); // Spaces are trimmed
TByteSize.Parse( ' 1.55 kb ' );
TByteSize.Parse( ' 1.55 MB ' );
TByteSize.Parse( ' 1.55 mB ' );
TByteSize.Parse( ' 1.55 mb ' );
TByteSize.Parse( ' 1.55 GB ' );
TByteSize.Parse( ' 1.55 gB ' );
TByteSize.Parse( ' 1.55 gb ' );
TByteSize.Parse( ' 1.55 TB ' );
TByteSize.Parse( ' 1.55 tB ' );
TByteSize.Parse( ' 1.55 tb ' );
TByteSize.Parse( ' 1,55 kb ' ); // de-DE culture
end ;Testes de unidade ###
Unit Tests can be found in ByteSizeLib.Tests Folder.
The unit tests makes use of DUnitX and TestInsight.
###Licença
Este "software" está licenciado sob MIT License (MIT) .
1MhFfW7tDuEHQSgie65uJcAfJgCNchGeKf0x6c1DC21aeC49A822A4f1E3bf07c623C2C1978a98345367-40###Conclusão
Agradecimentos especiais a Omar Khudeira por esta biblioteca incrível. (Graças aos desenvolvedores da DunitX Testing Framework e TestInsight para fazer ferramentas que simplificam o teste de unidade.