Skip to content

Commit 7726f57

Browse files
David DunnDavid Dunn
authored andcommitted
Initial implementation of ByteCountFormatter
1 parent 0cbb322 commit 7726f57

File tree

2 files changed

+365
-19
lines changed

2 files changed

+365
-19
lines changed

Foundation/NSByteCountFormatter.swift

Lines changed: 231 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -47,48 +47,261 @@ open class ByteCountFormatter : Formatter {
4747
}
4848

4949
public required init?(coder: NSCoder) {
50-
NSUnimplemented()
50+
super.init(coder: coder)
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+
if includesActualByteCount {
107+
numberFormatter.numberStyle = .decimal
108+
actualBytes = numberFormatter.string(from: NSNumber(value: byteCount))!
109+
}
110+
111+
if allowedUnits != .useDefault && allowedUnits != .useAll {
112+
if countStyle == .file || countStyle == .decimal {
113+
return unitsToUseFor(byteCount: byteCount, byteSize: decimalByteSize)
114+
} else {
115+
return unitsToUseFor(byteCount: byteCount, byteSize: binaryByteSize)
116+
}
117+
} else if countStyle == .decimal || countStyle == .file {
118+
return convertValue(fromByteCount: byteCount, for: decimalByteSize)
119+
} else {
120+
return convertValue(fromByteCount: byteCount, for: binaryByteSize)
121+
}
122+
}
123+
124+
/* Convenience method on string(for:):. Convert a byte count into a string without creating an NSNumber.
125+
*/
126+
open override func string(for obj: Any?) -> String? {
127+
guard let value = obj as? Double else {
128+
return nil
129+
}
130+
131+
return string(fromByteCount: Int64(value))
132+
}
133+
134+
/* If allowedUnits has been set this function will ensure the correct unit is used and conversion is done. The conversion is done by making use of the divide method.
135+
*/
136+
private func unitsToUseFor(byteCount: Int64, byteSize: [Unit: Double]) -> String {
137+
let bytes = Double(byteCount)
138+
139+
if bytes == 0 {
140+
return "Zero \(Unit.KB)"
141+
} else if bytes == 1 {
142+
return formatNumberFor(bytes: bytes, unit: Unit.byte)
143+
}
144+
145+
switch allowedUnits {
146+
case Units.useBytes: return formatNumberFor(bytes: bytes, unit: Unit.bytes)
147+
case Units.useKB: return divide(bytes, by: byteSize, for: .KB)
148+
case Units.useMB: return divide(bytes, by: byteSize, for: .MB)
149+
case Units.useGB: return divide(bytes, by: byteSize, for: .GB)
150+
case Units.useTB: return divide(bytes, by: byteSize, for: .TB)
151+
case Units.usePB: return divide(bytes, by: byteSize, for: .PB)
152+
case Units.useEB: return divide(bytes, by: byteSize, for: .EB)
153+
case Units.useZB: return divide(bytes, by: byteSize, for: .ZB)
154+
default: return divide(bytes, by: byteSize, for: .YB)
155+
156+
}
157+
}
158+
159+
/* 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.
160+
*/
161+
private func convertValue(fromByteCount byteCount: Int64, for byteSize: [Unit: Double]) -> String {
162+
let byte = Double(byteCount)
163+
if byte == 0 && allowsNonnumericFormatting {
164+
return "Zero \(Unit.KB)"
165+
} else if byte == 1 {
166+
return "\(byteCount) \(Unit.byte)"
167+
168+
} else if byte < byteSize[Unit.KB]! && byte > -byteSize[Unit.KB]!{
169+
return formatNumberFor(bytes: byte, unit: Unit.bytes)
170+
171+
} else if byte < byteSize[Unit.MB]! && byte > -byteSize[Unit.MB]! {
172+
return divide(byte, by: byteSize, for: .KB)
173+
174+
} else if byte < byteSize[Unit.GB]! && byte > -byteSize[Unit.GB]! {
175+
return divide(byte, by: byteSize, for: .MB)
176+
177+
} else if byte < byteSize[Unit.TB]! && byte > -byteSize[Unit.TB]! {
178+
return divide(byte, by: byteSize, for: .GB)
179+
180+
} else if byte < byteSize[Unit.PB]! && byte > -byteSize[Unit.PB]! {
181+
return divide(byte, by: byteSize, for: .TB)
182+
183+
} else if byte < byteSize[Unit.EB]! && byte > -byteSize[Unit.EB]! {
184+
return divide(byte, by: byteSize, for: .PB)
185+
186+
} else {
187+
return divide(byte, by: byteSize, for: .EB)
188+
}
189+
}
190+
191+
// Coverts the number of bytes to the correct value given a specified unit, then passes the value and unit to formattedValue
192+
private func divide(_ bytes: Double, by byteSize: [Unit: Double], for unit: Unit) -> String {
193+
guard let byteSizeUnit = byteSize[unit] else {
194+
fatalError("Cannot find value \(unit)")
195+
}
196+
let result = bytes/byteSizeUnit
197+
return formatNumberFor(bytes: result, unit: unit)
198+
}
199+
200+
//Formats the byte value using the NumberFormatter class based on set properties and the unit passed in as a parameter.
201+
private func formatNumberFor(bytes: Double, unit: Unit) -> String {
202+
203+
numberFormatter.numberStyle = .decimal
204+
205+
switch (zeroPadsFractionDigits, isAdaptive) {
206+
//zeroPadsFractionDigits is true, isAdaptive is true
207+
case (true, true):
208+
switch unit {
209+
case .bytes, .byte, .KB:
210+
numberFormatter.minimumFractionDigits = 0
211+
numberFormatter.maximumFractionDigits = 0
212+
let result = numberFormatter.string(from: NSNumber(value: bytes))
213+
return partsToIncludeFor(value: result!, unit: unit)
214+
case .MB:
215+
numberFormatter.minimumFractionDigits = 1
216+
numberFormatter.maximumFractionDigits = 1
217+
let result = numberFormatter.string(from: NSNumber(value: bytes))
218+
return partsToIncludeFor(value: result!, unit: unit)
219+
default:
220+
numberFormatter.minimumFractionDigits = 2
221+
numberFormatter.maximumFractionDigits = 2
222+
let result = numberFormatter.string(from: NSNumber(value: bytes))
223+
return partsToIncludeFor(value: result!, unit: unit)
224+
}
225+
//zeroPadsFractionDigits is true, isAdaptive is false
226+
case (true, false):
227+
if unit == .byte || unit == .bytes {
228+
return partsToIncludeFor(value: "\(bytes)", unit: unit)
229+
} else {
230+
numberFormatter.usesSignificantDigits = true
231+
numberFormatter.minimumSignificantDigits = 3
232+
numberFormatter.maximumSignificantDigits = 3
233+
let result = numberFormatter.string(from: NSNumber(value: bytes))
234+
return partsToIncludeFor(value: result!, unit: unit)
235+
}
236+
//zeroPadsFractionDigits is false, isAdaptive is true
237+
case (false, true):
238+
switch unit {
239+
case .bytes, .byte, .KB:
240+
numberFormatter.minimumFractionDigits = 0
241+
numberFormatter.maximumFractionDigits = 0
242+
let result = numberFormatter.string(from: NSNumber(value: bytes))
243+
return partsToIncludeFor(value: result!, unit: unit)
244+
case .MB:
245+
numberFormatter.minimumFractionDigits = 0
246+
numberFormatter.maximumFractionDigits = 1
247+
let result = numberFormatter.string(from: NSNumber(value: bytes))
248+
return partsToIncludeFor(value: result!, unit: unit)
249+
default:
250+
numberFormatter.minimumFractionDigits = 0
251+
numberFormatter.maximumFractionDigits = 2
252+
let result = numberFormatter.string(from: NSNumber(value: bytes))
253+
return partsToIncludeFor(value: result!, unit: unit)
254+
}
255+
//zeroPadsFractionDigits is false, isAdaptive is false
256+
case (false, false):
257+
if unit == .byte || unit == .bytes {
258+
return partsToIncludeFor(value: "\(bytes)", unit: unit)
259+
} else {
260+
numberFormatter.usesSignificantDigits = true
261+
numberFormatter.minimumSignificantDigits = 3
262+
numberFormatter.maximumSignificantDigits = 3
263+
let result = numberFormatter.string(from: NSNumber(value: bytes))
264+
return partsToIncludeFor(value: result!, unit: unit)
265+
}
266+
}
267+
}
268+
269+
// Returns the correct string based on the includesValue and includesUnit properties
270+
private func partsToIncludeFor(value: String, unit: Unit) -> String {
271+
if includesActualByteCount, includesUnit, includesCount {
272+
switch unit {
273+
case .byte, .bytes: return "\(value) \(unit)"
274+
default: return "\(value) \(unit) (\(actualBytes) \(Unit.bytes))"
275+
}
276+
} else if includesCount, includesUnit {
277+
return "\(value) \(unit)"
278+
} else if includesCount, !includesUnit {
279+
return "\(value)"
280+
} else if !includesCount, includesUnit {
281+
return "\(unit)"
282+
} else {
283+
return ""
284+
}
285+
}
286+
287+
//Enum containing available byte units
288+
private enum Unit: String {
289+
case byte
290+
case bytes
291+
case KB
292+
case MB
293+
case GB
294+
case TB
295+
case PB
296+
case EB
297+
case ZB
298+
case YB
299+
}
300+
// Maps each unit to it's corresponding value in bytes for decimal
301+
private let decimalByteSize: [Unit: Double] = [.byte: 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)]
302+
303+
// Maps each unit to it's corresponding value in bytes for binary
304+
private let binaryByteSize: [Unit: Double] = [.byte: 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)]
305+
306+
}
94307

0 commit comments

Comments
 (0)