-
Notifications
You must be signed in to change notification settings - Fork 726
feat: NIO.TimeAmount(string:) and TimeAmount.description #3046
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
5dca8f4
feat: NIO.TimeAmount(string:) and TimeAmount.description
natikgadzhi 79f9b67
formatting
natikgadzhi ff8d127
Make validation error enum internal
natikgadzhi 11ccee8
Merge branch 'main' into time-amount/parsing
natikgadzhi ed93528
Make validation error enum internal
natikgadzhi ec4631b
Merge branch 'main' into time-amount/parsing
Lukasa b00626b
removed defaultUnit
natikgadzhi 526f3a7
Merge branch 'main' into time-amount/parsing
Lukasa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,5 @@ | ||
| .DS_Store | ||
| /.build | ||
| .build | ||
| /.index-build | ||
| /Packages | ||
| /*.xcodeproj | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -551,6 +551,94 @@ public struct TimeAmount: Hashable, Sendable { | |
| } | ||
| } | ||
|
|
||
| /// Contains the logic for parsing time amounts from strings, | ||
| /// and printing pretty strings to represent time amounts. | ||
| extension TimeAmount: CustomStringConvertible { | ||
|
|
||
| /// Errors thrown when parsint a TimeAmount from a string | ||
| public enum ValidationError: Error, Equatable { | ||
| /// Can't parse the provided unit | ||
| case unsupportedUnit(String) | ||
|
|
||
| /// Can't parse the number into a Double | ||
| case invalidNumber(String) | ||
| } | ||
|
|
||
| /// Creates a TimeAmount from a string representation with an optional default unit. | ||
| /// | ||
| /// Supports formats like: | ||
| /// - "5s" (5 seconds) | ||
| /// - "100ms" (100 milliseconds) | ||
| /// - "42" (42 of default unit) | ||
| /// - "1 hr" (1 hour) | ||
| /// | ||
| /// This function only supports one pair of the number and units, i.e. "5s" or "100ms" but not "5s 100ms". | ||
Lukasa marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| /// | ||
| /// Supported units: | ||
| /// - h, hr, hrs (hours) | ||
| /// - m, min (minutes) | ||
| /// - s, sec, secs (seconds) | ||
| /// - ms, millis (milliseconds) | ||
| /// - us, µs, micros (microseconds) | ||
| /// - ns, nanos (nanoseconds) | ||
| /// | ||
| /// - Parameters: | ||
| /// - userProvidedString: The string to parse | ||
| /// - defaultUnit: Unit to use if no unit is specified in the string | ||
| /// | ||
| /// - Throws: ValidationError if the string cannot be parsed | ||
| public init(_ userProvidedString: String, defaultUnit: String = "s") throws { | ||
Lukasa marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| // First parse the string into a number and supported units. | ||
| // Clean out white space from the string. | ||
Lukasa marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| let string = String(userProvidedString.filter { !$0.isWhitespace }).lowercased() | ||
Lukasa marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| // Grab the number from the string prefix. | ||
| let parsedNumbers = string.prefix(while: { $0.isWholeNumber || $0 == "," || $0 == "." }) | ||
| // Grab the rest of the string and match this to a known unit later. | ||
| let parsedUnit = string.dropFirst(parsedNumbers.count) | ||
|
|
||
| guard let numbers = Int64(parsedNumbers) else { | ||
| throw ValidationError.invalidNumber("'\(userProvidedString)' cannot be parsed as number and unit") | ||
| } | ||
| let unit = parsedUnit.isEmpty ? defaultUnit : String(parsedUnit) | ||
|
|
||
| switch unit { | ||
| case "h", "hr", "hrs": | ||
| self = .hours(numbers) | ||
| case "m", "min": | ||
| self = .minutes(numbers) | ||
| case "s", "sec", "secs": | ||
| self = .seconds(numbers) | ||
| case "ms", "millis": | ||
| self = .milliseconds(numbers) | ||
| case "us", "µs", "micros": | ||
| self = .microseconds(numbers) | ||
| case "ns", "nanos": | ||
| self = .nanoseconds(numbers) | ||
| default: | ||
| throw ValidationError.unsupportedUnit("Unknown unit '\(unit)' in '\(userProvidedString)'") | ||
| } | ||
| } | ||
|
|
||
| /// Returns a human-readable string representation of the time amount | ||
| /// using the most appropriate unit | ||
| public var description: String { | ||
Lukasa marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| let fullNS = self.nanoseconds | ||
| let (fullUS, remUS) = fullNS.quotientAndRemainder(dividingBy: 1_000) | ||
| let (fullMS, remMS) = fullNS.quotientAndRemainder(dividingBy: 1_000_000) | ||
| let (fullS, remS) = fullNS.quotientAndRemainder(dividingBy: 1_000_000_000) | ||
|
|
||
| if remS == 0 { | ||
| return "\(fullS) s" | ||
| } else if remMS == 0 { | ||
| return "\(fullMS) ms" | ||
| } else if remUS == 0 { | ||
| return "\(fullUS) us" | ||
| } else { | ||
| return "\(fullNS) ns" | ||
| } | ||
| } | ||
| } | ||
|
|
||
| extension TimeAmount: Comparable { | ||
| @inlinable | ||
| public static func < (lhs: TimeAmount, rhs: TimeAmount) -> Bool { | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure it's a great idea to introduce a new public error type. Can I get away with re-using something?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I doubt that anybody would really catch that error, so we could also just make this an
internalerror type. That way you can still throw & print it but NIO wouldn't be forced into the API.