Skip to content

Commit af7b10f

Browse files
authored
Merge pull request #892 from ddunn2/byteCount
2 parents f0f1209 + 7d60a67 commit af7b10f

File tree

2 files changed

+773
-19
lines changed

2 files changed

+773
-19
lines changed

Foundation/NSByteCountFormatter.swift

Lines changed: 335 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ extension ByteCountFormatter {
2828
// Can use any unit in showing the number.
2929
public static let useAll = Units(rawValue: 0x0FFFF)
3030
}
31-
31+
3232
public enum CountStyle : Int {
3333

3434
// Specifies display of file or storage byte counts. The actual behavior for this is platform-specific; on OS X 10.8, this uses the decimal style, but that may change over time.
@@ -50,45 +50,362 @@ open class ByteCountFormatter : Formatter {
5050
NSUnimplemented()
5151
}
5252

53-
/* Shortcut for converting a byte count into a string without creating an NSByteCountFormatter and an NSNumber. If you need to specify options other than countStyle, create an instance of NSByteCountFormatter first.
54-
*/
55-
open class func string(fromByteCount byteCount: Int64, countStyle: ByteCountFormatter.CountStyle) -> String { NSUnimplemented() }
56-
57-
/* Convenience method on string(for:):. Convert a byte count into a string without creating an NSNumber.
58-
*/
59-
open func string(fromByteCount byteCount: Int64) -> String { NSUnimplemented() }
60-
6153
/* Specify the units that can be used in the output. If NSByteCountFormatterUseDefault, uses platform-appropriate settings; otherwise will only use the specified units. This is the default value. Note that ZB and YB cannot be covered by the range of possible values, but you can still choose to use these units to get fractional display ("0.0035 ZB" for instance).
62-
*/
54+
*/
6355
open var allowedUnits: Units = .useDefault
6456

6557
/* Specify how the count is displayed by indicating the number of bytes to be used for kilobyte. The default setting is NSByteCountFormatterFileCount, which is the system specific value for file and storage sizes.
66-
*/
58+
*/
6759
open var countStyle: CountStyle = .file
6860

6961
/* Choose whether to allow more natural display of some values, such as zero, where it may be displayed as "Zero KB," ignoring all other flags or options (with the exception of NSByteCountFormatterUseBytes, which would generate "Zero bytes"). The result is appropriate for standalone output. Default value is YES. Special handling of certain values such as zero is especially important in some languages, so it's highly recommended that this property be left in its default state.
70-
*/
62+
*/
7163
open var allowsNonnumericFormatting: Bool = true
7264

7365
/* Choose whether to include the number or the units in the resulting formatted string. (For example, instead of 723 KB, returns "723" or "KB".) You can call the API twice to get both parts, separately. But note that putting them together yourself via string concatenation may be wrong for some locales; so use this functionality with care. Both of these values are YES by default. Setting both to NO will unsurprisingly result in an empty string.
74-
*/
66+
*/
7567
open var includesUnit: Bool = true
7668
open var includesCount: Bool = true
7769

7870
/* Choose whether to parenthetically (localized as appropriate) display the actual number of bytes as well, for instance "723 KB (722,842 bytes)". This will happen only if needed, that is, the first part is already not showing the exact byte count. If includesUnit or includesCount are NO, then this setting has no effect. Default value is NO.
79-
*/
71+
*/
8072
open var includesActualByteCount: Bool = false
8173

8274
/* Choose the display style. The "adaptive" algorithm is platform specific and uses a different number of fraction digits based on the magnitude (in 10.8: 0 fraction digits for bytes and KB; 1 fraction digits for MB; 2 for GB and above). Otherwise the result always tries to show at least three significant digits, introducing fraction digits as necessary. Default is YES.
83-
*/
75+
*/
8476
open var isAdaptive: Bool = true
8577

8678
/* Choose whether to zero pad fraction digits so a consistent number of fraction digits are displayed, causing updating displays to remain more stable. For instance, if the adaptive algorithm is used, this option formats 1.19 and 1.2 GB as "1.19 GB" and "1.20 GB" respectively, while without the option the latter would be displayed as "1.2 GB". Default value is NO.
87-
*/
79+
*/
8880
open var zeroPadsFractionDigits: Bool = false
8981

9082
/* Specify the formatting context for the formatted string. Default is NSFormattingContextUnknown.
91-
*/
83+
*/
9284
open var formattingContext: Context = .unknown
93-
}
85+
86+
/* A variable to store the actual bytes passed into the methods. This value is used if the includesActualByteCount property is set.
87+
*/
88+
private var actualBytes: String = ""
89+
90+
/* Create an instance of NumberFormatter for use in various methods
91+
*/
92+
private let numberFormatter = NumberFormatter()
93+
94+
/* Shortcut for converting a byte count into a string without creating an NSByteCountFormatter and an NSNumber. If you need to specify options other than countStyle, create an instance of NSByteCountFormatter first.
95+
*/
96+
open class func string(fromByteCount byteCount: Int64, countStyle: ByteCountFormatter.CountStyle) -> String {
97+
let formatter = ByteCountFormatter()
98+
formatter.countStyle = countStyle
99+
return formatter.string(fromByteCount: byteCount)
100+
}
101+
102+
/* Convenience method on string(for:):. Convert a byte count into a string without creating an NSNumber.
103+
*/
104+
open func string(fromByteCount byteCount: Int64) -> String {
105+
//Convert actual bytes to a formatted string for use later
106+
numberFormatter.numberStyle = .decimal
107+
actualBytes = numberFormatter.string(from: NSNumber(value: byteCount))!
94108

109+
if countStyle == .decimal || countStyle == .file {
110+
return convertValue(fromByteCount: byteCount, for: decimalByteSize)
111+
} else {
112+
return convertValue(fromByteCount: byteCount, for: binaryByteSize)
113+
}
114+
}
115+
116+
/* Convenience method on string(for:):. Convert a byte count into a string without creating an NSNumber.
117+
*/
118+
open override func string(for obj: Any?) -> String? {
119+
guard let value = obj as? Double else {
120+
return nil
121+
}
122+
123+
return string(fromByteCount: Int64(value))
124+
}
125+
126+
/* This method accepts a byteCount and a byteSize value. Checks to see what range the byteCount falls into and then converts to the units determined by that range. The range to be used is decided by the byteSize parameter. The conversion is done by making use of the divide method.
127+
*/
128+
private func convertValue(fromByteCount byteCount: Int64, for byteSize: [Unit: Double]) -> String {
129+
let byte = Double(byteCount)
130+
if byte == 0, allowsNonnumericFormatting, allowedUnits == .useDefault, includesUnit, includesCount {
131+
return partsToIncludeFor(value: "Zero", unit: Unit.KB)
132+
} else if byte == 1 || byte == -1 {
133+
if allowedUnits.contains(.useAll) || allowedUnits == .useDefault {
134+
return formatNumberFor(bytes: byte, unit: Unit.byte)
135+
} else {
136+
return valueToUseFor(byteCount: byte, unit: allowedUnits)
137+
}
138+
} else if byte < byteSize[Unit.KB]! && byte > -byteSize[Unit.KB]!{
139+
if allowedUnits.contains(.useAll) || allowedUnits == .useDefault {
140+
return formatNumberFor(bytes: byte, unit: Unit.bytes)
141+
} else {
142+
return valueToUseFor(byteCount: byte, unit: allowedUnits)
143+
}
144+
} else if byte < byteSize[Unit.MB]! && byte > -byteSize[Unit.MB]! {
145+
if allowedUnits.contains(.useAll) || allowedUnits == .useDefault {
146+
return divide(byte, by: byteSize, for: .KB)
147+
}
148+
return valueToUseFor(byteCount: byte, unit: allowedUnits)
149+
150+
} else if byte < byteSize[Unit.GB]! && byte > -byteSize[Unit.GB]! {
151+
if allowedUnits.contains(.useAll) || allowedUnits == .useDefault {
152+
return divide(byte, by: byteSize, for: .MB)
153+
}
154+
return valueToUseFor(byteCount: byte, unit: allowedUnits)
155+
156+
} else if byte < byteSize[Unit.TB]! && byte > -byteSize[Unit.TB]! {
157+
if allowedUnits.contains(.useAll) || allowedUnits == .useDefault {
158+
return divide(byte, by: byteSize, for: .GB)
159+
}
160+
return valueToUseFor(byteCount: byte, unit: allowedUnits)
161+
162+
} else if byte < byteSize[Unit.PB]! && byte > -byteSize[Unit.PB]! {
163+
if allowedUnits.contains(.useAll) || allowedUnits == .useDefault {
164+
return divide(byte, by: byteSize, for: .TB)
165+
}
166+
return valueToUseFor(byteCount: byte, unit: allowedUnits)
167+
168+
} else if byte < byteSize[Unit.EB]! && byte > -byteSize[Unit.EB]! {
169+
if allowedUnits.contains(.useAll) || allowedUnits == .useDefault {
170+
return divide(byte, by: byteSize, for: .PB)
171+
}
172+
return valueToUseFor(byteCount: byte, unit: allowedUnits)
173+
174+
} else {
175+
if allowedUnits.contains(.useAll) || allowedUnits == .useDefault {
176+
return divide(byte, by: byteSize, for: .EB)
177+
}
178+
return valueToUseFor(byteCount: byte, unit: allowedUnits)
179+
}
180+
}
181+
182+
/*
183+
A helper method to deal with the Option Set, caters for setting an individual value or passing in an array of values.
184+
Returns the correct value based on the units that are allowed for use.
185+
*/
186+
private func valueToUseFor(byteCount: Double, unit: ByteCountFormatter.Units) -> String {
187+
var byteSize: [Unit: Double]
188+
189+
//Check to see whether we're using 1000bytes per KB or 1024 per KB
190+
if countStyle == .decimal || countStyle == .file {
191+
byteSize = decimalByteSize
192+
} else {
193+
byteSize = binaryByteSize
194+
}
195+
if byteCount == 0, allowsNonnumericFormatting, includesCount, includesUnit {
196+
return partsToIncludeFor(value: "Zero", unit: Unit.KB)
197+
}
198+
//Handles the cases where allowedUnits is set to a specific individual value. e.g. allowedUnits = .useTB
199+
switch allowedUnits {
200+
case Units.useBytes: return partsToIncludeFor(value: actualBytes, unit: Unit.bytes)
201+
case Units.useKB: return divide(byteCount, by: byteSize, for: .KB)
202+
case Units.useMB: return divide(byteCount, by: byteSize, for: .MB)
203+
case Units.useGB: return divide(byteCount, by: byteSize, for: .GB)
204+
case Units.useTB: return divide(byteCount, by: byteSize, for: .TB)
205+
case Units.usePB: return divide(byteCount, by: byteSize, for: .PB)
206+
case Units.useEB: return divide(byteCount, by: byteSize, for: .EB)
207+
case Units.useZB: return divide(byteCount, by: byteSize, for: .ZB)
208+
case Units.useYBOrHigher: return divide(byteCount, by: byteSize, for: .YB)
209+
default: break
210+
}
211+
212+
//Initialise an array that will hold all the units we can use
213+
var unitsToUse: [Unit] = []
214+
215+
//Based on what units have been selected for use, build an array out of them.
216+
if unit.contains(.useBytes) && byteCount == 1 {
217+
unitsToUse.append(.byte)
218+
} else if unit.contains(.useBytes) {
219+
unitsToUse.append(.bytes)
220+
}
221+
if unit.contains(.useKB) {
222+
unitsToUse.append(.KB)
223+
}
224+
if unit.contains(.useMB) {
225+
unitsToUse.append(.MB)
226+
}
227+
if unit.contains(.useGB) {
228+
unitsToUse.append(.GB)
229+
}
230+
if unit.contains(.useTB) {
231+
unitsToUse.append(.TB)
232+
}
233+
if unit.contains(.usePB) {
234+
unitsToUse.append(.PB)
235+
}
236+
if unit.contains(.useEB) {
237+
unitsToUse.append(.EB)
238+
}
239+
if unit.contains(.useZB) {
240+
unitsToUse.append(.ZB)
241+
}
242+
if unit.contains(.useYBOrHigher) {
243+
unitsToUse.append(.YB)
244+
}
245+
246+
247+
var counter = 0
248+
for _ in unitsToUse {
249+
counter += 1
250+
if counter > unitsToUse.count - 1 {
251+
counter = unitsToUse.count - 1
252+
}
253+
/*
254+
The units are appended to the array in asceding order, so if the value for byteCount is smaller than the byteSize value of the next unit
255+
in the Array we use the previous unit. e.g. if byteCount = 1000, and AllowedUnits = [.useKB, .useGB] check to see if byteCount is smaller
256+
than a GB in bytes(pow(1000, 3)) and if so, we'll use the previous unit which is KB in this case.
257+
*/
258+
if byteCount < byteSize[unitsToUse[counter]]! {
259+
return divide(byteCount, by: byteSize, for: unitsToUse[counter - 1])
260+
}
261+
}
262+
return divide(byteCount, by: byteSize, for: unitsToUse[counter])
263+
}
264+
265+
// Coverts the number of bytes to the correct value given a specified unit, then passes the value and unit to formattedValue
266+
private func divide(_ bytes: Double, by byteSize: [Unit: Double], for unit: Unit) -> String {
267+
guard let byteSizeUnit = byteSize[unit] else {
268+
fatalError("Cannot find value \(unit)")
269+
}
270+
let result = bytes/byteSizeUnit
271+
return formatNumberFor(bytes: result, unit: unit)
272+
}
273+
274+
//Formats the byte value using the NumberFormatter class based on set properties and the unit passed in as a parameter.
275+
private func formatNumberFor(bytes: Double, unit: Unit) -> String {
276+
277+
switch (zeroPadsFractionDigits, isAdaptive) {
278+
//zeroPadsFractionDigits is true, isAdaptive is true
279+
case (true, true):
280+
switch unit {
281+
case .bytes, .byte, .KB:
282+
let result = String(format: "%.0f", bytes)
283+
return partsToIncludeFor(value: result, unit: unit)
284+
case .MB:
285+
let result = String(format: "%.1f", bytes)
286+
return partsToIncludeFor(value: result, unit: unit)
287+
default:
288+
let result = String(format: "%.2f", bytes)
289+
return partsToIncludeFor(value: result, unit: unit)
290+
}
291+
//zeroPadsFractionDigits is true, isAdaptive is false
292+
case (true, false):
293+
if unit == .byte || unit == .bytes {
294+
numberFormatter.maximumFractionDigits = 0
295+
let result = numberFormatter.string(from: NSNumber(value: bytes))
296+
return partsToIncludeFor(value: result!, unit: unit)
297+
} else {
298+
if lengthOfInt(number: Int(bytes)) == 3 {
299+
numberFormatter.maximumFractionDigits = 1
300+
} else {
301+
numberFormatter.usesSignificantDigits = true
302+
numberFormatter.maximumSignificantDigits = 3
303+
numberFormatter.minimumSignificantDigits = 3
304+
}
305+
let result = numberFormatter.string(from: NSNumber(value: bytes))
306+
return partsToIncludeFor(value: result!, unit: unit)
307+
}
308+
//zeroPadsFractionDigits is false, isAdaptive is true
309+
case (false, true):
310+
switch unit {
311+
case .bytes, .byte, .KB:
312+
numberFormatter.minimumFractionDigits = 0
313+
numberFormatter.maximumFractionDigits = 0
314+
let result = numberFormatter.string(from: NSNumber(value: bytes))
315+
return partsToIncludeFor(value: result!, unit: unit)
316+
case .MB:
317+
numberFormatter.minimumFractionDigits = 0
318+
numberFormatter.maximumFractionDigits = 1
319+
let result = numberFormatter.string(from: NSNumber(value: bytes))
320+
return partsToIncludeFor(value: result!, unit: unit)
321+
default:
322+
let result: String
323+
//Need to add in an extra case for negative numbers as NumberFormatter formats 0.005 to 0 rather than
324+
// 0.01
325+
if bytes < 0 {
326+
let negBytes = round(bytes * 100) / 100
327+
result = numberFormatter.string(from: NSNumber(value: negBytes))!
328+
} else {
329+
numberFormatter.minimumFractionDigits = 0
330+
numberFormatter.maximumFractionDigits = 2
331+
result = numberFormatter.string(from: NSNumber(value: bytes))!
332+
}
333+
334+
335+
return partsToIncludeFor(value: result, unit: unit)
336+
}
337+
//zeroPadsFractionDigits is false, isAdaptive is false
338+
case (false, false):
339+
if unit == .byte || unit == .bytes {
340+
numberFormatter.minimumFractionDigits = 0
341+
numberFormatter.maximumFractionDigits = 0
342+
let result = numberFormatter.string(from: NSNumber(value: bytes))
343+
return partsToIncludeFor(value: result!, unit: unit)
344+
} else {
345+
if lengthOfInt(number: Int(bytes)) > 3 {
346+
numberFormatter.maximumFractionDigits = 0
347+
} else {
348+
numberFormatter.usesSignificantDigits = true
349+
numberFormatter.maximumSignificantDigits = 3
350+
}
351+
let result = numberFormatter.string(from: NSNumber(value: bytes))
352+
return partsToIncludeFor(value: result!, unit: unit)
353+
}
354+
}
355+
}
356+
357+
// A helper method to return the length of an int
358+
private func lengthOfInt(number: Int) -> Int {
359+
var num = abs(number)
360+
var length: [Int] = []
361+
362+
while num > 0 {
363+
let remainder = num % 10
364+
length.append(remainder)
365+
num /= 10
366+
}
367+
return length.count
368+
}
369+
370+
// Returns the correct string based on the includesValue and includesUnit properties
371+
private func partsToIncludeFor(value: String, unit: Unit) -> String {
372+
if includesActualByteCount, includesUnit, includesCount {
373+
switch unit {
374+
case .byte, .bytes: return "\(value) \(unit)"
375+
default: return "\(value) \(unit) (\(actualBytes) \(Unit.bytes))"
376+
}
377+
} else if includesCount, includesUnit {
378+
return "\(value) \(unit)"
379+
} else if includesCount, !includesUnit {
380+
if value == "Zero", allowedUnits == .useDefault {
381+
return "0"
382+
} else {
383+
return value
384+
}
385+
} else if !includesCount, includesUnit {
386+
return "\(unit)"
387+
} else {
388+
return ""
389+
}
390+
}
391+
392+
//Enum containing available byte units
393+
private enum Unit: String {
394+
case byte
395+
case bytes
396+
case KB
397+
case MB
398+
case GB
399+
case TB
400+
case PB
401+
case EB
402+
case ZB
403+
case YB
404+
}
405+
// Maps each unit to it's corresponding value in bytes for decimal
406+
private let decimalByteSize: [Unit: Double] = [.byte: 1, .bytes: 1, .KB: 1000, .MB: pow(1000, 2), .GB: pow(1000, 3), .TB: pow(1000, 4), .PB: pow(1000, 5), .EB: pow(1000, 6), .ZB: pow(1000, 7), .YB: pow(1000, 8)]
407+
408+
// Maps each unit to it's corresponding value in bytes for binary
409+
private let binaryByteSize: [Unit: Double] = [.byte: 1, .bytes: 1, .KB: 1024, .MB: pow(1024, 2), .GB: pow(1024, 3), .TB: pow(1024, 4), .PB: pow(1024, 5), .EB: pow(1024, 6), .ZB: pow(1024, 7), .YB: pow(1024, 8)]
410+
411+
}

0 commit comments

Comments
 (0)