1
1
// Helper functions for validator and sanitizer.
2
2
3
+ import 'dart:math' ;
4
+
5
+ import 'package:intl/intl.dart' ;
6
+
3
7
T shift <T >(List <T > l) {
4
8
if (l.isNotEmpty) {
5
9
final first = l.first;
@@ -26,14 +30,18 @@ String fileExtensionFromPath(String path) {
26
30
}
27
31
28
32
/// Helper function to format bytes into a human-readable string (e.g., KB, MB, GB).
29
- String formatBytes (int bytes) {
30
- const suffixes = ['B' , 'KB' , 'MB' , 'GB' , 'TB' ];
31
- var i = 0 ;
32
- double size = bytes.toDouble ();
33
- while (size > 1024 && i < suffixes.length - 1 ) {
34
- size /= 1024 ;
35
- i++ ;
36
- }
37
- // Truncate to 1 decimal place
38
- return '${size .toStringAsFixed (1 )}${suffixes [i ]}' ;
33
+ String formatBytes (int bytes, {bool base1024 = true }) {
34
+ double log10 (num x) => log (x) / ln10;
35
+
36
+ if (bytes <= 0 ) return "0 B" ;
37
+
38
+ final base = base1024 ? 1024 : 1000 ;
39
+ final units = base1024
40
+ ? ["B" , "KiB" , "MiB" , "GiB" , "TiB" ]
41
+ : ["B" , "kB" , "MB" , "GB" , "TB" ];
42
+
43
+ int digitGroups = (log10 (bytes) / log10 (base )).floor ();
44
+ double size = bytes / pow (base , digitGroups);
45
+
46
+ return "${NumberFormat ("#,##0.#" ).format (size )} ${units [digitGroups ]}" ;
39
47
}
0 commit comments