ente/lib/utils/data_util.dart

55 lines
1.5 KiB
Dart
Raw Normal View History

2021-06-28 12:54:27 +00:00
import 'dart:math';
2022-09-20 12:48:15 +00:00
final storageUnits = ["bytes", "KB", "MB", "GB"];
2021-03-02 06:35:10 +00:00
String convertBytesToReadableFormat(int bytes) {
int storageUnitIndex = 0;
2022-09-20 12:48:15 +00:00
while (bytes >= 1024 && storageUnitIndex < storageUnits.length - 1) {
2021-03-02 06:35:10 +00:00
storageUnitIndex++;
bytes = (bytes / 1024).round();
}
2022-09-20 12:48:15 +00:00
return bytes.toString() + " " + storageUnits[storageUnitIndex];
2021-03-02 06:35:10 +00:00
}
2021-06-28 12:54:27 +00:00
String formatBytes(int bytes, [int decimals = 2]) {
2021-07-27 14:19:58 +00:00
if (bytes == 0) return '0 bytes';
const k = 1024;
2022-08-29 14:43:31 +00:00
final int dm = decimals < 0 ? 0 : decimals;
final int i = (log(bytes) / log(k)).floor();
2022-09-20 12:48:15 +00:00
return ((bytes / pow(k, i)).toStringAsFixed(dm)) + ' ' + storageUnits[i];
2021-07-27 14:19:58 +00:00
}
2022-10-26 11:06:42 +00:00
//shows 1st decimal only if less than 10GB & omits decimal if decimal is 0
num roundBytesUsedToGBs(int usedBytes, int freeSpace) {
const tenGBinBytes = 10737418240;
num bytesInGB = convertBytesToGBs(usedBytes);
if ((usedBytes >= tenGBinBytes && freeSpace >= tenGBinBytes) ||
bytesInGB % 1 == 0) {
2022-10-26 11:06:42 +00:00
bytesInGB = bytesInGB.truncate();
}
return bytesInGB;
}
2022-10-26 12:21:16 +00:00
//Eg: 0.3 GB, 11.0 GB, 532.3 GB
2022-10-26 11:35:34 +00:00
num convertBytesToGBs(int bytes) {
return num.parse((bytes / (pow(1024, 3))).toStringAsFixed(1));
}
2023-02-15 16:47:40 +00:00
int convertBytesToAbsoluteGBs(int bytes) {
return (bytes / pow(1024, 3)).round();
}
2022-10-19 04:49:06 +00:00
int convertBytesToMBs(int bytes) {
return (bytes / pow(1024, 2)).round();
}
2022-12-29 13:40:36 +00:00
//Eg: 1TB, 1.3TB, 4.9TB, 3TB
roundGBsToTBs(sizeInGBs) {
final num sizeInTBs = num.parse((sizeInGBs / 1000).toStringAsFixed(1));
if (sizeInTBs % 1 == 0) {
return sizeInTBs.truncate();
} else {
return sizeInTBs;
}
}