diff options
author | Michael Voronin <m.voronin@ngenix.net> | 2018-05-31 15:30:12 +0300 |
---|---|---|
committer | Michael Voronin <m.voronin@ngenix.net> | 2018-05-31 16:02:37 +0300 |
commit | 11fcc83f8a1cc54965eba55dbfb52625199f651c (patch) | |
tree | 194407a692ae8ebef6e8483056ada73c02b1c382 /lib/pure | |
parent | a573577cdc7d334c88088058dc00f0771ce9bb39 (diff) | |
download | Nim-11fcc83f8a1cc54965eba55dbfb52625199f651c.tar.gz |
[add] Add procs for TimeInterval stringify
Diffstat (limited to 'lib/pure')
-rw-r--r-- | lib/pure/times.nim | 35 |
1 files changed, 34 insertions, 1 deletions
diff --git a/lib/pure/times.nim b/lib/pure/times.nim index 8eda73cc1..956d9716c 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -35,7 +35,7 @@ # of the standard library! import - strutils, parseutils + strutils, parseutils, algorithm include "system/inclrtl" @@ -184,6 +184,8 @@ type isDst*: bool ## Determines whether DST is in effect. DurationParts* = array[FixedTimeUnit, int64] # Array of Duration parts starts + TimeIntervalParts* = array[TimeUnit, int] # Array of Duration parts starts + {.deprecated: [TMonth: Month, TWeekDay: WeekDay, TTime: Time, @@ -1014,6 +1016,37 @@ proc `$`*(m: Month): string = "November", "December"] return lookup[m] + +proc toParts* (ti: TimeInterval): TimeIntervalParts = + ## Converts a `TimeInterval` into an array consisting of its time units, + ## starting with nanoseconds and ending with years + ## + ## This procedure is useful for converting ``TimeInterval`` values to strings. + ## E.g. then you need to implement custom interval printing + runnableExamples: + var tp = toParts(initTimeInterval(years=1, nanoseconds=123)) + doAssert tp[Years] == 1 + doAssert tp[Nanoseconds] == 123 + + var index = 0 + for name, value in fieldPairs(ti): + result[index.TimeUnit()] = value + index += 1 + +proc `$`*(ti: TimeInterval): string = + ## Get string representation of `TimeInterval` + runnableExamples: + doAssert $initTimeInterval(years=1, nanoseconds=123) == "1 year and 123 nanoseconds" + doAssert $initTimeInterval() == "0 nanoseconds" + + var parts: seq[string] = @[] + var tiParts = toParts(ti) + for unit in countdown(Years, Nanoseconds): + if tiParts[unit] != 0: + parts.add(stringifyUnit(tiParts[unit], $unit)) + + result = humanizeParts(parts) + proc nanoseconds*(nanos: int): TimeInterval {.inline.} = ## TimeInterval of ``nanos`` nanoseconds. initTimeInterval(nanoseconds = nanos) |