2019-12-05 11:51:11 +00:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
2021-09-22 21:10:15 +01:00
|
|
|
export enum Memory {
|
2019-12-05 11:51:11 +00:00
|
|
|
Bytes = 1e0,
|
|
|
|
KB = 1e3,
|
|
|
|
MB = 1e6,
|
|
|
|
GB = 1e9,
|
|
|
|
TB = 1e12,
|
|
|
|
PB = 1e15,
|
|
|
|
}
|
|
|
|
|
2019-12-12 16:25:38 +00:00
|
|
|
export enum Dimensions {
|
2021-11-24 16:50:53 +00:00
|
|
|
Bytes = 'B',
|
2019-12-05 11:51:11 +00:00
|
|
|
KB = 'KB',
|
|
|
|
MB = 'MB',
|
|
|
|
GB = 'GB',
|
|
|
|
TB = 'TB',
|
|
|
|
PB = 'PB',
|
|
|
|
}
|
|
|
|
|
|
|
|
export class Size {
|
2019-12-12 16:25:38 +00:00
|
|
|
private readonly precision: number;
|
2019-12-05 11:51:11 +00:00
|
|
|
public readonly bytes: number;
|
|
|
|
public readonly formattedBytes: string;
|
|
|
|
public readonly label: Dimensions;
|
|
|
|
|
2021-08-02 19:17:49 +01:00
|
|
|
public constructor(bytes: number, precision = 0) {
|
2019-12-05 11:51:11 +00:00
|
|
|
const _bytes = Math.ceil(bytes);
|
|
|
|
this.bytes = bytes;
|
2019-12-12 16:25:38 +00:00
|
|
|
this.precision = precision;
|
2019-12-05 11:51:11 +00:00
|
|
|
|
|
|
|
switch (true) {
|
2021-08-02 19:17:49 +01:00
|
|
|
case _bytes === 0:
|
|
|
|
this.formattedBytes = (bytes / Memory.Bytes).toFixed(this.precision);
|
|
|
|
this.label = Dimensions.Bytes;
|
|
|
|
break;
|
|
|
|
case _bytes < Memory.MB:
|
|
|
|
this.formattedBytes = (bytes / Memory.KB).toFixed(this.precision);
|
|
|
|
this.label = Dimensions.KB;
|
|
|
|
break;
|
|
|
|
case _bytes < Memory.GB:
|
|
|
|
this.formattedBytes = (bytes / Memory.MB).toFixed(this.precision);
|
|
|
|
this.label = Dimensions.MB;
|
|
|
|
break;
|
|
|
|
case _bytes < Memory.TB:
|
|
|
|
this.formattedBytes = (bytes / Memory.GB).toFixed(this.precision);
|
|
|
|
this.label = Dimensions.GB;
|
|
|
|
break;
|
|
|
|
case _bytes < Memory.PB:
|
|
|
|
this.formattedBytes = (bytes / Memory.TB).toFixed(this.precision);
|
|
|
|
this.label = Dimensions.TB;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
this.formattedBytes = (bytes / Memory.PB).toFixed(this.precision);
|
|
|
|
this.label = Dimensions.PB;
|
2019-12-05 11:51:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|