Debian Codegraph @

libphobos/libdruntime/core/time.d

raw
1 //Written in the D programming language
2
3 /++
4 Module containing core time functionality, such as $(LREF Duration) (which
5 represents a duration of time) or $(LREF MonoTime) (which represents a
6 timestamp of the system's monotonic clock).
7
8 Various functions take a string (or strings) to represent a unit of time
9 (e.g. $(D convert!("days", "hours")(numDays))). The valid strings to use
10 with such functions are "years", "months", "weeks", "days", "hours",
11 "minutes", "seconds", "msecs" (milliseconds), "usecs" (microseconds),
12 "hnsecs" (hecto-nanoseconds - i.e. 100 ns) or some subset thereof. There
13 are a few functions that also allow "nsecs", but very little actually
14 has precision greater than hnsecs.
15
16 $(BOOKTABLE Cheat Sheet,
17 $(TR $(TH Symbol) $(TH Description))
18 $(LEADINGROW Types)
19 $(TR $(TDNW $(LREF Duration)) $(TD Represents a duration of time of weeks
20 or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds).))
21 $(TR $(TDNW $(LREF TickDuration)) $(TD $(RED DEPRECATED) Represents a duration of time in
22 system clock ticks, using the highest precision that the system provides.))
23 $(TR $(TDNW $(LREF MonoTime)) $(TD Represents a monotonic timestamp in
24 system clock ticks, using the highest precision that the system provides.))
25 $(LEADINGROW Functions)
26 $(TR $(TDNW $(LREF convert)) $(TD Generic way of converting between two time
27 units.))
28 $(TR $(TDNW $(LREF dur)) $(TD Allows constructing a $(LREF Duration) from
29 the given time units with the given length.))
30 $(TR $(TDNW $(LREF weeks)$(NBSP)$(LREF days)$(NBSP)$(LREF hours)$(BR)
31 $(LREF minutes)$(NBSP)$(LREF seconds)$(NBSP)$(LREF msecs)$(BR)
32 $(LREF usecs)$(NBSP)$(LREF hnsecs)$(NBSP)$(LREF nsecs))
33 $(TD Convenience aliases for $(LREF dur).))
34 $(TR $(TDNW $(LREF abs)) $(TD Returns the absolute value of a duration.))
35 )
36
37 $(BOOKTABLE Conversions,
38 $(TR $(TH )
39 $(TH From $(LREF Duration))
40 $(TH From $(LREF TickDuration))
41 $(TH From units)
42 )
43 $(TR $(TD $(B To $(LREF Duration)))
44 $(TD -)
45 $(TD $(D tickDuration.)$(REF_SHORT to, std,conv)$(D !Duration()))
46 $(TD $(D dur!"msecs"(5)) or $(D 5.msecs()))
47 )
48 $(TR $(TD $(B To $(LREF TickDuration)))
49 $(TD $(D duration.)$(REF_SHORT to, std,conv)$(D !TickDuration()))
50 $(TD -)
51 $(TD $(D TickDuration.from!"msecs"(msecs)))
52 )
53 $(TR $(TD $(B To units))
54 $(TD $(D duration.total!"days"))
55 $(TD $(D tickDuration.msecs))
56 $(TD $(D convert!("days", "msecs")(msecs)))
57 ))
58
59 Copyright: Copyright 2010 - 2012
60 License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
61 Authors: $(HTTP jmdavisprog.com, Jonathan M Davis) and Kato Shoichi
62 Source: $(DRUNTIMESRC core/_time.d)
63 Macros:
64 NBSP= 
65 +/
66 module core.time;
67
68 import core.exception;
69 import core.internal.string;
70 import core.stdc.time : time;
71
72 version (OSX)
73 version = Darwin;
74 else version (iOS)
75 version = Darwin;
76 else version (TVOS)
77 version = Darwin;
78 else version (WatchOS)
79 version = Darwin;
80
81 version (Windows)
82 {
83 import core.sys.windows.winbase /+: QueryPerformanceCounter, QueryPerformanceFrequency+/;
84 }
85 else version (Darwin)
86 {
87 import core.sys.posix.sys.time : gettimeofday, timeval;
88 import core.sys.posix.time : timespec;
89 }
90 else version (Posix)
91 {
92 import core.sys.posix.sys.time : gettimeofday, timeval;
93 import core.sys.posix.time : clock_getres, clock_gettime, CLOCK_MONOTONIC, timespec;
94 }
95
96 version (unittest) import core.stdc.stdio : printf;
97
98
99 //This probably should be moved somewhere else in druntime which
100 //is Darwin-specific.
101 version (Darwin)
102 {
103
104 import core.sys.darwin.mach.kern_return : kern_return_t;
105
106 extern(C) nothrow @nogc
107 {
108
109 struct mach_timebase_info_data_t
110 {
111 uint numer;
112 uint denom;
113 }
114
115 alias mach_timebase_info_data_t* mach_timebase_info_t;
116
117 kern_return_t mach_timebase_info(mach_timebase_info_t);
118
119 ulong mach_absolute_time();
120
121 }
122
123 }
124
125 /++
126 What type of clock to use with $(LREF MonoTime) / $(LREF MonoTimeImpl) or
127 $(D std.datetime.Clock.currTime). They default to $(D ClockType.normal),
128 and most programs do not need to ever deal with the others.
129
130 The other $(D ClockType)s are provided so that other clocks provided by the
131 underlying C, system calls can be used with $(LREF MonoTimeImpl) or
132 $(D std.datetime.Clock.currTime) without having to use the C API directly.
133
134 In the case of the monotonic time, $(LREF MonoTimeImpl) is templatized on
135 $(D ClockType), whereas with $(D std.datetime.Clock.currTime), its a runtime
136 argument, since in the case of the monotonic time, the type of the clock
137 affects the resolution of a $(LREF MonoTimeImpl) object, whereas with
138 $(REF SysTime, std,datetime), its resolution is always hecto-nanoseconds
139 regardless of the source of the time.
140
141 $(D ClockType.normal), $(D ClockType.coarse), and $(D ClockType.precise)
142 work with both $(D Clock.currTime) and $(LREF MonoTimeImpl).
143 $(D ClockType.second) only works with $(D Clock.currTime). The others only
144 work with $(LREF MonoTimeImpl).
145 +/
146 version (CoreDdoc) enum ClockType
147 {
148 /++
149 Use the normal clock.
150 +/
151 normal = 0,
152
153 /++
154 $(BLUE Linux,OpenBSD-Only)
155
156 Uses $(D CLOCK_BOOTTIME).
157 +/
158 bootTime = 1,
159
160 /++
161 Use the coarse clock, not the normal one (e.g. on Linux, that would be
162 $(D CLOCK_REALTIME_COARSE) instead of $(D CLOCK_REALTIME) for
163 $(D clock_gettime) if a function is using the realtime clock). It's
164 generally faster to get the time with the coarse clock than the normal
165 clock, but it's less precise (e.g. 1 msec instead of 1 usec or 1 nsec).
166 Howeover, it $(I is) guaranteed to still have sub-second precision
167 (just not as high as with $(D ClockType.normal)).
168
169 On systems which do not support a coarser clock,
170 $(D MonoTimeImpl!(ClockType.coarse)) will internally use the same clock
171 as $(D MonoTime) does, and $(D Clock.currTime!(ClockType.coarse)) will
172 use the same clock as $(D Clock.currTime). This is because the coarse
173 clock is doing the same thing as the normal clock (just at lower
174 precision), whereas some of the other clock types
175 (e.g. $(D ClockType.processCPUTime)) mean something fundamentally
176 different. So, treating those as $(D ClockType.normal) on systems where
177 they weren't natively supported would give misleading results.
178
179 Most programs should not use the coarse clock, exactly because it's
180 less precise, and most programs don't need to get the time often
181 enough to care, but for those rare programs that need to get the time
182 extremely frequently (e.g. hundreds of thousands of times a second) but
183 don't care about high precision, the coarse clock might be appropriate.
184
185 Currently, only Linux and FreeBSD/DragonFlyBSD support a coarser clock, and on other
186 platforms, it's treated as $(D ClockType.normal).
187 +/
188 coarse = 2,
189
190 /++
191 Uses a more precise clock than the normal one (which is already very
192 precise), but it takes longer to get the time. Similarly to
193 $(D ClockType.coarse), if it's used on a system that does not support a
194 more precise clock than the normal one, it's treated as equivalent to
195 $(D ClockType.normal).
196
197 Currently, only FreeBSD/DragonFlyBSD supports a more precise clock, where it uses
198 $(D CLOCK_MONOTONIC_PRECISE) for the monotonic time and
199 $(D CLOCK_REALTIME_PRECISE) for the wall clock time.
200 +/
201 precise = 3,
202
203 /++
204 $(BLUE Linux,OpenBSD,Solaris-Only)
205
206 Uses $(D CLOCK_PROCESS_CPUTIME_ID).
207 +/
208 processCPUTime = 4,
209
210 /++
211 $(BLUE Linux-Only)
212
213 Uses $(D CLOCK_MONOTONIC_RAW).
214 +/
215 raw = 5,
216
217 /++
218 Uses a clock that has a precision of one second (contrast to the coarse
219 clock, which has sub-second precision like the normal clock does).
220
221 FreeBSD/DragonFlyBSD are the only systems which specifically have a clock set up for
222 this (it has $(D CLOCK_SECOND) to use with $(D clock_gettime) which
223 takes advantage of an in-kernel cached value), but on other systems, the
224 fastest function available will be used, and the resulting $(D SysTime)
225 will be rounded down to the second if the clock that was used gave the
226 time at a more precise resolution. So, it's guaranteed that the time
227 will be given at a precision of one second and it's likely the case that
228 will be faster than $(D ClockType.normal), since there tend to be
229 several options on a system to get the time at low resolutions, and they
230 tend to be faster than getting the time at high resolutions.
231
232 So, the primary difference between $(D ClockType.coarse) and
233 $(D ClockType.second) is that $(D ClockType.coarse) sacrifices some
234 precision in order to get speed but is still fairly precise, whereas
235 $(D ClockType.second) tries to be as fast as possible at the expense of
236 all sub-second precision.
237 +/
238 second = 6,
239
240 /++
241 $(BLUE Linux,OpenBSD,Solaris-Only)
242
243 Uses $(D CLOCK_THREAD_CPUTIME_ID).
244 +/
245 threadCPUTime = 7,
246
247 /++
248 $(BLUE DragonFlyBSD,FreeBSD,OpenBSD-Only)
249
250 Uses $(D CLOCK_UPTIME).
251 +/
252 uptime = 8,
253
254 /++
255 $(BLUE FreeBSD-Only)
256
257 Uses $(D CLOCK_UPTIME_FAST).
258 +/
259 uptimeCoarse = 9,
260
261 /++
262 $(BLUE FreeBSD-Only)
263
264 Uses $(D CLOCK_UPTIME_PRECISE).
265 +/
266 uptimePrecise = 10,
267 }
268 else version (Windows) enum ClockType
269 {
270 normal = 0,
271 coarse = 2,
272 precise = 3,
273 second = 6,
274 }
275 else version (Darwin) enum ClockType
276 {
277 normal = 0,
278 coarse = 2,
279 precise = 3,
280 second = 6,
281 }
282 else version (linux) enum ClockType
283 {
284 normal = 0,
285 bootTime = 1,
286 coarse = 2,
287 precise = 3,
288 processCPUTime = 4,
289 raw = 5,
290 second = 6,
291 threadCPUTime = 7,
292 }
293 else version (FreeBSD) enum ClockType
294 {
295 normal = 0,
296 coarse = 2,
297 precise = 3,
298 second = 6,
299 uptime = 8,
300 uptimeCoarse = 9,
301 uptimePrecise = 10,
302 }
303 else version (NetBSD) enum ClockType
304 {
305 normal = 0,
306 coarse = 2,
307 precise = 3,
308 second = 6,
309 }
310 else version (OpenBSD) enum ClockType
311 {
312 normal = 0,
313 bootTime = 1,
314 coarse = 2,
315 precise = 3,
316 processCPUTime = 4,
317 second = 6,
318 threadCPUTime = 7,
319 uptime = 8,
320 }
321 else version (DragonFlyBSD) enum ClockType
322 {
323 normal = 0,
324 coarse = 2,
325 precise = 3,
326 second = 6,
327 uptime = 8,
328 uptimeCoarse = 9,
329 uptimePrecise = 10,
330 }
331 else version (Solaris) enum ClockType
332 {
333 normal = 0,
334 coarse = 2,
335 precise = 3,
336 processCPUTime = 4,
337 second = 6,
338 threadCPUTime = 7,
339 }
340 else
341 {
342 // It needs to be decided (and implemented in an appropriate version branch
343 // here) which clock types new platforms are going to support. At minimum,
344 // the ones _not_ marked with $(D Blue Foo-Only) should be supported.
345 static assert(0, "What are the clock types supported by this system?");
346 }
347
348 // private, used to translate clock type to proper argument to clock_xxx
349 // functions on posix systems
350 version (CoreDdoc)
351 private int _posixClock(ClockType clockType) { return 0; }
352 else
353 version (Posix)
354 {
355 private auto _posixClock(ClockType clockType)
356 {
357 version (linux)
358 {
359 import core.sys.linux.time;
360 with(ClockType) final switch (clockType)
361 {
362 case bootTime: return CLOCK_BOOTTIME;
363 case coarse: return CLOCK_MONOTONIC_COARSE;
364 case normal: return CLOCK_MONOTONIC;
365 case precise: return CLOCK_MONOTONIC;
366 case processCPUTime: return CLOCK_PROCESS_CPUTIME_ID;
367 case raw: return CLOCK_MONOTONIC_RAW;
368 case threadCPUTime: return CLOCK_THREAD_CPUTIME_ID;
369 case second: assert(0);
370 }
371 }
372 else version (FreeBSD)
373 {
374 import core.sys.freebsd.time;
375 with(ClockType) final switch (clockType)
376 {
377 case coarse: return CLOCK_MONOTONIC_FAST;
378 case normal: return CLOCK_MONOTONIC;
379 case precise: return CLOCK_MONOTONIC_PRECISE;
380 case uptime: return CLOCK_UPTIME;
381 case uptimeCoarse: return CLOCK_UPTIME_FAST;
382 case uptimePrecise: return CLOCK_UPTIME_PRECISE;
383 case second: assert(0);
384 }
385 }
386 else version (NetBSD)
387 {
388 import core.sys.netbsd.time;
389 with(ClockType) final switch (clockType)
390 {
391 case coarse: return CLOCK_MONOTONIC;
392 case normal: return CLOCK_MONOTONIC;
393 case precise: return CLOCK_MONOTONIC;
394 case second: assert(0);
395 }
396 }
397 else version (OpenBSD)
398 {
399 import core.sys.openbsd.time;
400 with(ClockType) final switch (clockType)
401 {
402 case bootTime: return CLOCK_BOOTTIME;
403 case coarse: return CLOCK_MONOTONIC;
404 case normal: return CLOCK_MONOTONIC;
405 case precise: return CLOCK_MONOTONIC;
406 case processCPUTime: return CLOCK_PROCESS_CPUTIME_ID;
407 case threadCPUTime: return CLOCK_THREAD_CPUTIME_ID;
408 case uptime: return CLOCK_UPTIME;
409 case second: assert(0);
410 }
411 }
412 else version (DragonFlyBSD)
413 {
414 import core.sys.dragonflybsd.time;
415 with(ClockType) final switch (clockType)
416 {
417 case coarse: return CLOCK_MONOTONIC_FAST;
418 case normal: return CLOCK_MONOTONIC;
419 case precise: return CLOCK_MONOTONIC_PRECISE;
420 case uptime: return CLOCK_UPTIME;
421 case uptimeCoarse: return CLOCK_UPTIME_FAST;
422 case uptimePrecise: return CLOCK_UPTIME_PRECISE;
423 case second: assert(0);
424 }
425 }
426 else version (Solaris)
427 {
428 import core.sys.solaris.time;
429 with(ClockType) final switch (clockType)
430 {
431 case coarse: return CLOCK_MONOTONIC;
432 case normal: return CLOCK_MONOTONIC;
433 case precise: return CLOCK_MONOTONIC;
434 case processCPUTime: return CLOCK_PROCESS_CPUTIME_ID;
435 case threadCPUTime: return CLOCK_THREAD_CPUTIME_ID;
436 case second: assert(0);
437 }
438 }
439 else
440 // It needs to be decided (and implemented in an appropriate
441 // version branch here) which clock types new platforms are going
442 // to support. Also, ClockType's documentation should be updated to
443 // mention it if a new platform uses anything that's not supported
444 // on all platforms..
445 assert(0, "What are the monotonic clock types supported by this system?");
446 }
447 }
448
449 unittest
450 {
451 // Make sure that the values are the same across platforms.
452 static if (is(typeof(ClockType.normal))) static assert(ClockType.normal == 0);
453 static if (is(typeof(ClockType.bootTime))) static assert(ClockType.bootTime == 1);
454 static if (is(typeof(ClockType.coarse))) static assert(ClockType.coarse == 2);
455 static if (is(typeof(ClockType.precise))) static assert(ClockType.precise == 3);
456 static if (is(typeof(ClockType.processCPUTime))) static assert(ClockType.processCPUTime == 4);
457 static if (is(typeof(ClockType.raw))) static assert(ClockType.raw == 5);
458 static if (is(typeof(ClockType.second))) static assert(ClockType.second == 6);
459 static if (is(typeof(ClockType.threadCPUTime))) static assert(ClockType.threadCPUTime == 7);
460 static if (is(typeof(ClockType.uptime))) static assert(ClockType.uptime == 8);
461 static if (is(typeof(ClockType.uptimeCoarse))) static assert(ClockType.uptimeCoarse == 9);
462 static if (is(typeof(ClockType.uptimePrecise))) static assert(ClockType.uptimePrecise == 10);
463 }
464
465
466 /++
467 Represents a duration of time of weeks or less (kept internally as hnsecs).
468 (e.g. 22 days or 700 seconds).
469
470 It is used when representing a duration of time - such as how long to
471 sleep with $(REF Thread.sleep, core,thread).
472
473 In std.datetime, it is also used as the result of various arithmetic
474 operations on time points.
475
476 Use the $(LREF dur) function or one of its non-generic aliases to create
477 $(D Duration)s.
478
479 It's not possible to create a Duration of months or years, because the
480 variable number of days in a month or year makes it impossible to convert
481 between months or years and smaller units without a specific date. So,
482 nothing uses $(D Duration)s when dealing with months or years. Rather,
483 functions specific to months and years are defined. For instance,
484 $(REF Date, std,datetime) has $(D add!"years") and $(D add!"months") for adding
485 years and months rather than creating a Duration of years or months and
486 adding that to a $(REF Date, std,datetime). But Duration is used when dealing
487 with weeks or smaller.
488
489 Examples:
490 --------------------
491 import std.datetime;
492
493 assert(dur!"days"(12) == dur!"hnsecs"(10_368_000_000_000L));
494 assert(dur!"hnsecs"(27) == dur!"hnsecs"(27));
495 assert(std.datetime.Date(2010, 9, 7) + dur!"days"(5) ==
496 std.datetime.Date(2010, 9, 12));
497
498 assert(days(-12) == dur!"hnsecs"(-10_368_000_000_000L));
499 assert(hnsecs(-27) == dur!"hnsecs"(-27));
500 assert(std.datetime.Date(2010, 9, 7) - std.datetime.Date(2010, 10, 3) ==
501 days(-26));
502 --------------------
503 +/
504 struct Duration
505 {
506 /++
507 Converts this `Duration` to a `string`.
508
509 The string is meant to be human readable, not machine parseable (e.g.
510 whether there is an `'s'` on the end of the unit name usually depends on
511 whether it's plural or not, and empty units are not included unless the
512 Duration is `zero`). Any code needing a specific string format should
513 use `total` or `split` to get the units needed to create the desired
514 string format and create the string itself.
515
516 The format returned by toString may or may not change in the future.
517
518 Params:
519 sink = A sink object, expected to be a delegate or aggregate
520 implementing `opCall` that accepts a `scope const(char)[]`
521 as argument.
522 +/
523 void toString (SinkT) (scope SinkT sink) const scope
524 {
525 static immutable units = [
526 "weeks", "days", "hours", "minutes", "seconds", "msecs", "usecs"
527 ];
528
529 static void appListSep(SinkT sink, uint pos, bool last)
530 {
531 if (pos == 0)
532 return;
533 if (!last)
534 sink(", ");
535 else
536 sink(pos == 1 ? " and " : ", and ");
537 }
538
539 static void appUnitVal(string units)(SinkT sink, long val)
540 {
541 immutable plural = val != 1;
542 string unit;
543 static if (units == "seconds")
544 unit = plural ? "secs" : "sec";
545 else static if (units == "msecs")
546 unit = "ms";
547 else static if (units == "usecs")
548 unit = "μs";
549 else
550 unit = plural ? units : units[0 .. $-1];
551 sink(signedToTempString(val));
552 sink(" ");
553 sink(unit);
554 }
555
556 if (_hnsecs == 0)
557 {
558 sink("0 hnsecs");
559 return;
560 }
561
562 long hnsecs = _hnsecs;
563 uint pos;
564 static foreach (unit; units)
565 {
566 if (auto val = splitUnitsFromHNSecs!unit(hnsecs))
567 {
568 appListSep(sink, pos++, hnsecs == 0);
569 appUnitVal!unit(sink, val);
570 }
571 if (hnsecs == 0)
572 return;
573 }
574 if (hnsecs != 0)
575 {
576 appListSep(sink, pos++, true);
577 appUnitVal!"hnsecs"(sink, hnsecs);
578 }
579 }
580
581 @safe pure:
582
583 public:
584
585 /++
586 A $(D Duration) of $(D 0). It's shorter than doing something like
587 $(D dur!"seconds"(0)) and more explicit than $(D Duration.init).
588 +/
589 static @property nothrow @nogc Duration zero() { return Duration(0); }
590
591 /++
592 Largest $(D Duration) possible.
593 +/
594 static @property nothrow @nogc Duration max() { return Duration(long.max); }
595
596 /++
597 Most negative $(D Duration) possible.
598 +/
599 static @property nothrow @nogc Duration min() { return Duration(long.min); }
600
601 version (CoreUnittest) unittest
602 {
603 assert(zero == dur!"seconds"(0));
604 assert(Duration.max == Duration(long.max));
605 assert(Duration.min == Duration(long.min));
606 assert(Duration.min < Duration.zero);
607 assert(Duration.zero < Duration.max);
608 assert(Duration.min < Duration.max);
609 assert(Duration.min - dur!"hnsecs"(1) == Duration.max);
610 assert(Duration.max + dur!"hnsecs"(1) == Duration.min);
611 }
612
613
614 /++
615 Compares this $(D Duration) with the given $(D Duration).
616
617 Returns:
618 $(TABLE
619 $(TR $(TD this &lt; rhs) $(TD &lt; 0))
620 $(TR $(TD this == rhs) $(TD 0))
621 $(TR $(TD this &gt; rhs) $(TD &gt; 0))
622 )
623 +/
624 int opCmp(Duration rhs) const nothrow @nogc
625 {
626 return (_hnsecs > rhs._hnsecs) - (_hnsecs < rhs._hnsecs);
627 }
628
629 version (CoreUnittest) unittest
630 {
631 import core.internal.traits : rvalueOf;
632 foreach (T; AliasSeq!(Duration, const Duration, immutable Duration))
633 {
634 foreach (U; AliasSeq!(Duration, const Duration, immutable Duration))
635 {
636 T t = 42;
637 // workaround https://issues.dlang.org/show_bug.cgi?id=18296
638 version (D_Coverage)
639 U u = T(t._hnsecs);
640 else
641 U u = t;
642 assert(t == u);
643 assert(rvalueOf(t) == u);
644 assert(t == rvalueOf(u));
645 }
646 }
647
648 foreach (D; AliasSeq!(Duration, const Duration, immutable Duration))
649 {
650 foreach (E; AliasSeq!(Duration, const Duration, immutable Duration))
651 {
652 assert((cast(D)Duration(12)).opCmp(cast(E)Duration(12)) == 0);
653 assert((cast(D)Duration(-12)).opCmp(cast(E)Duration(-12)) == 0);
654
655 assert((cast(D)Duration(10)).opCmp(cast(E)Duration(12)) < 0);
656 assert((cast(D)Duration(-12)).opCmp(cast(E)Duration(12)) < 0);
657
658 assert((cast(D)Duration(12)).opCmp(cast(E)Duration(10)) > 0);
659 assert((cast(D)Duration(12)).opCmp(cast(E)Duration(-12)) > 0);
660
661 assert(rvalueOf(cast(D)Duration(12)).opCmp(cast(E)Duration(12)) == 0);
662 assert(rvalueOf(cast(D)Duration(-12)).opCmp(cast(E)Duration(-12)) == 0);
663
664 assert(rvalueOf(cast(D)Duration(10)).opCmp(cast(E)Duration(12)) < 0);
665 assert(rvalueOf(cast(D)Duration(-12)).opCmp(cast(E)Duration(12)) < 0);
666
667 assert(rvalueOf(cast(D)Duration(12)).opCmp(cast(E)Duration(10)) > 0);
668 assert(rvalueOf(cast(D)Duration(12)).opCmp(cast(E)Duration(-12)) > 0);
669
670 assert((cast(D)Duration(12)).opCmp(rvalueOf(cast(E)Duration(12))) == 0);
671 assert((cast(D)Duration(-12)).opCmp(rvalueOf(cast(E)Duration(-12))) == 0);
672
673 assert((cast(D)Duration(10)).opCmp(rvalueOf(cast(E)Duration(12))) < 0);
674 assert((cast(D)Duration(-12)).opCmp(rvalueOf(cast(E)Duration(12))) < 0);
675
676 assert((cast(D)Duration(12)).opCmp(rvalueOf(cast(E)Duration(10))) > 0);
677 assert((cast(D)Duration(12)).opCmp(rvalueOf(cast(E)Duration(-12))) > 0);
678 }
679 }
680 }
681
682
683 /++
684 Adds, subtracts or calculates the modulo of two durations.
685
686 The legal types of arithmetic for $(D Duration) using this operator are
687
688 $(TABLE
689 $(TR $(TD Duration) $(TD +) $(TD Duration) $(TD -->) $(TD Duration))
690 $(TR $(TD Duration) $(TD -) $(TD Duration) $(TD -->) $(TD Duration))
691 $(TR $(TD Duration) $(TD %) $(TD Duration) $(TD -->) $(TD Duration))
692 )
693
694 Params:
695 rhs = The duration to add to or subtract from this $(D Duration).
696 +/
697 Duration opBinary(string op)(const Duration rhs) const nothrow @nogc
698 if (op == "+" || op == "-" || op == "%")
699 {
700 return Duration(mixin("_hnsecs " ~ op ~ " rhs._hnsecs"));
701 }
702
703 deprecated Duration opBinary(string op)(const TickDuration rhs) const nothrow @nogc
704 if (op == "+" || op == "-")
705 {
706 return Duration(mixin("_hnsecs " ~ op ~ " rhs.hnsecs"));
707 }
708
709 version (CoreUnittest) unittest
710 {
711 alias Types = AliasSeq!(Duration, const Duration, immutable Duration);
712 foreach (D; Types)
713 {
714 foreach (E; Types)
715 {
716 assert((cast(D)Duration(5)) + (cast(E)Duration(7)) == Duration(12));
717 assert((cast(D)Duration(5)) - (cast(E)Duration(7)) == Duration(-2));
718 assert((cast(D)Duration(5)) % (cast(E)Duration(7)) == Duration(5));
719 assert((cast(D)Duration(7)) + (cast(E)Duration(5)) == Duration(12));
720 assert((cast(D)Duration(7)) - (cast(E)Duration(5)) == Duration(2));
721 assert((cast(D)Duration(7)) % (cast(E)Duration(5)) == Duration(2));
722
723 assert((cast(D)Duration(5)) + (cast(E)Duration(-7)) == Duration(-2));
724 assert((cast(D)Duration(5)) - (cast(E)Duration(-7)) == Duration(12));
725 assert((cast(D)Duration(5)) % (cast(E)Duration(-7)) == Duration(5));
726 assert((cast(D)Duration(7)) + (cast(E)Duration(-5)) == Duration(2));
727 assert((cast(D)Duration(7)) - (cast(E)Duration(-5)) == Duration(12));
728 assert((cast(D)Duration(7)) % (cast(E)Duration(-5)) == Duration(2));
729
730 assert((cast(D)Duration(-5)) + (cast(E)Duration(7)) == Duration(2));
731 assert((cast(D)Duration(-5)) - (cast(E)Duration(7)) == Duration(-12));
732 assert((cast(D)Duration(-5)) % (cast(E)Duration(7)) == Duration(-5));
733 assert((cast(D)Duration(-7)) + (cast(E)Duration(5)) == Duration(-2));
734 assert((cast(D)Duration(-7)) - (cast(E)Duration(5)) == Duration(-12));
735 assert((cast(D)Duration(-7)) % (cast(E)Duration(5)) == Duration(-2));
736
737 assert((cast(D)Duration(-5)) + (cast(E)Duration(-7)) == Duration(-12));
738 assert((cast(D)Duration(-5)) - (cast(E)Duration(-7)) == Duration(2));
739 assert((cast(D)Duration(-5)) % (cast(E)Duration(7)) == Duration(-5));
740 assert((cast(D)Duration(-7)) + (cast(E)Duration(-5)) == Duration(-12));
741 assert((cast(D)Duration(-7)) - (cast(E)Duration(-5)) == Duration(-2));
742 assert((cast(D)Duration(-7)) % (cast(E)Duration(5)) == Duration(-2));
743 }
744 }
745 }
746
747 version (CoreUnittest) deprecated unittest
748 {
749 foreach (D; AliasSeq!(Duration, const Duration, immutable Duration))
750 {
751 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
752 {
753 assertApprox((cast(D)Duration(5)) + cast(T)TickDuration.from!"usecs"(7), Duration(70), Duration(80));
754 assertApprox((cast(D)Duration(5)) - cast(T)TickDuration.from!"usecs"(7), Duration(-70), Duration(-60));
755 assertApprox((cast(D)Duration(7)) + cast(T)TickDuration.from!"usecs"(5), Duration(52), Duration(62));
756 assertApprox((cast(D)Duration(7)) - cast(T)TickDuration.from!"usecs"(5), Duration(-48), Duration(-38));
757
758 assertApprox((cast(D)Duration(5)) + cast(T)TickDuration.from!"usecs"(-7), Duration(-70), Duration(-60));
759 assertApprox((cast(D)Duration(5)) - cast(T)TickDuration.from!"usecs"(-7), Duration(70), Duration(80));
760 assertApprox((cast(D)Duration(7)) + cast(T)TickDuration.from!"usecs"(-5), Duration(-48), Duration(-38));
761 assertApprox((cast(D)Duration(7)) - cast(T)TickDuration.from!"usecs"(-5), Duration(52), Duration(62));
762
763 assertApprox((cast(D)Duration(-5)) + cast(T)TickDuration.from!"usecs"(7), Duration(60), Duration(70));
764 assertApprox((cast(D)Duration(-5)) - cast(T)TickDuration.from!"usecs"(7), Duration(-80), Duration(-70));
765 assertApprox((cast(D)Duration(-7)) + cast(T)TickDuration.from!"usecs"(5), Duration(38), Duration(48));
766 assertApprox((cast(D)Duration(-7)) - cast(T)TickDuration.from!"usecs"(5), Duration(-62), Duration(-52));
767
768 assertApprox((cast(D)Duration(-5)) + cast(T)TickDuration.from!"usecs"(-7), Duration(-80), Duration(-70));
769 assertApprox((cast(D)Duration(-5)) - cast(T)TickDuration.from!"usecs"(-7), Duration(60), Duration(70));
770 assertApprox((cast(D)Duration(-7)) + cast(T)TickDuration.from!"usecs"(-5), Duration(-62), Duration(-52));
771 assertApprox((cast(D)Duration(-7)) - cast(T)TickDuration.from!"usecs"(-5), Duration(38), Duration(48));
772 }
773 }
774 }
775
776
777 /++
778 $(RED TickDuration is Deprecated)
779
780 Adds or subtracts two durations.
781
782 The legal types of arithmetic for $(D Duration) using this operator are
783
784 $(TABLE
785 $(TR $(TD TickDuration) $(TD +) $(TD Duration) $(TD -->) $(TD Duration))
786 $(TR $(TD TickDuration) $(TD -) $(TD Duration) $(TD -->) $(TD Duration))
787 )
788
789 Params:
790 lhs = The $(D TickDuration) to add to this $(D Duration) or to
791 subtract this $(D Duration) from.
792 +/
793 deprecated Duration opBinaryRight(string op, D)(D lhs) const nothrow @nogc
794 if ((op == "+" || op == "-") &&
795 is(immutable D == immutable TickDuration))
796 {
797 return Duration(mixin("lhs.hnsecs " ~ op ~ " _hnsecs"));
798 }
799
800 version (CoreUnittest) deprecated unittest
801 {
802 foreach (D; AliasSeq!(Duration, const Duration, immutable Duration))
803 {
804 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
805 {
806 assertApprox((cast(T)TickDuration.from!"usecs"(7)) + cast(D)Duration(5), Duration(70), Duration(80));
807 assertApprox((cast(T)TickDuration.from!"usecs"(7)) - cast(D)Duration(5), Duration(60), Duration(70));
808 assertApprox((cast(T)TickDuration.from!"usecs"(5)) + cast(D)Duration(7), Duration(52), Duration(62));
809 assertApprox((cast(T)TickDuration.from!"usecs"(5)) - cast(D)Duration(7), Duration(38), Duration(48));
810
811 assertApprox((cast(T)TickDuration.from!"usecs"(-7)) + cast(D)Duration(5), Duration(-70), Duration(-60));
812 assertApprox((cast(T)TickDuration.from!"usecs"(-7)) - cast(D)Duration(5), Duration(-80), Duration(-70));
813 assertApprox((cast(T)TickDuration.from!"usecs"(-5)) + cast(D)Duration(7), Duration(-48), Duration(-38));
814 assertApprox((cast(T)TickDuration.from!"usecs"(-5)) - cast(D)Duration(7), Duration(-62), Duration(-52));
815
816 assertApprox((cast(T)TickDuration.from!"usecs"(7)) + (cast(D)Duration(-5)), Duration(60), Duration(70));
817 assertApprox((cast(T)TickDuration.from!"usecs"(7)) - (cast(D)Duration(-5)), Duration(70), Duration(80));
818 assertApprox((cast(T)TickDuration.from!"usecs"(5)) + (cast(D)Duration(-7)), Duration(38), Duration(48));
819 assertApprox((cast(T)TickDuration.from!"usecs"(5)) - (cast(D)Duration(-7)), Duration(52), Duration(62));
820
821 assertApprox((cast(T)TickDuration.from!"usecs"(-7)) + cast(D)Duration(-5), Duration(-80), Duration(-70));
822 assertApprox((cast(T)TickDuration.from!"usecs"(-7)) - cast(D)Duration(-5), Duration(-70), Duration(-60));
823 assertApprox((cast(T)TickDuration.from!"usecs"(-5)) + cast(D)Duration(-7), Duration(-62), Duration(-52));
824 assertApprox((cast(T)TickDuration.from!"usecs"(-5)) - cast(D)Duration(-7), Duration(-48), Duration(-38));
825 }
826 }
827 }
828
829
830 /++
831 Adds, subtracts or calculates the modulo of two durations as well as
832 assigning the result to this $(D Duration).
833
834 The legal types of arithmetic for $(D Duration) using this operator are
835
836 $(TABLE
837 $(TR $(TD Duration) $(TD +) $(TD Duration) $(TD -->) $(TD Duration))
838 $(TR $(TD Duration) $(TD -) $(TD Duration) $(TD -->) $(TD Duration))
839 $(TR $(TD Duration) $(TD %) $(TD Duration) $(TD -->) $(TD Duration))
840 )
841
842 Params:
843 rhs = The duration to add to or subtract from this $(D Duration).
844 +/
845 ref Duration opOpAssign(string op)(const Duration rhs) nothrow @nogc
846 if (op == "+" || op == "-" || op == "%")
847 {
848 mixin("_hnsecs " ~ op ~ "= rhs._hnsecs;");
849 return this;
850 }
851
852 deprecated ref Duration opOpAssign(string op)(const TickDuration rhs) nothrow @nogc
853 if (op == "+" || op == "-")
854 {
855 mixin("_hnsecs " ~ op ~ "= rhs.hnsecs;");
856 return this;
857 }
858
859 version (CoreUnittest) unittest
860 {
861 static void test1(string op, E)(Duration actual, in E rhs, Duration expected, size_t line = __LINE__)
862 {
863 if (mixin("actual " ~ op ~ " rhs") != expected)
864 throw new AssertError("op failed", __FILE__, line);
865
866 if (actual != expected)
867 throw new AssertError("op assign failed", __FILE__, line);
868 }
869
870 foreach (E; AliasSeq!(Duration, const Duration, immutable Duration))
871 {
872 test1!"+="(Duration(5), (cast(E)Duration(7)), Duration(12));
873 test1!"-="(Duration(5), (cast(E)Duration(7)), Duration(-2));
874 test1!"%="(Duration(5), (cast(E)Duration(7)), Duration(5));
875 test1!"+="(Duration(7), (cast(E)Duration(5)), Duration(12));
876 test1!"-="(Duration(7), (cast(E)Duration(5)), Duration(2));
877 test1!"%="(Duration(7), (cast(E)Duration(5)), Duration(2));
878
879 test1!"+="(Duration(5), (cast(E)Duration(-7)), Duration(-2));
880 test1!"-="(Duration(5), (cast(E)Duration(-7)), Duration(12));
881 test1!"%="(Duration(5), (cast(E)Duration(-7)), Duration(5));
882 test1!"+="(Duration(7), (cast(E)Duration(-5)), Duration(2));
883 test1!"-="(Duration(7), (cast(E)Duration(-5)), Duration(12));
884 test1!"%="(Duration(7), (cast(E)Duration(-5)), Duration(2));
885
886 test1!"+="(Duration(-5), (cast(E)Duration(7)), Duration(2));
887 test1!"-="(Duration(-5), (cast(E)Duration(7)), Duration(-12));
888 test1!"%="(Duration(-5), (cast(E)Duration(7)), Duration(-5));
889 test1!"+="(Duration(-7), (cast(E)Duration(5)), Duration(-2));
890 test1!"-="(Duration(-7), (cast(E)Duration(5)), Duration(-12));
891 test1!"%="(Duration(-7), (cast(E)Duration(5)), Duration(-2));
892
893 test1!"+="(Duration(-5), (cast(E)Duration(-7)), Duration(-12));
894 test1!"-="(Duration(-5), (cast(E)Duration(-7)), Duration(2));
895 test1!"%="(Duration(-5), (cast(E)Duration(-7)), Duration(-5));
896 test1!"+="(Duration(-7), (cast(E)Duration(-5)), Duration(-12));
897 test1!"-="(Duration(-7), (cast(E)Duration(-5)), Duration(-2));
898 test1!"%="(Duration(-7), (cast(E)Duration(-5)), Duration(-2));
899 }
900
901 foreach (D; AliasSeq!(const Duration, immutable Duration))
902 {
903 foreach (E; AliasSeq!(Duration, const Duration, immutable Duration))
904 {
905 D lhs = D(120);
906 E rhs = E(120);
907 static assert(!__traits(compiles, lhs += rhs), D.stringof ~ " " ~ E.stringof);
908 }
909 }
910 }
911
912 version (CoreUnittest) deprecated unittest
913 {
914 static void test2(string op, E)
915 (Duration actual, in E rhs, Duration lower, Duration upper, size_t line = __LINE__)
916 {
917 assertApprox(mixin("actual " ~ op ~ " rhs"), lower, upper, "op failed", line);
918 assertApprox(actual, lower, upper, "op assign failed", line);
919 }
920
921 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
922 {
923 test2!"+="(Duration(5), cast(T)TickDuration.from!"usecs"(7), Duration(70), Duration(80));
924 test2!"-="(Duration(5), cast(T)TickDuration.from!"usecs"(7), Duration(-70), Duration(-60));
925 test2!"+="(Duration(7), cast(T)TickDuration.from!"usecs"(5), Duration(52), Duration(62));
926 test2!"-="(Duration(7), cast(T)TickDuration.from!"usecs"(5), Duration(-48), Duration(-38));
927
928 test2!"+="(Duration(5), cast(T)TickDuration.from!"usecs"(-7), Duration(-70), Duration(-60));
929 test2!"-="(Duration(5), cast(T)TickDuration.from!"usecs"(-7), Duration(70), Duration(80));
930 test2!"+="(Duration(7), cast(T)TickDuration.from!"usecs"(-5), Duration(-48), Duration(-38));
931 test2!"-="(Duration(7), cast(T)TickDuration.from!"usecs"(-5), Duration(52), Duration(62));
932
933 test2!"+="(Duration(-5), cast(T)TickDuration.from!"usecs"(7), Duration(60), Duration(70));
934 test2!"-="(Duration(-5), cast(T)TickDuration.from!"usecs"(7), Duration(-80), Duration(-70));
935 test2!"+="(Duration(-7), cast(T)TickDuration.from!"usecs"(5), Duration(38), Duration(48));
936 test2!"-="(Duration(-7), cast(T)TickDuration.from!"usecs"(5), Duration(-62), Duration(-52));
937
938 test2!"+="(Duration(-5), cast(T)TickDuration.from!"usecs"(-7), Duration(-80), Duration(-70));
939 test2!"-="(Duration(-5), cast(T)TickDuration.from!"usecs"(-7), Duration(60), Duration(70));
940 test2!"+="(Duration(-7), cast(T)TickDuration.from!"usecs"(-5), Duration(-62), Duration(-52));
941 test2!"-="(Duration(-7), cast(T)TickDuration.from!"usecs"(-5), Duration(38), Duration(48));
942 }
943
944 foreach (D; AliasSeq!(const Duration, immutable Duration))
945 {
946 foreach (E; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
947 {
948 D lhs = D(120);
949 E rhs = E(120);
950 static assert(!__traits(compiles, lhs += rhs), D.stringof ~ " " ~ E.stringof);
951 }
952 }
953 }
954
955
956 /++
957 Multiplies or divides the duration by an integer value.
958
959 The legal types of arithmetic for $(D Duration) using this operator
960 overload are
961
962 $(TABLE
963 $(TR $(TD Duration) $(TD *) $(TD long) $(TD -->) $(TD Duration))
964 $(TR $(TD Duration) $(TD /) $(TD long) $(TD -->) $(TD Duration))
965 )
966
967 Params:
968 value = The value to multiply this $(D Duration) by.
969 +/
970 Duration opBinary(string op)(long value) const nothrow @nogc
971 if (op == "*" || op == "/")
972 {
973 mixin("return Duration(_hnsecs " ~ op ~ " value);");
974 }
975
976 version (CoreUnittest) unittest
977 {
978 foreach (D; AliasSeq!(Duration, const Duration, immutable Duration))
979 {
980 assert((cast(D)Duration(5)) * 7 == Duration(35));
981 assert((cast(D)Duration(7)) * 5 == Duration(35));
982
983 assert((cast(D)Duration(5)) * -7 == Duration(-35));
984 assert((cast(D)Duration(7)) * -5 == Duration(-35));
985
986 assert((cast(D)Duration(-5)) * 7 == Duration(-35));
987 assert((cast(D)Duration(-7)) * 5 == Duration(-35));
988
989 assert((cast(D)Duration(-5)) * -7 == Duration(35));
990 assert((cast(D)Duration(-7)) * -5 == Duration(35));
991
992 assert((cast(D)Duration(5)) * 0 == Duration(0));
993 assert((cast(D)Duration(-5)) * 0 == Duration(0));
994 }
995 }
996
997 version (CoreUnittest) unittest
998 {
999 foreach (D; AliasSeq!(Duration, const Duration, immutable Duration))
1000 {
1001 assert((cast(D)Duration(5)) / 7 == Duration(0));
1002 assert((cast(D)Duration(7)) / 5 == Duration(1));
1003
1004 assert((cast(D)Duration(5)) / -7 == Duration(0));
1005 assert((cast(D)Duration(7)) / -5 == Duration(-1));
1006
1007 assert((cast(D)Duration(-5)) / 7 == Duration(0));
1008 assert((cast(D)Duration(-7)) / 5 == Duration(-1));
1009
1010 assert((cast(D)Duration(-5)) / -7 == Duration(0));
1011 assert((cast(D)Duration(-7)) / -5 == Duration(1));
1012 }
1013 }
1014
1015
1016 /++
1017 Multiplies/Divides the duration by an integer value as well as
1018 assigning the result to this $(D Duration).
1019
1020 The legal types of arithmetic for $(D Duration) using this operator
1021 overload are
1022
1023 $(TABLE
1024 $(TR $(TD Duration) $(TD *) $(TD long) $(TD -->) $(TD Duration))
1025 $(TR $(TD Duration) $(TD /) $(TD long) $(TD -->) $(TD Duration))
1026 )
1027
1028 Params:
1029 value = The value to multiply/divide this $(D Duration) by.
1030 +/
1031 ref Duration opOpAssign(string op)(long value) nothrow @nogc
1032 if (op == "*" || op == "/")
1033 {
1034 mixin("_hnsecs " ~ op ~ "= value;");
1035 return this;
1036 }
1037
1038 version (CoreUnittest) unittest
1039 {
1040 static void test(D)(D actual, long value, Duration expected, size_t line = __LINE__)
1041 {
1042 if ((actual *= value) != expected)
1043 throw new AssertError("op failed", __FILE__, line);
1044
1045 if (actual != expected)
1046 throw new AssertError("op assign failed", __FILE__, line);
1047 }
1048
1049 test(Duration(5), 7, Duration(35));
1050 test(Duration(7), 5, Duration(35));
1051
1052 test(Duration(5), -7, Duration(-35));
1053 test(Duration(7), -5, Duration(-35));
1054
1055 test(Duration(-5), 7, Duration(-35));
1056 test(Duration(-7), 5, Duration(-35));
1057
1058 test(Duration(-5), -7, Duration(35));
1059 test(Duration(-7), -5, Duration(35));
1060
1061 test(Duration(5), 0, Duration(0));
1062 test(Duration(-5), 0, Duration(0));
1063
1064 const cdur = Duration(12);
1065 immutable idur = Duration(12);
1066 static assert(!__traits(compiles, cdur *= 12));
1067 static assert(!__traits(compiles, idur *= 12));
1068 }
1069
1070 version (CoreUnittest) unittest
1071 {
1072 static void test(Duration actual, long value, Duration expected, size_t line = __LINE__)
1073 {
1074 if ((actual /= value) != expected)
1075 throw new AssertError("op failed", __FILE__, line);
1076
1077 if (actual != expected)
1078 throw new AssertError("op assign failed", __FILE__, line);
1079 }
1080
1081 test(Duration(5), 7, Duration(0));
1082 test(Duration(7), 5, Duration(1));
1083
1084 test(Duration(5), -7, Duration(0));
1085 test(Duration(7), -5, Duration(-1));
1086
1087 test(Duration(-5), 7, Duration(0));
1088 test(Duration(-7), 5, Duration(-1));
1089
1090 test(Duration(-5), -7, Duration(0));
1091 test(Duration(-7), -5, Duration(1));
1092
1093 const cdur = Duration(12);
1094 immutable idur = Duration(12);
1095 static assert(!__traits(compiles, cdur /= 12));
1096 static assert(!__traits(compiles, idur /= 12));
1097 }
1098
1099
1100 /++
1101 Divides two durations.
1102
1103 The legal types of arithmetic for $(D Duration) using this operator are
1104
1105 $(TABLE
1106 $(TR $(TD Duration) $(TD /) $(TD Duration) $(TD -->) $(TD long))
1107 )
1108
1109 Params:
1110 rhs = The duration to divide this $(D Duration) by.
1111 +/
1112 long opBinary(string op)(Duration rhs) const nothrow @nogc
1113 if (op == "/")
1114 {
1115 return _hnsecs / rhs._hnsecs;
1116 }
1117
1118 version (CoreUnittest) unittest
1119 {
1120 assert(Duration(5) / Duration(7) == 0);
1121 assert(Duration(7) / Duration(5) == 1);
1122 assert(Duration(8) / Duration(4) == 2);
1123
1124 assert(Duration(5) / Duration(-7) == 0);
1125 assert(Duration(7) / Duration(-5) == -1);
1126 assert(Duration(8) / Duration(-4) == -2);
1127
1128 assert(Duration(-5) / Duration(7) == 0);
1129 assert(Duration(-7) / Duration(5) == -1);
1130 assert(Duration(-8) / Duration(4) == -2);
1131
1132 assert(Duration(-5) / Duration(-7) == 0);
1133 assert(Duration(-7) / Duration(-5) == 1);
1134 assert(Duration(-8) / Duration(-4) == 2);
1135 }
1136
1137
1138 /++
1139 Multiplies an integral value and a $(D Duration).
1140
1141 The legal types of arithmetic for $(D Duration) using this operator
1142 overload are
1143
1144 $(TABLE
1145 $(TR $(TD long) $(TD *) $(TD Duration) $(TD -->) $(TD Duration))
1146 )
1147
1148 Params:
1149 value = The number of units to multiply this $(D Duration) by.
1150 +/
1151 Duration opBinaryRight(string op)(long value) const nothrow @nogc
1152 if (op == "*")
1153 {
1154 return opBinary!op(value);
1155 }
1156
1157 version (CoreUnittest) unittest
1158 {
1159 foreach (D; AliasSeq!(Duration, const Duration, immutable Duration))
1160 {
1161 assert(5 * cast(D)Duration(7) == Duration(35));
1162 assert(7 * cast(D)Duration(5) == Duration(35));
1163
1164 assert(5 * cast(D)Duration(-7) == Duration(-35));
1165 assert(7 * cast(D)Duration(-5) == Duration(-35));
1166
1167 assert(-5 * cast(D)Duration(7) == Duration(-35));
1168 assert(-7 * cast(D)Duration(5) == Duration(-35));
1169
1170 assert(-5 * cast(D)Duration(-7) == Duration(35));
1171 assert(-7 * cast(D)Duration(-5) == Duration(35));
1172
1173 assert(0 * cast(D)Duration(-5) == Duration(0));
1174 assert(0 * cast(D)Duration(5) == Duration(0));
1175 }
1176 }
1177
1178
1179 /++
1180 Returns the negation of this $(D Duration).
1181 +/
1182 Duration opUnary(string op)() const nothrow @nogc
1183 if (op == "-")
1184 {
1185 return Duration(-_hnsecs);
1186 }
1187
1188 version (CoreUnittest) unittest
1189 {
1190 foreach (D; AliasSeq!(Duration, const Duration, immutable Duration))
1191 {
1192 assert(-(cast(D)Duration(7)) == Duration(-7));
1193 assert(-(cast(D)Duration(5)) == Duration(-5));
1194 assert(-(cast(D)Duration(-7)) == Duration(7));
1195 assert(-(cast(D)Duration(-5)) == Duration(5));
1196 assert(-(cast(D)Duration(0)) == Duration(0));
1197 }
1198 }
1199
1200
1201 /++
1202 $(RED TickDuration is Deprecated)
1203
1204 Returns a $(LREF TickDuration) with the same number of hnsecs as this
1205 $(D Duration).
1206 Note that the conventional way to convert between $(D Duration) and
1207 $(D TickDuration) is using $(REF to, std,conv), e.g.:
1208 $(D duration.to!TickDuration())
1209 +/
1210 deprecated TickDuration opCast(T)() const nothrow @nogc
1211 if (is(immutable T == immutable TickDuration))
1212 {
1213 return TickDuration.from!"hnsecs"(_hnsecs);
1214 }
1215
1216 version (CoreUnittest) deprecated unittest
1217 {
1218 foreach (D; AliasSeq!(Duration, const Duration, immutable Duration))
1219 {
1220 foreach (units; AliasSeq!("seconds", "msecs", "usecs", "hnsecs"))
1221 {
1222 enum unitsPerSec = convert!("seconds", units)(1);
1223
1224 if (TickDuration.ticksPerSec >= unitsPerSec)
1225 {
1226 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
1227 {
1228 auto t = TickDuration.from!units(1);
1229 assertApprox(cast(T)cast(D)dur!units(1), t - TickDuration(1), t + TickDuration(1), units);
1230 t = TickDuration.from!units(2);
1231 assertApprox(cast(T)cast(D)dur!units(2), t - TickDuration(1), t + TickDuration(1), units);
1232 }
1233 }
1234 else
1235 {
1236 auto t = TickDuration.from!units(1);
1237 assert(t.to!(units, long)() == 0, units);
1238 t = TickDuration.from!units(1_000_000);
1239 assert(t.to!(units, long)() >= 900_000, units);
1240 assert(t.to!(units, long)() <= 1_100_000, units);
1241 }
1242 }
1243 }
1244 }
1245
1246 /++
1247 Allow Duration to be used as a boolean.
1248 Returns: `true` if this duration is non-zero.
1249 +/
1250 bool opCast(T : bool)() const nothrow @nogc
1251 {
1252 return _hnsecs != 0;
1253 }
1254
1255 version (CoreUnittest) unittest
1256 {
1257 auto d = 10.minutes;
1258 assert(d);
1259 assert(!(d - d));
1260 assert(d + d);
1261 }
1262
1263 //Temporary hack until bug http://d.puremagic.com/issues/show_bug.cgi?id=5747 is fixed.
1264 Duration opCast(T)() const nothrow @nogc
1265 if (is(immutable T == immutable Duration))
1266 {
1267 return this;
1268 }
1269
1270
1271 /++
1272 Splits out the Duration into the given units.
1273
1274 split takes the list of time units to split out as template arguments.
1275 The time unit strings must be given in decreasing order. How it returns
1276 the values for those units depends on the overload used.
1277
1278 The overload which accepts function arguments takes integral types in
1279 the order that the time unit strings were given, and those integers are
1280 passed by $(D ref). split assigns the values for the units to each
1281 corresponding integer. Any integral type may be used, but no attempt is
1282 made to prevent integer overflow, so don't use small integral types in
1283 circumstances where the values for those units aren't likely to fit in
1284 an integral type that small.
1285
1286 The overload with no arguments returns the values for the units in a
1287 struct with members whose names are the same as the given time unit
1288 strings. The members are all $(D long)s. This overload will also work
1289 with no time strings being given, in which case $(I all) of the time
1290 units from weeks through hnsecs will be provided (but no nsecs, since it
1291 would always be $(D 0)).
1292
1293 For both overloads, the entire value of the Duration is split among the
1294 units (rather than splitting the Duration across all units and then only
1295 providing the values for the requested units), so if only one unit is
1296 given, the result is equivalent to $(LREF total).
1297
1298 $(D "nsecs") is accepted by split, but $(D "years") and $(D "months")
1299 are not.
1300
1301 For negative durations, all of the split values will be negative.
1302 +/
1303 template split(units...)
1304 if (allAreAcceptedUnits!("weeks", "days", "hours", "minutes", "seconds",
1305 "msecs", "usecs", "hnsecs", "nsecs")([units]) &&
1306 unitsAreInDescendingOrder([units]))
1307 {
1308 /++ Ditto +/
1309 void split(Args...)(out Args args) const nothrow @nogc
1310 if (units.length != 0 && args.length == units.length && allAreMutableIntegralTypes!Args)
1311 {
1312 long hnsecs = _hnsecs;
1313 foreach (i, unit; units)
1314 {
1315 static if (unit == "nsecs")
1316 args[i] = cast(Args[i])convert!("hnsecs", "nsecs")(hnsecs);
1317 else
1318 args[i] = cast(Args[i])splitUnitsFromHNSecs!unit(hnsecs);
1319 }
1320 }
1321
1322 /++ Ditto +/
1323 auto split() const nothrow @nogc
1324 {
1325 static if (units.length == 0)
1326 return split!("weeks", "days", "hours", "minutes", "seconds", "msecs", "usecs", "hnsecs")();
1327 else
1328 {
1329 static string genMemberDecls()
1330 {
1331 string retval;
1332 foreach (unit; units)
1333 {
1334 retval ~= "long ";
1335 retval ~= unit;
1336 retval ~= "; ";
1337 }
1338 return retval;
1339 }
1340
1341 static struct SplitUnits
1342 {
1343 mixin(genMemberDecls());
1344 }
1345
1346 static string genSplitCall()
1347 {
1348 auto retval = "split(";
1349 foreach (i, unit; units)
1350 {
1351 retval ~= "su.";
1352 retval ~= unit;
1353 if (i < units.length - 1)
1354 retval ~= ", ";
1355 else
1356 retval ~= ");";
1357 }
1358 return retval;
1359 }
1360
1361 SplitUnits su = void;
1362 mixin(genSplitCall());
1363 return su;
1364 }
1365 }
1366
1367 /+
1368 Whether all of the given arguments are integral types.
1369 +/
1370 private template allAreMutableIntegralTypes(Args...)
1371 {
1372 static if (Args.length == 0)
1373 enum allAreMutableIntegralTypes = true;
1374 else static if (!is(Args[0] == long) &&
1375 !is(Args[0] == int) &&
1376 !is(Args[0] == short) &&
1377 !is(Args[0] == byte) &&
1378 !is(Args[0] == ulong) &&
1379 !is(Args[0] == uint) &&
1380 !is(Args[0] == ushort) &&
1381 !is(Args[0] == ubyte))
1382 {
1383 enum allAreMutableIntegralTypes = false;
1384 }
1385 else
1386 enum allAreMutableIntegralTypes = allAreMutableIntegralTypes!(Args[1 .. $]);
1387 }
1388
1389 version (CoreUnittest) unittest
1390 {
1391 foreach (T; AliasSeq!(long, int, short, byte, ulong, uint, ushort, ubyte))
1392 static assert(allAreMutableIntegralTypes!T);
1393 foreach (T; AliasSeq!(long, int, short, byte, ulong, uint, ushort, ubyte))
1394 static assert(!allAreMutableIntegralTypes!(const T));
1395 foreach (T; AliasSeq!(char, wchar, dchar, float, double, real, string))
1396 static assert(!allAreMutableIntegralTypes!T);
1397 static assert(allAreMutableIntegralTypes!(long, int, short, byte));
1398 static assert(!allAreMutableIntegralTypes!(long, int, short, char, byte));
1399 static assert(!allAreMutableIntegralTypes!(long, int*, short));
1400 }
1401 }
1402
1403 ///
1404 unittest
1405 {
1406 {
1407 auto d = dur!"days"(12) + dur!"minutes"(7) + dur!"usecs"(501223);
1408 long days;
1409 int seconds;
1410 short msecs;
1411 d.split!("days", "seconds", "msecs")(days, seconds, msecs);
1412 assert(days == 12);
1413 assert(seconds == 7 * 60);
1414 assert(msecs == 501);
1415
1416 auto splitStruct = d.split!("days", "seconds", "msecs")();
1417 assert(splitStruct.days == 12);
1418 assert(splitStruct.seconds == 7 * 60);
1419 assert(splitStruct.msecs == 501);
1420
1421 auto fullSplitStruct = d.split();
1422 assert(fullSplitStruct.weeks == 1);
1423 assert(fullSplitStruct.days == 5);
1424 assert(fullSplitStruct.hours == 0);
1425 assert(fullSplitStruct.minutes == 7);
1426 assert(fullSplitStruct.seconds == 0);
1427 assert(fullSplitStruct.msecs == 501);
1428 assert(fullSplitStruct.usecs == 223);
1429 assert(fullSplitStruct.hnsecs == 0);
1430
1431 assert(d.split!"minutes"().minutes == d.total!"minutes");
1432 }
1433
1434 {
1435 auto d = dur!"days"(12);
1436 assert(d.split!"weeks"().weeks == 1);
1437 assert(d.split!"days"().days == 12);
1438
1439 assert(d.split().weeks == 1);
1440 assert(d.split().days == 5);
1441 }
1442
1443 {
1444 auto d = dur!"days"(7) + dur!"hnsecs"(42);
1445 assert(d.split!("seconds", "nsecs")().nsecs == 4200);
1446 }
1447
1448 {
1449 auto d = dur!"days"(-7) + dur!"hours"(-9);
1450 auto result = d.split!("days", "hours")();
1451 assert(result.days == -7);
1452 assert(result.hours == -9);
1453 }
1454 }
1455
1456 version (CoreUnittest) pure nothrow unittest
1457 {
1458 foreach (D; AliasSeq!(const Duration, immutable Duration))
1459 {
1460 D d = dur!"weeks"(3) + dur!"days"(5) + dur!"hours"(19) + dur!"minutes"(7) +
1461 dur!"seconds"(2) + dur!"hnsecs"(1234567);
1462 byte weeks;
1463 ubyte days;
1464 short hours;
1465 ushort minutes;
1466 int seconds;
1467 uint msecs;
1468 long usecs;
1469 ulong hnsecs;
1470 long nsecs;
1471
1472 d.split!("weeks", "days", "hours", "minutes", "seconds", "msecs", "usecs", "hnsecs", "nsecs")
1473 (weeks, days, hours, minutes, seconds, msecs, usecs, hnsecs, nsecs);
1474 assert(weeks == 3);
1475 assert(days == 5);
1476 assert(hours == 19);
1477 assert(minutes == 7);
1478 assert(seconds == 2);
1479 assert(msecs == 123);
1480 assert(usecs == 456);
1481 assert(hnsecs == 7);
1482 assert(nsecs == 0);
1483
1484 d.split!("weeks", "days", "hours", "seconds", "usecs")(weeks, days, hours, seconds, usecs);
1485 assert(weeks == 3);
1486 assert(days == 5);
1487 assert(hours == 19);
1488 assert(seconds == 422);
1489 assert(usecs == 123456);
1490
1491 d.split!("days", "minutes", "seconds", "nsecs")(days, minutes, seconds, nsecs);
1492 assert(days == 26);
1493 assert(minutes == 1147);
1494 assert(seconds == 2);
1495 assert(nsecs == 123456700);
1496
1497 d.split!("minutes", "msecs", "usecs", "hnsecs")(minutes, msecs, usecs, hnsecs);
1498 assert(minutes == 38587);
1499 assert(msecs == 2123);
1500 assert(usecs == 456);
1501 assert(hnsecs == 7);
1502
1503 {
1504 auto result = d.split!("weeks", "days", "hours", "minutes", "seconds",
1505 "msecs", "usecs", "hnsecs", "nsecs");
1506 assert(result.weeks == 3);
1507 assert(result.days == 5);
1508 assert(result.hours == 19);
1509 assert(result.minutes == 7);
1510 assert(result.seconds == 2);
1511 assert(result.msecs == 123);
1512 assert(result.usecs == 456);
1513 assert(result.hnsecs == 7);
1514 assert(result.nsecs == 0);
1515 }
1516
1517 {
1518 auto result = d.split!("weeks", "days", "hours", "seconds", "usecs");
1519 assert(result.weeks == 3);
1520 assert(result.days == 5);
1521 assert(result.hours == 19);
1522 assert(result.seconds == 422);
1523 assert(result.usecs == 123456);
1524 }
1525
1526 {
1527 auto result = d.split!("days", "minutes", "seconds", "nsecs")();
1528 assert(result.days == 26);
1529 assert(result.minutes == 1147);
1530 assert(result.seconds == 2);
1531 assert(result.nsecs == 123456700);
1532 }
1533
1534 {
1535 auto result = d.split!("minutes", "msecs", "usecs", "hnsecs")();
1536 assert(result.minutes == 38587);
1537 assert(result.msecs == 2123);
1538 assert(result.usecs == 456);
1539 assert(result.hnsecs == 7);
1540 }
1541
1542 {
1543 auto result = d.split();
1544 assert(result.weeks == 3);
1545 assert(result.days == 5);
1546 assert(result.hours == 19);
1547 assert(result.minutes == 7);
1548 assert(result.seconds == 2);
1549 assert(result.msecs == 123);
1550 assert(result.usecs == 456);
1551 assert(result.hnsecs == 7);
1552 static assert(!is(typeof(result.nsecs)));
1553 }
1554
1555 static assert(!is(typeof(d.split("seconds", "hnsecs")(seconds))));
1556 static assert(!is(typeof(d.split("hnsecs", "seconds", "minutes")(hnsecs, seconds, minutes))));
1557 static assert(!is(typeof(d.split("hnsecs", "seconds", "msecs")(hnsecs, seconds, msecs))));
1558 static assert(!is(typeof(d.split("seconds", "hnecs", "msecs")(seconds, hnsecs, msecs))));
1559 static assert(!is(typeof(d.split("seconds", "msecs", "msecs")(seconds, msecs, msecs))));
1560 static assert(!is(typeof(d.split("hnsecs", "seconds", "minutes")())));
1561 static assert(!is(typeof(d.split("hnsecs", "seconds", "msecs")())));
1562 static assert(!is(typeof(d.split("seconds", "hnecs", "msecs")())));
1563 static assert(!is(typeof(d.split("seconds", "msecs", "msecs")())));
1564 alias AliasSeq!("nsecs", "hnsecs", "usecs", "msecs", "seconds",
1565 "minutes", "hours", "days", "weeks") timeStrs;
1566 foreach (i, str; timeStrs[1 .. $])
1567 static assert(!is(typeof(d.split!(timeStrs[i - 1], str)())));
1568
1569 D nd = -d;
1570
1571 {
1572 auto result = nd.split();
1573 assert(result.weeks == -3);
1574 assert(result.days == -5);
1575 assert(result.hours == -19);
1576 assert(result.minutes == -7);
1577 assert(result.seconds == -2);
1578 assert(result.msecs == -123);
1579 assert(result.usecs == -456);
1580 assert(result.hnsecs == -7);
1581 }
1582
1583 {
1584 auto result = nd.split!("weeks", "days", "hours", "minutes", "seconds", "nsecs")();
1585 assert(result.weeks == -3);
1586 assert(result.days == -5);
1587 assert(result.hours == -19);
1588 assert(result.minutes == -7);
1589 assert(result.seconds == -2);
1590 assert(result.nsecs == -123456700);
1591 }
1592 }
1593 }
1594
1595
1596 /++
1597 Returns the total number of the given units in this $(D Duration).
1598 So, unlike $(D split), it does not strip out the larger units.
1599 +/
1600 @property long total(string units)() const nothrow @nogc
1601 if (units == "weeks" ||
1602 units == "days" ||
1603 units == "hours" ||
1604 units == "minutes" ||
1605 units == "seconds" ||
1606 units == "msecs" ||
1607 units == "usecs" ||
1608 units == "hnsecs" ||
1609 units == "nsecs")
1610 {
1611 return convert!("hnsecs", units)(_hnsecs);
1612 }
1613
1614 ///
1615 unittest
1616 {
1617 assert(dur!"weeks"(12).total!"weeks" == 12);
1618 assert(dur!"weeks"(12).total!"days" == 84);
1619
1620 assert(dur!"days"(13).total!"weeks" == 1);
1621 assert(dur!"days"(13).total!"days" == 13);
1622
1623 assert(dur!"hours"(49).total!"days" == 2);
1624 assert(dur!"hours"(49).total!"hours" == 49);
1625
1626 assert(dur!"nsecs"(2007).total!"hnsecs" == 20);
1627 assert(dur!"nsecs"(2007).total!"nsecs" == 2000);
1628 }
1629
1630 version (CoreUnittest) unittest
1631 {
1632 foreach (D; AliasSeq!(const Duration, immutable Duration))
1633 {
1634 assert((cast(D)dur!"weeks"(12)).total!"weeks" == 12);
1635 assert((cast(D)dur!"weeks"(12)).total!"days" == 84);
1636
1637 assert((cast(D)dur!"days"(13)).total!"weeks" == 1);
1638 assert((cast(D)dur!"days"(13)).total!"days" == 13);
1639
1640 assert((cast(D)dur!"hours"(49)).total!"days" == 2);
1641 assert((cast(D)dur!"hours"(49)).total!"hours" == 49);
1642
1643 assert((cast(D)dur!"nsecs"(2007)).total!"hnsecs" == 20);
1644 assert((cast(D)dur!"nsecs"(2007)).total!"nsecs" == 2000);
1645 }
1646 }
1647
1648 /// Ditto
1649 string toString() const scope nothrow
1650 {
1651 string result;
1652 this.toString((in char[] data) { result ~= data; });
1653 return result;
1654 }
1655
1656 ///
1657 unittest
1658 {
1659 assert(Duration.zero.toString() == "0 hnsecs");
1660 assert(weeks(5).toString() == "5 weeks");
1661 assert(days(2).toString() == "2 days");
1662 assert(hours(1).toString() == "1 hour");
1663 assert(minutes(19).toString() == "19 minutes");
1664 assert(seconds(42).toString() == "42 secs");
1665 assert(msecs(42).toString() == "42 ms");
1666 assert(usecs(27).toString() == "27 μs");
1667 assert(hnsecs(5).toString() == "5 hnsecs");
1668
1669 assert(seconds(121).toString() == "2 minutes and 1 sec");
1670 assert((minutes(5) + seconds(3) + usecs(4)).toString() ==
1671 "5 minutes, 3 secs, and 4 μs");
1672
1673 assert(seconds(-42).toString() == "-42 secs");
1674 assert(usecs(-5239492).toString() == "-5 secs, -239 ms, and -492 μs");
1675 }
1676
1677 version (CoreUnittest) unittest
1678 {
1679 foreach (D; AliasSeq!(Duration, const Duration, immutable Duration))
1680 {
1681 assert((cast(D)Duration(0)).toString() == "0 hnsecs");
1682 assert((cast(D)Duration(1)).toString() == "1 hnsec");
1683 assert((cast(D)Duration(7)).toString() == "7 hnsecs");
1684 assert((cast(D)Duration(10)).toString() == "1 μs");
1685 assert((cast(D)Duration(20)).toString() == "2 μs");
1686 assert((cast(D)Duration(10_000)).toString() == "1 ms");
1687 assert((cast(D)Duration(20_000)).toString() == "2 ms");
1688 assert((cast(D)Duration(10_000_000)).toString() == "1 sec");
1689 assert((cast(D)Duration(20_000_000)).toString() == "2 secs");
1690 assert((cast(D)Duration(600_000_000)).toString() == "1 minute");
1691 assert((cast(D)Duration(1_200_000_000)).toString() == "2 minutes");
1692 assert((cast(D)Duration(36_000_000_000)).toString() == "1 hour");
1693 assert((cast(D)Duration(72_000_000_000)).toString() == "2 hours");
1694 assert((cast(D)Duration(864_000_000_000)).toString() == "1 day");
1695 assert((cast(D)Duration(1_728_000_000_000)).toString() == "2 days");
1696 assert((cast(D)Duration(6_048_000_000_000)).toString() == "1 week");
1697 assert((cast(D)Duration(12_096_000_000_000)).toString() == "2 weeks");
1698
1699 assert((cast(D)Duration(12)).toString() == "1 μs and 2 hnsecs");
1700 assert((cast(D)Duration(120_795)).toString() == "12 ms, 79 μs, and 5 hnsecs");
1701 assert((cast(D)Duration(12_096_020_900_003)).toString() == "2 weeks, 2 secs, 90 ms, and 3 hnsecs");
1702
1703 assert((cast(D)Duration(-1)).toString() == "-1 hnsecs");
1704 assert((cast(D)Duration(-7)).toString() == "-7 hnsecs");
1705 assert((cast(D)Duration(-10)).toString() == "-1 μs");
1706 assert((cast(D)Duration(-20)).toString() == "-2 μs");
1707 assert((cast(D)Duration(-10_000)).toString() == "-1 ms");
1708 assert((cast(D)Duration(-20_000)).toString() == "-2 ms");
1709 assert((cast(D)Duration(-10_000_000)).toString() == "-1 secs");
1710 assert((cast(D)Duration(-20_000_000)).toString() == "-2 secs");
1711 assert((cast(D)Duration(-600_000_000)).toString() == "-1 minutes");
1712 assert((cast(D)Duration(-1_200_000_000)).toString() == "-2 minutes");
1713 assert((cast(D)Duration(-36_000_000_000)).toString() == "-1 hours");
1714 assert((cast(D)Duration(-72_000_000_000)).toString() == "-2 hours");
1715 assert((cast(D)Duration(-864_000_000_000)).toString() == "-1 days");
1716 assert((cast(D)Duration(-1_728_000_000_000)).toString() == "-2 days");
1717 assert((cast(D)Duration(-6_048_000_000_000)).toString() == "-1 weeks");
1718 assert((cast(D)Duration(-12_096_000_000_000)).toString() == "-2 weeks");
1719
1720 assert((cast(D)Duration(-12)).toString() == "-1 μs and -2 hnsecs");
1721 assert((cast(D)Duration(-120_795)).toString() == "-12 ms, -79 μs, and -5 hnsecs");
1722 assert((cast(D)Duration(-12_096_020_900_003)).toString() == "-2 weeks, -2 secs, -90 ms, and -3 hnsecs");
1723 }
1724 }
1725
1726
1727 /++
1728 Returns whether this $(D Duration) is negative.
1729 +/
1730 @property bool isNegative() const nothrow @nogc
1731 {
1732 return _hnsecs < 0;
1733 }
1734
1735 version (CoreUnittest) unittest
1736 {
1737 foreach (D; AliasSeq!(Duration, const Duration, immutable Duration))
1738 {
1739 assert(!(cast(D)Duration(100)).isNegative);
1740 assert(!(cast(D)Duration(1)).isNegative);
1741 assert(!(cast(D)Duration(0)).isNegative);
1742 assert((cast(D)Duration(-1)).isNegative);
1743 assert((cast(D)Duration(-100)).isNegative);
1744 }
1745 }
1746
1747
1748 private:
1749
1750 /+
1751 Params:
1752 hnsecs = The total number of hecto-nanoseconds in this $(D Duration).
1753 +/
1754 this(long hnsecs) nothrow @nogc
1755 {
1756 _hnsecs = hnsecs;
1757 }
1758
1759
1760 long _hnsecs;
1761 }
1762
1763 ///
1764 unittest
1765 {
1766 import core.time;
1767
1768 // using the dur template
1769 auto numDays = dur!"days"(12);
1770
1771 // using the days function
1772 numDays = days(12);
1773
1774 // alternatively using UFCS syntax
1775 numDays = 12.days;
1776
1777 auto myTime = 100.msecs + 20_000.usecs + 30_000.hnsecs;
1778 assert(myTime == 123.msecs);
1779 }
1780
1781 // Ensure `toString` doesn't allocate if the sink doesn't
1782 version (CoreUnittest) @safe pure nothrow @nogc unittest
1783 {
1784 char[256] buffer; size_t len;
1785 scope sink = (in char[] data) {
1786 assert(data.length + len <= buffer.length);
1787 buffer[len .. len + data.length] = data[];
1788 len += data.length;
1789 };
1790 auto dur = Duration(-12_096_020_900_003);
1791 dur.toString(sink);
1792 assert(buffer[0 .. len] == "-2 weeks, -2 secs, -90 ms, and -3 hnsecs");
1793 }
1794
1795 /++
1796 $(RED TickDuration is DEPRECATED)
1797
1798 Converts a $(D TickDuration) to the given units as either an integral
1799 value or a floating point value.
1800
1801 Params:
1802 units = The units to convert to. Accepts $(D "seconds") and smaller
1803 only.
1804 T = The type to convert to (either an integral type or a
1805 floating point type).
1806
1807 td = The TickDuration to convert
1808 +/
1809 deprecated("TickDuration has been deprecated, please use Duration or MonoTime instead")
1810 T to(string units, T, D)(D td) @safe pure nothrow @nogc
1811 if (is(immutable D == immutable TickDuration) &&
1812 (units == "seconds" ||
1813 units == "msecs" ||
1814 units == "usecs" ||
1815 units == "hnsecs" ||
1816 units == "nsecs"))
1817 {
1818 static if (__traits(isIntegral, T) && T.sizeof >= 4)
1819 {
1820 enum unitsPerSec = convert!("seconds", units)(1);
1821
1822 return cast(T) (td.length / (TickDuration.ticksPerSec / cast(real) unitsPerSec));
1823 }
1824 else static if (__traits(isFloating, T))
1825 {
1826 static if (units == "seconds")
1827 return td.length / cast(T)TickDuration.ticksPerSec;
1828 else
1829 {
1830 enum unitsPerSec = convert!("seconds", units)(1);
1831
1832 return cast(T) (td.length /
1833 (TickDuration.ticksPerSec / cast(real) unitsPerSec));
1834 }
1835 }
1836 else
1837 static assert(0, "Incorrect template constraint.");
1838 }
1839
1840 ///
1841 deprecated unittest
1842 {
1843 auto t = TickDuration.from!"seconds"(1000);
1844
1845 long tl = to!("seconds",long)(t);
1846 assert(tl == 1000);
1847
1848 import core.stdc.math : fabs;
1849 double td = to!("seconds",double)(t);
1850 assert(fabs(td - 1000) < 0.001);
1851 }
1852
1853 deprecated unittest
1854 {
1855 void testFun(string U)() {
1856 auto t1v = 1000;
1857 auto t2v = 333;
1858
1859 auto t1 = TickDuration.from!U(t1v);
1860 auto t2 = TickDuration.from!U(t2v);
1861
1862 auto _str(F)(F val)
1863 {
1864 static if (is(F == int) || is(F == long))
1865 return signedToTempString(val);
1866 else
1867 return unsignedToTempString(val);
1868 }
1869
1870 foreach (F; AliasSeq!(int,uint,long,ulong,float,double,real))
1871 {
1872 F t1f = to!(U,F)(t1);
1873 F t2f = to!(U,F)(t2);
1874 auto t12d = t1 / t2v;
1875 auto t12m = t1 - t2;
1876 F t3f = to!(U,F)(t12d);
1877 F t4f = to!(U,F)(t12m);
1878
1879
1880 static if (is(F == float) || is(F == double) || is(F == real))
1881 {
1882 assert((t1f - cast(F)t1v) <= 3.0,
1883 F.stringof ~ " " ~ U ~ " " ~ doubleToString(t1f) ~ " " ~
1884 doubleToString(cast(F)t1v)
1885 );
1886 assert((t2f - cast(F)t2v) <= 3.0,
1887 F.stringof ~ " " ~ U ~ " " ~ doubleToString(t2f) ~ " " ~
1888 doubleToString(cast(F)t2v)
1889 );
1890 assert(t3f - (cast(F)t1v) / (cast(F)t2v) <= 3.0,
1891 F.stringof ~ " " ~ U ~ " " ~ doubleToString(t3f) ~ " " ~
1892 doubleToString((cast(F)t1v)/(cast(F)t2v))
1893 );
1894 assert(t4f - (cast(F)(t1v - t2v)) <= 3.0,
1895 F.stringof ~ " " ~ U ~ " " ~ doubleToString(t4f) ~ " " ~
1896 doubleToString(cast(F)(t1v - t2v))
1897 );
1898 }
1899 else
1900 {
1901 // even though this should be exact math it is not as internal
1902 // in "to" floating point is used
1903 assert(_abs(t1f) - _abs(cast(F)t1v) <= 3,
1904 F.stringof ~ " " ~ U ~ " " ~ _str(t1f) ~ " " ~
1905 _str(cast(F)t1v)
1906 );
1907 assert(_abs(t2f) - _abs(cast(F)t2v) <= 3,
1908 F.stringof ~ " " ~ U ~ " " ~ _str(t2f) ~ " " ~
1909 _str(cast(F)t2v)
1910 );
1911 assert(_abs(t3f) - _abs((cast(F)t1v) / (cast(F)t2v)) <= 3,
1912 F.stringof ~ " " ~ U ~ " " ~ _str(t3f) ~ " " ~
1913 _str((cast(F)t1v) / (cast(F)t2v))
1914 );
1915 assert(_abs(t4f) - _abs((cast(F)t1v) - (cast(F)t2v)) <= 3,
1916 F.stringof ~ " " ~ U ~ " " ~ _str(t4f) ~ " " ~
1917 _str((cast(F)t1v) - (cast(F)t2v))
1918 );
1919 }
1920 }
1921 }
1922
1923 testFun!"seconds"();
1924 testFun!"msecs"();
1925 testFun!"usecs"();
1926 }
1927
1928 /++
1929 These allow you to construct a $(D Duration) from the given time units
1930 with the given length.
1931
1932 You can either use the generic function $(D dur) and give it the units as
1933 a $(D string) or use the named aliases.
1934
1935 The possible values for units are $(D "weeks"), $(D "days"), $(D "hours"),
1936 $(D "minutes"), $(D "seconds"), $(D "msecs") (milliseconds), $(D "usecs"),
1937 (microseconds), $(D "hnsecs") (hecto-nanoseconds, i.e. 100 ns), and
1938 $(D "nsecs").
1939
1940 Params:
1941 units = The time units of the $(D Duration) (e.g. $(D "days")).
1942 length = The number of units in the $(D Duration).
1943 +/
1944 Duration dur(string units)(long length) @safe pure nothrow @nogc
1945 if (units == "weeks" ||
1946 units == "days" ||
1947 units == "hours" ||
1948 units == "minutes" ||
1949 units == "seconds" ||
1950 units == "msecs" ||
1951 units == "usecs" ||
1952 units == "hnsecs" ||
1953 units == "nsecs")
1954 {
1955 return Duration(convert!(units, "hnsecs")(length));
1956 }
1957
1958 alias weeks = dur!"weeks"; /// Ditto
1959 alias days = dur!"days"; /// Ditto
1960 alias hours = dur!"hours"; /// Ditto
1961 alias minutes = dur!"minutes"; /// Ditto
1962 alias seconds = dur!"seconds"; /// Ditto
1963 alias msecs = dur!"msecs"; /// Ditto
1964 alias usecs = dur!"usecs"; /// Ditto
1965 alias hnsecs = dur!"hnsecs"; /// Ditto
1966 alias nsecs = dur!"nsecs"; /// Ditto
1967
1968 ///
1969 unittest
1970 {
1971 // Generic
1972 assert(dur!"weeks"(142).total!"weeks" == 142);
1973 assert(dur!"days"(142).total!"days" == 142);
1974 assert(dur!"hours"(142).total!"hours" == 142);
1975 assert(dur!"minutes"(142).total!"minutes" == 142);
1976 assert(dur!"seconds"(142).total!"seconds" == 142);
1977 assert(dur!"msecs"(142).total!"msecs" == 142);
1978 assert(dur!"usecs"(142).total!"usecs" == 142);
1979 assert(dur!"hnsecs"(142).total!"hnsecs" == 142);
1980 assert(dur!"nsecs"(142).total!"nsecs" == 100);
1981
1982 // Non-generic
1983 assert(weeks(142).total!"weeks" == 142);
1984 assert(days(142).total!"days" == 142);
1985 assert(hours(142).total!"hours" == 142);
1986 assert(minutes(142).total!"minutes" == 142);
1987 assert(seconds(142).total!"seconds" == 142);
1988 assert(msecs(142).total!"msecs" == 142);
1989 assert(usecs(142).total!"usecs" == 142);
1990 assert(hnsecs(142).total!"hnsecs" == 142);
1991 assert(nsecs(142).total!"nsecs" == 100);
1992 }
1993
1994 unittest
1995 {
1996 foreach (D; AliasSeq!(Duration, const Duration, immutable Duration))
1997 {
1998 assert(dur!"weeks"(7).total!"weeks" == 7);
1999 assert(dur!"days"(7).total!"days" == 7);
2000 assert(dur!"hours"(7).total!"hours" == 7);
2001 assert(dur!"minutes"(7).total!"minutes" == 7);
2002 assert(dur!"seconds"(7).total!"seconds" == 7);
2003 assert(dur!"msecs"(7).total!"msecs" == 7);
2004 assert(dur!"usecs"(7).total!"usecs" == 7);
2005 assert(dur!"hnsecs"(7).total!"hnsecs" == 7);
2006 assert(dur!"nsecs"(7).total!"nsecs" == 0);
2007
2008 assert(dur!"weeks"(1007) == weeks(1007));
2009 assert(dur!"days"(1007) == days(1007));
2010 assert(dur!"hours"(1007) == hours(1007));
2011 assert(dur!"minutes"(1007) == minutes(1007));
2012 assert(dur!"seconds"(1007) == seconds(1007));
2013 assert(dur!"msecs"(1007) == msecs(1007));
2014 assert(dur!"usecs"(1007) == usecs(1007));
2015 assert(dur!"hnsecs"(1007) == hnsecs(1007));
2016 assert(dur!"nsecs"(10) == nsecs(10));
2017 }
2018 }
2019
2020 // used in MonoTimeImpl
2021 private string _clockTypeName(ClockType clockType)
2022 {
2023 final switch (clockType)
2024 {
2025 foreach (name; __traits(allMembers, ClockType))
2026 {
2027 case __traits(getMember, ClockType, name):
2028 return name;
2029 }
2030 }
2031 assert(0);
2032 }
2033
2034 // used in MonoTimeImpl
2035 private size_t _clockTypeIdx(ClockType clockType)
2036 {
2037 final switch (clockType)
2038 {
2039 foreach (i, name; __traits(allMembers, ClockType))
2040 {
2041 case __traits(getMember, ClockType, name):
2042 return i;
2043 }
2044 }
2045 assert(0);
2046 }
2047
2048
2049 /++
2050 alias for $(D MonoTimeImpl) instantiated with $(D ClockType.normal). This is
2051 what most programs should use. It's also what much of $(D MonoTimeImpl) uses
2052 in its documentation (particularly in the examples), because that's what's
2053 going to be used in most code.
2054 +/
2055 alias MonoTime = MonoTimeImpl!(ClockType.normal);
2056
2057 /++
2058 Represents a timestamp of the system's monotonic clock.
2059
2060 A monotonic clock is one which always goes forward and never moves
2061 backwards, unlike the system's wall clock time (as represented by
2062 $(REF SysTime, std,datetime)). The system's wall clock time can be adjusted
2063 by the user or by the system itself via services such as NTP, so it is
2064 unreliable to use the wall clock time for timing. Timers which use the wall
2065 clock time could easily end up never going off due to changes made to the
2066 wall clock time or otherwise waiting for a different period of time than
2067 that specified by the programmer. However, because the monotonic clock
2068 always increases at a fixed rate and is not affected by adjustments to the
2069 wall clock time, it is ideal for use with timers or anything which requires
2070 high precision timing.
2071
2072 So, MonoTime should be used for anything involving timers and timing,
2073 whereas $(REF SysTime, std,datetime) should be used when the wall clock time
2074 is required.
2075
2076 The monotonic clock has no relation to wall clock time. Rather, it holds
2077 its time as the number of ticks of the clock which have occurred since the
2078 clock started (typically when the system booted up). So, to determine how
2079 much time has passed between two points in time, one monotonic time is
2080 subtracted from the other to determine the number of ticks which occurred
2081 between the two points of time, and those ticks are divided by the number of
2082 ticks that occur every second (as represented by MonoTime.ticksPerSecond)
2083 to get a meaningful duration of time. Normally, MonoTime does these
2084 calculations for the programmer, but the $(D ticks) and $(D ticksPerSecond)
2085 properties are provided for those who require direct access to the system
2086 ticks. The normal way that MonoTime would be used is
2087
2088 --------------------
2089 MonoTime before = MonoTime.currTime;
2090 // do stuff...
2091 MonoTime after = MonoTime.currTime;
2092 Duration timeElapsed = after - before;
2093 --------------------
2094
2095 $(LREF MonoTime) is an alias to $(D MonoTimeImpl!(ClockType.normal)) and is
2096 what most programs should use for the monotonic clock, so that's what is
2097 used in most of $(D MonoTimeImpl)'s documentation. But $(D MonoTimeImpl)
2098 can be instantiated with other clock types for those rare programs that need
2099 it.
2100
2101 See_Also:
2102 $(LREF ClockType)
2103 +/
2104 struct MonoTimeImpl(ClockType clockType)
2105 {
2106 private enum _clockIdx = _clockTypeIdx(clockType);
2107 private enum _clockName = _clockTypeName(clockType);
2108
2109 @safe:
2110
2111 version (Windows)
2112 {
2113 static if (clockType != ClockType.coarse &&
2114 clockType != ClockType.normal &&
2115 clockType != ClockType.precise)
2116 {
2117 static assert(0, "ClockType." ~ _clockName ~
2118 " is not supported by MonoTimeImpl on this system.");
2119 }
2120 }
2121 else version (Darwin)
2122 {
2123 static if (clockType != ClockType.coarse &&
2124 clockType != ClockType.normal &&
2125 clockType != ClockType.precise)
2126 {
2127 static assert(0, "ClockType." ~ _clockName ~
2128 " is not supported by MonoTimeImpl on this system.");
2129 }
2130 }
2131 else version (Posix)
2132 {
2133 enum clockArg = _posixClock(clockType);
2134 }
2135 else
2136 static assert(0, "Unsupported platform");
2137
2138 // POD value, test mutable/const/immutable conversion
2139 version (CoreUnittest) unittest
2140 {
2141 MonoTimeImpl m;
2142 const MonoTimeImpl cm = m;
2143 immutable MonoTimeImpl im = m;
2144 m = cm;
2145 m = im;
2146 }
2147
2148 /++
2149 The current time of the system's monotonic clock. This has no relation
2150 to the wall clock time, as the wall clock time can be adjusted (e.g.
2151 by NTP), whereas the monotonic clock always moves forward. The source
2152 of the monotonic time is system-specific.
2153
2154 On Windows, $(D QueryPerformanceCounter) is used. On Mac OS X,
2155 $(D mach_absolute_time) is used, while on other POSIX systems,
2156 $(D clock_gettime) is used.
2157
2158 $(RED Warning): On some systems, the monotonic clock may stop counting
2159 when the computer goes to sleep or hibernates. So, the
2160 monotonic clock may indicate less time than has actually
2161 passed if that occurs. This is known to happen on
2162 Mac OS X. It has not been tested whether it occurs on
2163 either Windows or Linux.
2164 +/
2165 static @property MonoTimeImpl currTime() @trusted nothrow @nogc
2166 {
2167 if (ticksPerSecond == 0)
2168 {
2169 import core.internal.abort : abort;
2170 abort("MonoTimeImpl!(ClockType." ~ _clockName ~
2171 ") failed to get the frequency of the system's monotonic clock.");
2172 }
2173
2174 version (Windows)
2175 {
2176 long ticks = void;
2177 QueryPerformanceCounter(&ticks);
2178 return MonoTimeImpl(ticks);
2179 }
2180 else version (Darwin)
2181 return MonoTimeImpl(mach_absolute_time());
2182 else version (Posix)
2183 {
2184 timespec ts = void;
2185 immutable error = clock_gettime(clockArg, &ts);
2186 // clockArg is supported and if tv_sec is long or larger
2187 // overflow won't happen before 292 billion years A.D.
2188 static if (ts.tv_sec.max < long.max)
2189 {
2190 if (error)
2191 {
2192 import core.internal.abort : abort;
2193 abort("Call to clock_gettime failed.");
2194 }
2195 }
2196 return MonoTimeImpl(convClockFreq(ts.tv_sec * 1_000_000_000L + ts.tv_nsec,
2197 1_000_000_000L,
2198 ticksPerSecond));
2199 }
2200 }
2201
2202
2203 static @property pure nothrow @nogc
2204 {
2205 /++
2206 A $(D MonoTime) of $(D 0) ticks. It's provided to be consistent with
2207 $(D Duration.zero), and it's more explicit than $(D MonoTime.init).
2208 +/
2209 MonoTimeImpl zero() { return MonoTimeImpl(0); }
2210
2211 /++
2212 Largest $(D MonoTime) possible.
2213 +/
2214 MonoTimeImpl max() { return MonoTimeImpl(long.max); }
2215
2216 /++
2217 Most negative $(D MonoTime) possible.
2218 +/
2219 MonoTimeImpl min() { return MonoTimeImpl(long.min); }
2220 }
2221
2222 version (CoreUnittest) unittest
2223 {
2224 assert(MonoTimeImpl.zero == MonoTimeImpl(0));
2225 assert(MonoTimeImpl.max == MonoTimeImpl(long.max));
2226 assert(MonoTimeImpl.min == MonoTimeImpl(long.min));
2227 assert(MonoTimeImpl.min < MonoTimeImpl.zero);
2228 assert(MonoTimeImpl.zero < MonoTimeImpl.max);
2229 assert(MonoTimeImpl.min < MonoTimeImpl.max);
2230 }
2231
2232
2233 /++
2234 Compares this MonoTime with the given MonoTime.
2235
2236 Returns:
2237 $(BOOKTABLE,
2238 $(TR $(TD this &lt; rhs) $(TD &lt; 0))
2239 $(TR $(TD this == rhs) $(TD 0))
2240 $(TR $(TD this &gt; rhs) $(TD &gt; 0))
2241 )
2242 +/
2243 int opCmp(MonoTimeImpl rhs) const pure nothrow @nogc
2244 {
2245 return (_ticks > rhs._ticks) - (_ticks < rhs._ticks);
2246 }
2247
2248 version (CoreUnittest) unittest
2249 {
2250 import core.internal.traits : rvalueOf;
2251 const t = MonoTimeImpl.currTime;
2252 assert(t == rvalueOf(t));
2253 }
2254
2255 version (CoreUnittest) unittest
2256 {
2257 import core.internal.traits : rvalueOf;
2258 const before = MonoTimeImpl.currTime;
2259 auto after = MonoTimeImpl(before._ticks + 42);
2260 assert(before < after);
2261 assert(rvalueOf(before) <= before);
2262 assert(rvalueOf(after) > before);
2263 assert(after >= rvalueOf(after));
2264 }
2265
2266 version (CoreUnittest) unittest
2267 {
2268 const currTime = MonoTimeImpl.currTime;
2269 assert(MonoTimeImpl(long.max) > MonoTimeImpl(0));
2270 assert(MonoTimeImpl(0) > MonoTimeImpl(long.min));
2271 assert(MonoTimeImpl(long.max) > currTime);
2272 assert(currTime > MonoTimeImpl(0));
2273 assert(MonoTimeImpl(0) < currTime);
2274 assert(MonoTimeImpl(0) < MonoTimeImpl(long.max));
2275 assert(MonoTimeImpl(long.min) < MonoTimeImpl(0));
2276 }
2277
2278
2279 /++
2280 Subtracting two MonoTimes results in a $(LREF Duration) representing
2281 the amount of time which elapsed between them.
2282
2283 The primary way that programs should time how long something takes is to
2284 do
2285 --------------------
2286 MonoTime before = MonoTime.currTime;
2287 // do stuff
2288 MonoTime after = MonoTime.currTime;
2289
2290 // How long it took.
2291 Duration timeElapsed = after - before;
2292 --------------------
2293 or to use a wrapper (such as a stop watch type) which does that.
2294
2295 $(RED Warning):
2296 Because $(LREF Duration) is in hnsecs, whereas MonoTime is in system
2297 ticks, it's usually the case that this assertion will fail
2298 --------------------
2299 auto before = MonoTime.currTime;
2300 // do stuff
2301 auto after = MonoTime.currTime;
2302 auto timeElapsed = after - before;
2303 assert(before + timeElapsed == after);
2304 --------------------
2305
2306 This is generally fine, and by its very nature, converting from
2307 system ticks to any type of seconds (hnsecs, nsecs, etc.) will
2308 introduce rounding errors, but if code needs to avoid any of the
2309 small rounding errors introduced by conversion, then it needs to use
2310 MonoTime's $(D ticks) property and keep all calculations in ticks
2311 rather than using $(LREF Duration).
2312 +/
2313 Duration opBinary(string op)(MonoTimeImpl rhs) const pure nothrow @nogc
2314 if (op == "-")
2315 {
2316 immutable diff = _ticks - rhs._ticks;
2317 return Duration(convClockFreq(diff , ticksPerSecond, hnsecsPer!"seconds"));
2318 }
2319
2320 version (CoreUnittest) unittest
2321 {
2322 import core.internal.traits : rvalueOf;
2323 const t = MonoTimeImpl.currTime;
2324 assert(t - rvalueOf(t) == Duration.zero);
2325 static assert(!__traits(compiles, t + t));
2326 }
2327
2328 version (CoreUnittest) unittest
2329 {
2330 static void test(const scope MonoTimeImpl before, const scope MonoTimeImpl after, const scope Duration min)
2331 {
2332 immutable diff = after - before;
2333 assert(diff >= min);
2334 auto calcAfter = before + diff;
2335 assertApprox(calcAfter, calcAfter - Duration(1), calcAfter + Duration(1));
2336 assert(before - after == -diff);
2337 }
2338
2339 const before = MonoTimeImpl.currTime;
2340 test(before, MonoTimeImpl(before._ticks + 4202), Duration.zero);
2341 test(before, MonoTimeImpl.currTime, Duration.zero);
2342
2343 const durLargerUnits = dur!"minutes"(7) + dur!"seconds"(22);
2344 test(before, before + durLargerUnits + dur!"msecs"(33) + dur!"hnsecs"(571), durLargerUnits);
2345 }
2346
2347
2348 /++
2349 Adding or subtracting a $(LREF Duration) to/from a MonoTime results in
2350 a MonoTime which is adjusted by that amount.
2351 +/
2352 MonoTimeImpl opBinary(string op)(Duration rhs) const pure nothrow @nogc
2353 if (op == "+" || op == "-")
2354 {
2355 immutable rhsConverted = convClockFreq(rhs._hnsecs, hnsecsPer!"seconds", ticksPerSecond);
2356 mixin("return MonoTimeImpl(_ticks " ~ op ~ " rhsConverted);");
2357 }
2358
2359 version (CoreUnittest) unittest
2360 {
2361 const t = MonoTimeImpl.currTime;
2362 assert(t + Duration(0) == t);
2363 assert(t - Duration(0) == t);
2364 }
2365
2366 version (CoreUnittest) unittest
2367 {
2368 const t = MonoTimeImpl.currTime;
2369
2370 // We reassign ticks in order to get the same rounding errors
2371 // that we should be getting with Duration (e.g. MonoTimeImpl may be
2372 // at a higher precision than hnsecs, meaning that 7333 would be
2373 // truncated when converting to hnsecs).
2374 long ticks = 7333;
2375 auto hnsecs = convClockFreq(ticks, ticksPerSecond, hnsecsPer!"seconds");
2376 ticks = convClockFreq(hnsecs, hnsecsPer!"seconds", ticksPerSecond);
2377
2378 assert(t - Duration(hnsecs) == MonoTimeImpl(t._ticks - ticks));
2379 assert(t + Duration(hnsecs) == MonoTimeImpl(t._ticks + ticks));
2380 }
2381
2382
2383 /++ Ditto +/
2384 ref MonoTimeImpl opOpAssign(string op)(Duration rhs) pure nothrow @nogc
2385 if (op == "+" || op == "-")
2386 {
2387 immutable rhsConverted = convClockFreq(rhs._hnsecs, hnsecsPer!"seconds", ticksPerSecond);
2388 mixin("_ticks " ~ op ~ "= rhsConverted;");
2389 return this;
2390 }
2391
2392 version (CoreUnittest) unittest
2393 {
2394 auto mt = MonoTimeImpl.currTime;
2395 const initial = mt;
2396 mt += Duration(0);
2397 assert(mt == initial);
2398 mt -= Duration(0);
2399 assert(mt == initial);
2400
2401 // We reassign ticks in order to get the same rounding errors
2402 // that we should be getting with Duration (e.g. MonoTimeImpl may be
2403 // at a higher precision than hnsecs, meaning that 7333 would be
2404 // truncated when converting to hnsecs).
2405 long ticks = 7333;
2406 auto hnsecs = convClockFreq(ticks, ticksPerSecond, hnsecsPer!"seconds");
2407 ticks = convClockFreq(hnsecs, hnsecsPer!"seconds", ticksPerSecond);
2408 auto before = MonoTimeImpl(initial._ticks - ticks);
2409
2410 assert((mt -= Duration(hnsecs)) == before);
2411 assert(mt == before);
2412 assert((mt += Duration(hnsecs)) == initial);
2413 assert(mt == initial);
2414 }
2415
2416
2417 /++
2418 The number of ticks in the monotonic time.
2419
2420 Most programs should not use this directly, but it's exposed for those
2421 few programs that need it.
2422
2423 The main reasons that a program might need to use ticks directly is if
2424 the system clock has higher precision than hnsecs, and the program needs
2425 that higher precision, or if the program needs to avoid the rounding
2426 errors caused by converting to hnsecs.
2427 +/
2428 @property long ticks() const pure nothrow @nogc
2429 {
2430 return _ticks;
2431 }
2432
2433 version (CoreUnittest) unittest
2434 {
2435 const mt = MonoTimeImpl.currTime;
2436 assert(mt.ticks == mt._ticks);
2437 }
2438
2439
2440 /++
2441 The number of ticks that MonoTime has per second - i.e. the resolution
2442 or frequency of the system's monotonic clock.
2443
2444 e.g. if the system clock had a resolution of microseconds, then
2445 ticksPerSecond would be $(D 1_000_000).
2446 +/
2447 static @property long ticksPerSecond() pure nothrow @nogc
2448 {
2449 return _ticksPerSecond[_clockIdx];
2450 }
2451
2452 version (CoreUnittest) unittest
2453 {
2454 assert(MonoTimeImpl.ticksPerSecond == _ticksPerSecond[_clockIdx]);
2455 }
2456
2457
2458 ///
2459 string toString() const pure nothrow
2460 {
2461 static if (clockType == ClockType.normal)
2462 return "MonoTime(" ~ signedToTempString(_ticks) ~ " ticks, " ~ signedToTempString(ticksPerSecond) ~ " ticks per second)";
2463 else
2464 return "MonoTimeImpl!(ClockType." ~ _clockName ~ ")(" ~ signedToTempString(_ticks) ~ " ticks, " ~
2465 signedToTempString(ticksPerSecond) ~ " ticks per second)";
2466 }
2467
2468 version (CoreUnittest) unittest
2469 {
2470 import core.internal.util.math : min;
2471
2472 static void eat(ref string s, const(char)[] exp)
2473 {
2474 assert(s[0 .. min($, exp.length)] == exp, s~" != "~exp);
2475 s = s[exp.length .. $];
2476 }
2477
2478 immutable mt = MonoTimeImpl.currTime;
2479 auto str = mt.toString();
2480 static if (is(typeof(this) == MonoTime))
2481 eat(str, "MonoTime(");
2482 else
2483 eat(str, "MonoTimeImpl!(ClockType."~_clockName~")(");
2484
2485 eat(str, signedToTempString(mt._ticks));
2486 eat(str, " ticks, ");
2487 eat(str, signedToTempString(ticksPerSecond));
2488 eat(str, " ticks per second)");
2489 }
2490
2491 private:
2492
2493 // static immutable long _ticksPerSecond;
2494
2495 version (CoreUnittest) unittest
2496 {
2497 assert(_ticksPerSecond[_clockIdx]);
2498 }
2499
2500
2501 long _ticks;
2502 }
2503
2504 // This is supposed to be a static variable in MonoTimeImpl with the static
2505 // constructor being in there, but https://issues.dlang.org/show_bug.cgi?id=14517
2506 // prevents that from working. However, moving it back to a static ctor will
2507 // reraise issues with other systems using MonoTime, so we should leave this
2508 // here even when that bug is fixed.
2509 private immutable long[__traits(allMembers, ClockType).length] _ticksPerSecond;
2510
2511 // This is called directly from the runtime initilization function (rt_init),
2512 // instead of using a static constructor. Other subsystems inside the runtime
2513 // (namely, the GC) may need time functionality, but cannot wait until the
2514 // static ctors have run. Therefore, we initialize these specially. Because
2515 // it's a normal function, we need to do some dangerous casting PLEASE take
2516 // care when modifying this function, and it should NOT be called except from
2517 // the runtime init.
2518 //
2519 // NOTE: the code below SPECIFICALLY does not assert when it cannot initialize
2520 // the ticks per second array. This allows cases where a clock is never used on
2521 // a system that doesn't support it. See bugzilla issue
2522 // https://issues.dlang.org/show_bug.cgi?id=14863
2523 // The assert will occur when someone attempts to use _ticksPerSecond for that
2524 // value.
2525 extern(C) void _d_initMonoTime() @nogc nothrow
2526 {
2527 // We need a mutable pointer to the ticksPerSecond array. Although this
2528 // would appear to break immutability, it is logically the same as a static
2529 // ctor. So we should ONLY write these values once (we will check for 0
2530 // values when setting to ensure this is truly only called once).
2531 auto tps = cast(long[])_ticksPerSecond[];
2532
2533 // If we try to do anything with ClockType in the documentation build, it'll
2534 // trigger the static assertions related to ClockType, since the
2535 // documentation build defines all of the possible ClockTypes, which won't
2536 // work when they're used in the static ifs, because no system supports them
2537 // all.
2538 version (CoreDdoc)
2539 {}
2540 else version (Windows)
2541 {
2542 long ticksPerSecond;
2543 if (QueryPerformanceFrequency(&ticksPerSecond) != 0)
2544 {
2545 foreach (i, typeStr; __traits(allMembers, ClockType))
2546 {
2547 // ensure we are only writing immutable data once
2548 if (tps[i] != 0)
2549 // should only be called once
2550 assert(0);
2551 tps[i] = ticksPerSecond;
2552 }
2553 }
2554 }
2555 else version (Darwin)
2556 {
2557 immutable long ticksPerSecond = machTicksPerSecond();
2558 foreach (i, typeStr; __traits(allMembers, ClockType))
2559 {
2560 // ensure we are only writing immutable data once
2561 if (tps[i] != 0)
2562 // should only be called once
2563 assert(0);
2564 tps[i] = ticksPerSecond;
2565 }
2566 }
2567 else version (Posix)
2568 {
2569 timespec ts;
2570 foreach (i, typeStr; __traits(allMembers, ClockType))
2571 {
2572 static if (typeStr != "second")
2573 {
2574 enum clockArg = _posixClock(__traits(getMember, ClockType, typeStr));
2575 if (clock_getres(clockArg, &ts) == 0)
2576 {
2577 // ensure we are only writing immutable data once
2578 if (tps[i] != 0)
2579 // should only be called once
2580 assert(0);
2581
2582 // For some reason, on some systems, clock_getres returns
2583 // a resolution which is clearly wrong:
2584 // - it's a millisecond or worse, but the time is updated
2585 // much more frequently than that.
2586 // - it's negative
2587 // - it's zero
2588 // In such cases, we'll just use nanosecond resolution.
2589 tps[i] = ts.tv_sec != 0 || ts.tv_nsec <= 0 || ts.tv_nsec >= 1000
2590 ? 1_000_000_000L : 1_000_000_000L / ts.tv_nsec;
2591 }
2592 }
2593 }
2594 }
2595 else
2596 static assert(0, "Unsupported platform");
2597 }
2598
2599
2600 // Tests for MonoTimeImpl.currTime. It has to be outside, because MonoTimeImpl
2601 // is a template. This unittest block also makes sure that MonoTimeImpl actually
2602 // is instantiated with all of the various ClockTypes so that those types and
2603 // their tests are compiled and run.
2604 unittest
2605 {
2606 // This test is separate so that it can be tested with MonoTime and not just
2607 // MonoTimeImpl.
2608 auto norm1 = MonoTime.currTime;
2609 auto norm2 = MonoTimeImpl!(ClockType.normal).currTime;
2610 assert(norm1 <= norm2);
2611
2612 static bool clockSupported(ClockType c)
2613 {
2614 // Skip unsupported clocks on older linux kernels, assume that only
2615 // CLOCK_MONOTONIC and CLOCK_REALTIME exist, as that is the lowest
2616 // common denominator supported by all versions of Linux pre-2.6.12.
2617 version (Linux_Pre_2639)
2618 return c == ClockType.normal || c == ClockType.precise;
2619 else
2620 return c != ClockType.second; // second doesn't work with MonoTimeImpl
2621
2622 }
2623
2624 foreach (typeStr; __traits(allMembers, ClockType))
2625 {
2626 mixin("alias type = ClockType." ~ typeStr ~ ";");
2627 static if (clockSupported(type))
2628 {
2629 auto v1 = MonoTimeImpl!type.currTime;
2630 auto v2 = MonoTimeImpl!type.currTime;
2631 scope(failure)
2632 {
2633 printf("%s: v1 %s, v2 %s, tps %s\n",
2634 (type.stringof ~ "\0").ptr,
2635 numToStringz(v1._ticks),
2636 numToStringz(v2._ticks),
2637 numToStringz(typeof(v1).ticksPerSecond));
2638 }
2639 assert(v1 <= v2);
2640
2641 foreach (otherStr; __traits(allMembers, ClockType))
2642 {
2643 mixin("alias other = ClockType." ~ otherStr ~ ";");
2644 static if (clockSupported(other))
2645 {
2646 static assert(is(typeof({auto o1 = MonTimeImpl!other.currTime; auto b = v1 <= o1;})) ==
2647 is(type == other));
2648 }
2649 }
2650 }
2651 }
2652 }
2653
2654
2655 /++
2656 Converts the given time from one clock frequency/resolution to another.
2657
2658 See_Also:
2659 $(LREF ticksToNSecs)
2660 +/
2661 long convClockFreq(long ticks, long srcTicksPerSecond, long dstTicksPerSecond) @safe pure nothrow @nogc
2662 {
2663 // This would be more straightforward with floating point arithmetic,
2664 // but we avoid it here in order to avoid the rounding errors that that
2665 // introduces. Also, by splitting out the units in this way, we're able
2666 // to deal with much larger values before running into problems with
2667 // integer overflow.
2668 return ticks / srcTicksPerSecond * dstTicksPerSecond +
2669 ticks % srcTicksPerSecond * dstTicksPerSecond / srcTicksPerSecond;
2670 }
2671
2672 ///
2673 unittest
2674 {
2675 // one tick is one second -> one tick is a hecto-nanosecond
2676 assert(convClockFreq(45, 1, 10_000_000) == 450_000_000);
2677
2678 // one tick is one microsecond -> one tick is a millisecond
2679 assert(convClockFreq(9029, 1_000_000, 1_000) == 9);
2680
2681 // one tick is 1/3_515_654 of a second -> 1/1_001_010 of a second
2682 assert(convClockFreq(912_319, 3_515_654, 1_001_010) == 259_764);
2683
2684 // one tick is 1/MonoTime.ticksPerSecond -> one tick is a nanosecond
2685 // Equivalent to ticksToNSecs
2686 auto nsecs = convClockFreq(1982, MonoTime.ticksPerSecond, 1_000_000_000);
2687 }
2688
2689 unittest
2690 {
2691 assert(convClockFreq(99, 43, 57) == 131);
2692 assert(convClockFreq(131, 57, 43) == 98);
2693 assert(convClockFreq(1234567890, 10_000_000, 1_000_000_000) == 123456789000);
2694 assert(convClockFreq(1234567890, 1_000_000_000, 10_000_000) == 12345678);
2695 assert(convClockFreq(123456789000, 1_000_000_000, 10_000_000) == 1234567890);
2696 assert(convClockFreq(12345678, 10_000_000, 1_000_000_000) == 1234567800);
2697 assert(convClockFreq(13131, 3_515_654, 10_000_000) == 37350);
2698 assert(convClockFreq(37350, 10_000_000, 3_515_654) == 13130);
2699 assert(convClockFreq(37350, 3_515_654, 10_000_000) == 106239);
2700 assert(convClockFreq(106239, 10_000_000, 3_515_654) == 37349);
2701
2702 // It would be too expensive to cover a large range of possible values for
2703 // ticks, so we use random values in an attempt to get reasonable coverage.
2704 import core.stdc.stdlib : rand, srand;
2705 immutable seed = cast(int)time(null);
2706 srand(seed);
2707 scope(failure) printf("seed %d\n", seed);
2708 enum freq1 = 5_527_551L;
2709 enum freq2 = 10_000_000L;
2710 enum freq3 = 1_000_000_000L;
2711 enum freq4 = 98_123_320L;
2712 immutable freq5 = MonoTime.ticksPerSecond;
2713
2714 // This makes it so that freq6 is the first multiple of 10 which is greater
2715 // than or equal to freq5, which at one point was considered for MonoTime's
2716 // ticksPerSecond rather than using the system's actual clock frequency, so
2717 // it seemed like a good test case to have.
2718 import core.stdc.math : floor, log10, pow;
2719 immutable numDigitsMinus1 = cast(int)floor(log10(freq5));
2720 auto freq6 = cast(long)pow(10, numDigitsMinus1);
2721 if (freq5 > freq6)
2722 freq6 *= 10;
2723
2724 foreach (_; 0 .. 10_000)
2725 {
2726 long[2] values = [rand(), cast(long)rand() * (rand() % 16)];
2727 foreach (i; values)
2728 {
2729 scope(failure) printf("i %s\n", numToStringz(i));
2730 assertApprox(convClockFreq(convClockFreq(i, freq1, freq2), freq2, freq1), i - 10, i + 10);
2731 assertApprox(convClockFreq(convClockFreq(i, freq2, freq1), freq1, freq2), i - 10, i + 10);
2732
2733 assertApprox(convClockFreq(convClockFreq(i, freq3, freq4), freq4, freq3), i - 100, i + 100);
2734 assertApprox(convClockFreq(convClockFreq(i, freq4, freq3), freq3, freq4), i - 100, i + 100);
2735
2736 scope(failure) printf("sys %s mt %s\n", numToStringz(freq5), numToStringz(freq6));
2737 assertApprox(convClockFreq(convClockFreq(i, freq5, freq6), freq6, freq5), i - 10, i + 10);
2738 assertApprox(convClockFreq(convClockFreq(i, freq6, freq5), freq5, freq6), i - 10, i + 10);
2739
2740 // This is here rather than in a unittest block immediately after
2741 // ticksToNSecs in order to avoid code duplication in the unit tests.
2742 assert(convClockFreq(i, MonoTime.ticksPerSecond, 1_000_000_000) == ticksToNSecs(i));
2743 }
2744 }
2745 }
2746
2747
2748 /++
2749 Convenience wrapper around $(LREF convClockFreq) which converts ticks at
2750 a clock frequency of $(D MonoTime.ticksPerSecond) to nanoseconds.
2751
2752 It's primarily of use when $(D MonoTime.ticksPerSecond) is greater than
2753 hecto-nanosecond resolution, and an application needs a higher precision
2754 than hecto-nanoceconds.
2755
2756 See_Also:
2757 $(LREF convClockFreq)
2758 +/
2759 long ticksToNSecs(long ticks) @safe pure nothrow @nogc
2760 {
2761 return convClockFreq(ticks, MonoTime.ticksPerSecond, 1_000_000_000);
2762 }
2763
2764 ///
2765 unittest
2766 {
2767 auto before = MonoTime.currTime;
2768 // do stuff
2769 auto after = MonoTime.currTime;
2770 auto diffInTicks = after.ticks - before.ticks;
2771 auto diffInNSecs = ticksToNSecs(diffInTicks);
2772 assert(diffInNSecs == convClockFreq(diffInTicks, MonoTime.ticksPerSecond, 1_000_000_000));
2773 }
2774
2775
2776 /++
2777 The reverse of $(LREF ticksToNSecs).
2778 +/
2779 long nsecsToTicks(long ticks) @safe pure nothrow @nogc
2780 {
2781 return convClockFreq(ticks, 1_000_000_000, MonoTime.ticksPerSecond);
2782 }
2783
2784 unittest
2785 {
2786 long ticks = 123409832717333;
2787 auto nsecs = convClockFreq(ticks, MonoTime.ticksPerSecond, 1_000_000_000);
2788 ticks = convClockFreq(nsecs, 1_000_000_000, MonoTime.ticksPerSecond);
2789 assert(nsecsToTicks(nsecs) == ticks);
2790 }
2791
2792
2793
2794 /++
2795 $(RED Warning: TickDuration is deprecated. Please use
2796 $(LREF MonoTime) for the cases where a monotonic timestamp is needed
2797 and $(LREF Duration) when a duration is needed, rather than using
2798 TickDuration.)
2799
2800 Represents a duration of time in system clock ticks.
2801
2802 The system clock ticks are the ticks of the system clock at the highest
2803 precision that the system provides.
2804 +/
2805 deprecated("TickDuration has been deprecated, please use Duration or MonoTime instead")
2806 struct TickDuration
2807 {
2808 deprecated:
2809 private static TickDuration TDRvalueOf(TickDuration td)
2810 {
2811 return td;
2812 }
2813 /++
2814 The number of ticks that the system clock has in one second.
2815
2816 If $(D ticksPerSec) is $(D 0), then then $(D TickDuration) failed to
2817 get the value of $(D ticksPerSec) on the current system, and
2818 $(D TickDuration) is not going to work. That would be highly abnormal
2819 though.
2820 +/
2821 static immutable long ticksPerSec;
2822
2823
2824 /++
2825 The tick of the system clock (as a $(D TickDuration)) when the
2826 application started.
2827 +/
2828 static immutable TickDuration appOrigin;
2829
2830
2831 static @property @safe pure nothrow @nogc
2832 {
2833 /++
2834 It's the same as $(D TickDuration(0)), but it's provided to be
2835 consistent with $(D Duration), which provides a $(D zero) property.
2836 +/
2837 TickDuration zero() { return TickDuration(0); }
2838
2839 /++
2840 Largest $(D TickDuration) possible.
2841 +/
2842 TickDuration max() { return TickDuration(long.max); }
2843
2844 /++
2845 Most negative $(D TickDuration) possible.
2846 +/
2847 TickDuration min() { return TickDuration(long.min); }
2848 }
2849
2850 version (CoreUnittest) unittest
2851 {
2852 assert((zero == TickDuration(0)) == true);
2853 assert((TickDuration.max == TickDuration(long.max)) == true);
2854 assert((TickDuration.min == TickDuration(long.min)) == true);
2855 assert((TickDuration.min < TickDuration.zero) == true);
2856 assert((TickDuration.zero < TickDuration.max) == true);
2857 assert((TickDuration.min < TickDuration.max) == true);
2858 assert((TickDuration.min - TickDuration(1) == TickDuration.max) == true);
2859 assert((TickDuration.max + TickDuration(1) == TickDuration.min) == true);
2860 }
2861
2862
2863 static pragma(crt_constructor) void time_initializer()
2864 {
2865 version (Windows)
2866 {
2867 if (QueryPerformanceFrequency(cast(long*)&ticksPerSec) == 0)
2868 ticksPerSec = 0;
2869 }
2870 else version (Darwin)
2871 {
2872 ticksPerSec = machTicksPerSecond();
2873 }
2874 else version (Posix)
2875 {
2876 static if (is(typeof(clock_gettime)))
2877 {
2878 timespec ts;
2879
2880 if (clock_getres(CLOCK_MONOTONIC, &ts) != 0)
2881 ticksPerSec = 0;
2882 else
2883 {
2884 //For some reason, on some systems, clock_getres returns
2885 //a resolution which is clearly wrong (it's a millisecond
2886 //or worse, but the time is updated much more frequently
2887 //than that). In such cases, we'll just use nanosecond
2888 //resolution.
2889 ticksPerSec = ts.tv_nsec >= 1000 ? 1_000_000_000
2890 : 1_000_000_000 / ts.tv_nsec;
2891 }
2892 }
2893 else
2894 ticksPerSec = 1_000_000;
2895 }
2896 else
2897 static assert(0, "Unsupported platform");
2898
2899 if (ticksPerSec != 0)
2900 appOrigin = TickDuration.currSystemTick;
2901 }
2902
2903 version (CoreUnittest) unittest
2904 {
2905 assert(ticksPerSec);
2906 }
2907
2908
2909 /++
2910 The number of system ticks in this $(D TickDuration).
2911
2912 You can convert this $(D length) into the number of seconds by dividing
2913 it by $(D ticksPerSec) (or using one the appropriate property function
2914 to do it).
2915 +/
2916 long length;
2917
2918 /++
2919 Returns the total number of seconds in this $(D TickDuration).
2920 +/
2921 @property long seconds() @safe const pure nothrow @nogc
2922 {
2923 return this.to!("seconds", long)();
2924 }
2925
2926 version (CoreUnittest) unittest
2927 {
2928 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
2929 {
2930 assert((cast(T)TickDuration(ticksPerSec)).seconds == 1);
2931 assert((cast(T)TickDuration(ticksPerSec - 1)).seconds == 0);
2932 assert((cast(T)TickDuration(ticksPerSec * 2)).seconds == 2);
2933 assert((cast(T)TickDuration(ticksPerSec * 2 - 1)).seconds == 1);
2934 assert((cast(T)TickDuration(-1)).seconds == 0);
2935 assert((cast(T)TickDuration(-ticksPerSec - 1)).seconds == -1);
2936 assert((cast(T)TickDuration(-ticksPerSec)).seconds == -1);
2937 }
2938 }
2939
2940
2941 /++
2942 Returns the total number of milliseconds in this $(D TickDuration).
2943 +/
2944 @property long msecs() @safe const pure nothrow @nogc
2945 {
2946 return this.to!("msecs", long)();
2947 }
2948
2949
2950 /++
2951 Returns the total number of microseconds in this $(D TickDuration).
2952 +/
2953 @property long usecs() @safe const pure nothrow @nogc
2954 {
2955 return this.to!("usecs", long)();
2956 }
2957
2958
2959 /++
2960 Returns the total number of hecto-nanoseconds in this $(D TickDuration).
2961 +/
2962 @property long hnsecs() @safe const pure nothrow @nogc
2963 {
2964 return this.to!("hnsecs", long)();
2965 }
2966
2967
2968 /++
2969 Returns the total number of nanoseconds in this $(D TickDuration).
2970 +/
2971 @property long nsecs() @safe const pure nothrow @nogc
2972 {
2973 return this.to!("nsecs", long)();
2974 }
2975
2976
2977 /++
2978 This allows you to construct a $(D TickDuration) from the given time
2979 units with the given length.
2980
2981 Params:
2982 units = The time units of the $(D TickDuration) (e.g. $(D "msecs")).
2983 length = The number of units in the $(D TickDuration).
2984 +/
2985 static TickDuration from(string units)(long length) @safe pure nothrow @nogc
2986 if (units == "seconds" ||
2987 units == "msecs" ||
2988 units == "usecs" ||
2989 units == "hnsecs" ||
2990 units == "nsecs")
2991 {
2992 enum unitsPerSec = convert!("seconds", units)(1);
2993
2994 return TickDuration(cast(long)(length * (ticksPerSec / cast(real)unitsPerSec)));
2995 }
2996
2997 version (CoreUnittest) unittest
2998 {
2999 foreach (units; AliasSeq!("seconds", "msecs", "usecs", "nsecs"))
3000 {
3001 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
3002 {
3003 assertApprox((cast(T)TickDuration.from!units(1000)).to!(units, long)(),
3004 500, 1500, units);
3005 assertApprox((cast(T)TickDuration.from!units(1_000_000)).to!(units, long)(),
3006 900_000, 1_100_000, units);
3007 assertApprox((cast(T)TickDuration.from!units(2_000_000)).to!(units, long)(),
3008 1_900_000, 2_100_000, units);
3009 }
3010 }
3011 }
3012
3013
3014 /++
3015 Returns a $(LREF Duration) with the same number of hnsecs as this
3016 $(D TickDuration).
3017 Note that the conventional way to convert between $(D TickDuration)
3018 and $(D Duration) is using $(REF to, std,conv), e.g.:
3019 $(D tickDuration.to!Duration())
3020 +/
3021 Duration opCast(T)() @safe const pure nothrow @nogc
3022 if (is(immutable T == immutable Duration))
3023 {
3024 return Duration(hnsecs);
3025 }
3026
3027 version (CoreUnittest) unittest
3028 {
3029 foreach (D; AliasSeq!(Duration, const Duration, immutable Duration))
3030 {
3031 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
3032 {
3033 auto expected = dur!"seconds"(1);
3034 assert(cast(D)cast(T)TickDuration.from!"seconds"(1) == expected);
3035
3036 foreach (units; AliasSeq!("msecs", "usecs", "hnsecs"))
3037 {
3038 D actual = cast(D)cast(T)TickDuration.from!units(1_000_000);
3039 assertApprox(actual, dur!units(900_000), dur!units(1_100_000));
3040 }
3041 }
3042 }
3043 }
3044
3045
3046 //Temporary hack until bug http://d.puremagic.com/issues/show_bug.cgi?id=5747 is fixed.
3047 TickDuration opCast(T)() @safe const pure nothrow @nogc
3048 if (is(immutable T == immutable TickDuration))
3049 {
3050 return this;
3051 }
3052
3053
3054 /++
3055 Adds or subtracts two $(D TickDuration)s as well as assigning the result
3056 to this $(D TickDuration).
3057
3058 The legal types of arithmetic for $(D TickDuration) using this operator
3059 are
3060
3061 $(TABLE
3062 $(TR $(TD TickDuration) $(TD +=) $(TD TickDuration) $(TD -->) $(TD TickDuration))
3063 $(TR $(TD TickDuration) $(TD -=) $(TD TickDuration) $(TD -->) $(TD TickDuration))
3064 )
3065
3066 Params:
3067 rhs = The $(D TickDuration) to add to or subtract from this
3068 $(D $(D TickDuration)).
3069 +/
3070 ref TickDuration opOpAssign(string op)(TickDuration rhs) @safe pure nothrow @nogc
3071 if (op == "+" || op == "-")
3072 {
3073 mixin("length " ~ op ~ "= rhs.length;");
3074 return this;
3075 }
3076
3077 version (CoreUnittest) unittest
3078 {
3079 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
3080 {
3081 auto a = TickDuration.currSystemTick;
3082 auto result = a += cast(T)TickDuration.currSystemTick;
3083 assert((a == result) == true);
3084 assert(a.to!("seconds", real)() >= 0);
3085
3086 auto b = TickDuration.currSystemTick;
3087 result = b -= cast(T)TickDuration.currSystemTick;
3088 assert((b == result) == true);
3089 assert(b.to!("seconds", real)() <= 0);
3090
3091 foreach (U; AliasSeq!(const TickDuration, immutable TickDuration))
3092 {
3093 U u = TickDuration(12);
3094 static assert(!__traits(compiles, u += cast(T)TickDuration.currSystemTick));
3095 static assert(!__traits(compiles, u -= cast(T)TickDuration.currSystemTick));
3096 }
3097 }
3098 }
3099
3100
3101 /++
3102 Adds or subtracts two $(D TickDuration)s.
3103
3104 The legal types of arithmetic for $(D TickDuration) using this operator
3105 are
3106
3107 $(TABLE
3108 $(TR $(TD TickDuration) $(TD +) $(TD TickDuration) $(TD -->) $(TD TickDuration))
3109 $(TR $(TD TickDuration) $(TD -) $(TD TickDuration) $(TD -->) $(TD TickDuration))
3110 )
3111
3112 Params:
3113 rhs = The $(D TickDuration) to add to or subtract from this
3114 $(D TickDuration).
3115 +/
3116 TickDuration opBinary(string op)(TickDuration rhs) @safe const pure nothrow @nogc
3117 if (op == "+" || op == "-")
3118 {
3119 return TickDuration(mixin("length " ~ op ~ " rhs.length"));
3120 }
3121
3122 version (CoreUnittest) unittest
3123 {
3124 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
3125 {
3126 T a = TickDuration.currSystemTick;
3127 T b = TickDuration.currSystemTick;
3128 assert((a + b).usecs > 0);
3129 assert((a - b).seconds <= 0);
3130 }
3131 }
3132
3133
3134 /++
3135 Returns the negation of this $(D TickDuration).
3136 +/
3137 TickDuration opUnary(string op)() @safe const pure nothrow @nogc
3138 if (op == "-")
3139 {
3140 return TickDuration(-length);
3141 }
3142
3143 version (CoreUnittest) unittest
3144 {
3145 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
3146 {
3147 assert((-(cast(T)TickDuration(7)) == TickDuration(-7)) == true);
3148 assert((-(cast(T)TickDuration(5)) == TickDuration(-5)) == true);
3149 assert((-(cast(T)TickDuration(-7)) == TickDuration(7)) == true);
3150 assert((-(cast(T)TickDuration(-5)) == TickDuration(5)) == true);
3151 assert((-(cast(T)TickDuration(0)) == TickDuration(0)) == true);
3152 }
3153 }
3154
3155
3156 /++
3157 operator overloading "<, >, <=, >="
3158 +/
3159 int opCmp(TickDuration rhs) @safe const pure nothrow @nogc
3160 {
3161 return (length > rhs.length) - (length < rhs.length);
3162 }
3163
3164 version (CoreUnittest) unittest
3165 {
3166 import core.internal.traits : rvalueOf;
3167 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
3168 {
3169 foreach (U; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
3170 {
3171 T t = TickDuration.currSystemTick;
3172 U u = t;
3173 assert((t == u) == true);
3174 assert((TDRvalueOf(t) == u) == true);
3175 assert((t == TDRvalueOf(u)) == true);
3176 }
3177 }
3178
3179 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
3180 {
3181 foreach (U; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
3182 {
3183 T t = TickDuration.currSystemTick;
3184 U u = t + t;
3185 assert((t < u) == true);
3186 assert((t <= t) == true);
3187 assert((u > t) == true);
3188 assert((u >= u) == true);
3189
3190 assert((TDRvalueOf(t) < u) == true);
3191 assert((TDRvalueOf(t) <= t) == true);
3192 assert((TDRvalueOf(u) > t) == true);
3193 assert((TDRvalueOf(u) >= u) == true);
3194
3195 assert((t < TDRvalueOf(u)) == true);
3196 assert((t <= TDRvalueOf(t)) == true);
3197 assert((u > TDRvalueOf(t)) == true);
3198 assert((u >= TDRvalueOf(u)) == true);
3199 }
3200 }
3201 }
3202
3203
3204 /++
3205 The legal types of arithmetic for $(D TickDuration) using this operator
3206 overload are
3207
3208 $(TABLE
3209 $(TR $(TD TickDuration) $(TD *) $(TD long) $(TD -->) $(TD TickDuration))
3210 $(TR $(TD TickDuration) $(TD *) $(TD floating point) $(TD -->) $(TD TickDuration))
3211 )
3212
3213 Params:
3214 value = The value to divide from this duration.
3215 +/
3216 void opOpAssign(string op, T)(T value) @safe pure nothrow @nogc
3217 if (op == "*" &&
3218 (__traits(isIntegral, T) || __traits(isFloating, T)))
3219 {
3220 length = cast(long)(length * value);
3221 }
3222
3223 version (CoreUnittest) unittest
3224 {
3225 immutable curr = TickDuration.currSystemTick;
3226 TickDuration t1 = curr;
3227 immutable t2 = curr + curr;
3228 t1 *= 2;
3229 assert((t1 == t2) == true);
3230
3231 t1 = curr;
3232 t1 *= 2.0;
3233 immutable tol = TickDuration(cast(long)(_abs(t1.length) * double.epsilon * 2.0));
3234 assertApprox(t1, t2 - tol, t2 + tol);
3235
3236 t1 = curr;
3237 t1 *= 2.1;
3238 assert((t1 > t2) == true);
3239
3240 foreach (T; AliasSeq!(const TickDuration, immutable TickDuration))
3241 {
3242 T t = TickDuration.currSystemTick;
3243 assert(!__traits(compiles, t *= 12));
3244 assert(!__traits(compiles, t *= 12.0));
3245 }
3246 }
3247
3248
3249 /++
3250 The legal types of arithmetic for $(D TickDuration) using this operator
3251 overload are
3252
3253 $(TABLE
3254 $(TR $(TD TickDuration) $(TD /) $(TD long) $(TD -->) $(TD TickDuration))
3255 $(TR $(TD TickDuration) $(TD /) $(TD floating point) $(TD -->) $(TD TickDuration))
3256 )
3257
3258 Params:
3259 value = The value to divide from this $(D TickDuration).
3260
3261 Throws:
3262 $(D TimeException) if an attempt to divide by $(D 0) is made.
3263 +/
3264 void opOpAssign(string op, T)(T value) @safe pure
3265 if (op == "/" &&
3266 (__traits(isIntegral, T) || __traits(isFloating, T)))
3267 {
3268 if (value == 0)
3269 throw new TimeException("Attempted division by 0.");
3270
3271 length = cast(long)(length / value);
3272 }
3273
3274 version (CoreUnittest) unittest
3275 {
3276 immutable curr = TickDuration.currSystemTick;
3277 immutable t1 = curr;
3278 TickDuration t2 = curr + curr;
3279 t2 /= 2;
3280 assert((t1 == t2) == true);
3281
3282 t2 = curr + curr;
3283 t2 /= 2.0;
3284 immutable tol = TickDuration(cast(long)(_abs(t2.length) * double.epsilon / 2.0));
3285 assertApprox(t1, t2 - tol, t2 + tol);
3286
3287 t2 = curr + curr;
3288 t2 /= 2.1;
3289 assert((t1 > t2) == true);
3290
3291 _assertThrown!TimeException(t2 /= 0);
3292
3293 foreach (T; AliasSeq!(const TickDuration, immutable TickDuration))
3294 {
3295 T t = TickDuration.currSystemTick;
3296 assert(!__traits(compiles, t /= 12));
3297 assert(!__traits(compiles, t /= 12.0));
3298 }
3299 }
3300
3301
3302 /++
3303 The legal types of arithmetic for $(D TickDuration) using this operator
3304 overload are
3305
3306 $(TABLE
3307 $(TR $(TD TickDuration) $(TD *) $(TD long) $(TD -->) $(TD TickDuration))
3308 $(TR $(TD TickDuration) $(TD *) $(TD floating point) $(TD -->) $(TD TickDuration))
3309 )
3310
3311 Params:
3312 value = The value to divide from this $(D TickDuration).
3313 +/
3314 TickDuration opBinary(string op, T)(T value) @safe const pure nothrow @nogc
3315 if (op == "*" &&
3316 (__traits(isIntegral, T) || __traits(isFloating, T)))
3317 {
3318 return TickDuration(cast(long)(length * value));
3319 }
3320
3321 version (CoreUnittest) unittest
3322 {
3323 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
3324 {
3325 T t1 = TickDuration.currSystemTick;
3326 T t2 = t1 + t1;
3327 assert((t1 * 2 == t2) == true);
3328 immutable tol = TickDuration(cast(long)(_abs(t1.length) * double.epsilon * 2.0));
3329 assertApprox(t1 * 2.0, t2 - tol, t2 + tol);
3330 assert((t1 * 2.1 > t2) == true);
3331 }
3332 }
3333
3334
3335 /++
3336 The legal types of arithmetic for $(D TickDuration) using this operator
3337 overload are
3338
3339 $(TABLE
3340 $(TR $(TD TickDuration) $(TD /) $(TD long) $(TD -->) $(TD TickDuration))
3341 $(TR $(TD TickDuration) $(TD /) $(TD floating point) $(TD -->) $(TD TickDuration))
3342 )
3343
3344 Params:
3345 value = The value to divide from this $(D TickDuration).
3346
3347 Throws:
3348 $(D TimeException) if an attempt to divide by $(D 0) is made.
3349 +/
3350 TickDuration opBinary(string op, T)(T value) @safe const pure
3351 if (op == "/" &&
3352 (__traits(isIntegral, T) || __traits(isFloating, T)))
3353 {
3354 if (value == 0)
3355 throw new TimeException("Attempted division by 0.");
3356
3357 return TickDuration(cast(long)(length / value));
3358 }
3359
3360 version (CoreUnittest) unittest
3361 {
3362 foreach (T; AliasSeq!(TickDuration, const TickDuration, immutable TickDuration))
3363 {
3364 T t1 = TickDuration.currSystemTick;
3365 T t2 = t1 + t1;
3366 assert((t2 / 2 == t1) == true);
3367 immutable tol = TickDuration(cast(long)(_abs(t2.length) * double.epsilon / 2.0));
3368 assertApprox(t2 / 2.0, t1 - tol, t1 + tol);
3369 assert((t2 / 2.1 < t1) == true);
3370
3371 _assertThrownDep!TimeException(t2 / 0);
3372 }
3373 }
3374
3375
3376 /++
3377 Params:
3378 ticks = The number of ticks in the TickDuration.
3379 +/
3380 @safe pure nothrow @nogc this(long ticks)
3381 {
3382 this.length = ticks;
3383 }
3384
3385 version (CoreUnittest) unittest
3386 {
3387 foreach (i; [-42, 0, 42])
3388 assert(TickDuration(i).length == i);
3389 }
3390
3391
3392 /++
3393 The current system tick. The number of ticks per second varies from
3394 system to system. $(D currSystemTick) uses a monotonic clock, so it's
3395 intended for precision timing by comparing relative time values, not for
3396 getting the current system time.
3397
3398 On Windows, $(D QueryPerformanceCounter) is used. On Mac OS X,
3399 $(D mach_absolute_time) is used, while on other Posix systems,
3400 $(D clock_gettime) is used. If $(D mach_absolute_time) or
3401 $(D clock_gettime) is unavailable, then Posix systems use
3402 $(D gettimeofday) (the decision is made when $(D TickDuration) is
3403 compiled), which unfortunately, is not monotonic, but if
3404 $(D mach_absolute_time) and $(D clock_gettime) aren't available, then
3405 $(D gettimeofday) is the best that there is.
3406
3407 $(RED Warning):
3408 On some systems, the monotonic clock may stop counting when
3409 the computer goes to sleep or hibernates. So, the monotonic
3410 clock could be off if that occurs. This is known to happen
3411 on Mac OS X. It has not been tested whether it occurs on
3412 either Windows or on Linux.
3413
3414 Throws:
3415 $(D TimeException) if it fails to get the time.
3416 +/
3417 static @property TickDuration currSystemTick() @trusted nothrow @nogc
3418 {
3419 import core.internal.abort : abort;
3420 version (Windows)
3421 {
3422 ulong ticks = void;
3423 QueryPerformanceCounter(cast(long*)&ticks);
3424 return TickDuration(ticks);
3425 }
3426 else version (Darwin)
3427 {
3428 static if (is(typeof(mach_absolute_time)))
3429 return TickDuration(cast(long)mach_absolute_time());
3430 else
3431 {
3432 timeval tv = void;
3433 gettimeofday(&tv, null);
3434 return TickDuration(tv.tv_sec * TickDuration.ticksPerSec +
3435 tv.tv_usec * TickDuration.ticksPerSec / 1000 / 1000);
3436 }
3437 }
3438 else version (Posix)
3439 {
3440 static if (is(typeof(clock_gettime)))
3441 {
3442 timespec ts = void;
3443 immutable error = clock_gettime(CLOCK_MONOTONIC, &ts);
3444 // CLOCK_MONOTONIC is supported and if tv_sec is long or larger
3445 // overflow won't happen before 292 billion years A.D.
3446 static if (ts.tv_sec.max < long.max)
3447 {
3448 if (error)
3449 {
3450 import core.internal.abort : abort;
3451 abort("Call to clock_gettime failed.");
3452 }
3453 }
3454 return TickDuration(ts.tv_sec * TickDuration.ticksPerSec +
3455 ts.tv_nsec * TickDuration.ticksPerSec / 1000 / 1000 / 1000);
3456 }
3457 else
3458 {
3459 timeval tv = void;
3460 gettimeofday(&tv, null);
3461 return TickDuration(tv.tv_sec * TickDuration.ticksPerSec +
3462 tv.tv_usec * TickDuration.ticksPerSec / 1000 / 1000);
3463 }
3464 }
3465 }
3466
3467 version (CoreUnittest) @safe nothrow unittest
3468 {
3469 assert(TickDuration.currSystemTick.length > 0);
3470 }
3471 }
3472
3473 /++
3474 Generic way of converting between two time units. Conversions to smaller
3475 units use truncating division. Years and months can be converted to each
3476 other, small units can be converted to each other, but years and months
3477 cannot be converted to or from smaller units (due to the varying number
3478 of days in a month or year).
3479
3480 Params:
3481 from = The units of time to convert from.
3482 to = The units of time to convert to.
3483 value = The value to convert.
3484 +/
3485 long convert(string from, string to)(long value) @safe pure nothrow @nogc
3486 if (((from == "weeks" ||
3487 from == "days" ||
3488 from == "hours" ||
3489 from == "minutes" ||
3490 from == "seconds" ||
3491 from == "msecs" ||
3492 from == "usecs" ||
3493 from == "hnsecs" ||
3494 from == "nsecs") &&
3495 (to == "weeks" ||
3496 to == "days" ||
3497 to == "hours" ||
3498 to == "minutes" ||
3499 to == "seconds" ||
3500 to == "msecs" ||
3501 to == "usecs" ||
3502 to == "hnsecs" ||
3503 to == "nsecs")) ||
3504 ((from == "years" || from == "months") && (to == "years" || to == "months")))
3505 {
3506 static if (from == "years")
3507 {
3508 static if (to == "years")
3509 return value;
3510 else static if (to == "months")
3511 return value * 12;
3512 else
3513 static assert(0, "A generic month or year cannot be converted to or from smaller units.");
3514 }
3515 else static if (from == "months")
3516 {
3517 static if (to == "years")
3518 return value / 12;
3519 else static if (to == "months")
3520 return value;
3521 else
3522 static assert(0, "A generic month or year cannot be converted to or from smaller units.");
3523 }
3524 else static if (from == "nsecs" && to == "nsecs")
3525 return value;
3526 else static if (from == "nsecs")
3527 return convert!("hnsecs", to)(value / 100);
3528 else static if (to == "nsecs")
3529 return convert!(from, "hnsecs")(value) * 100;
3530 else
3531 return (hnsecsPer!from * value) / hnsecsPer!to;
3532 }
3533
3534 ///
3535 unittest
3536 {
3537 assert(convert!("years", "months")(1) == 12);
3538 assert(convert!("months", "years")(12) == 1);
3539
3540 assert(convert!("weeks", "days")(1) == 7);
3541 assert(convert!("hours", "seconds")(1) == 3600);
3542 assert(convert!("seconds", "days")(1) == 0);
3543 assert(convert!("seconds", "days")(86_400) == 1);
3544
3545 assert(convert!("nsecs", "nsecs")(1) == 1);
3546 assert(convert!("nsecs", "hnsecs")(1) == 0);
3547 assert(convert!("hnsecs", "nsecs")(1) == 100);
3548 assert(convert!("nsecs", "seconds")(1) == 0);
3549 assert(convert!("seconds", "nsecs")(1) == 1_000_000_000);
3550 }
3551
3552 unittest
3553 {
3554 foreach (units; AliasSeq!("weeks", "days", "hours", "seconds", "msecs", "usecs", "hnsecs", "nsecs"))
3555 {
3556 static assert(!__traits(compiles, convert!("years", units)(12)), units);
3557 static assert(!__traits(compiles, convert!(units, "years")(12)), units);
3558 }
3559
3560 foreach (units; AliasSeq!("years", "months", "weeks", "days",
3561 "hours", "seconds", "msecs", "usecs", "hnsecs", "nsecs"))
3562 {
3563 assert(convert!(units, units)(12) == 12);
3564 }
3565
3566 assert(convert!("weeks", "hnsecs")(1) == 6_048_000_000_000L);
3567 assert(convert!("days", "hnsecs")(1) == 864_000_000_000L);
3568 assert(convert!("hours", "hnsecs")(1) == 36_000_000_000L);
3569 assert(convert!("minutes", "hnsecs")(1) == 600_000_000L);
3570 assert(convert!("seconds", "hnsecs")(1) == 10_000_000L);
3571 assert(convert!("msecs", "hnsecs")(1) == 10_000);
3572 assert(convert!("usecs", "hnsecs")(1) == 10);
3573
3574 assert(convert!("hnsecs", "weeks")(6_048_000_000_000L) == 1);
3575 assert(convert!("hnsecs", "days")(864_000_000_000L) == 1);
3576 assert(convert!("hnsecs", "hours")(36_000_000_000L) == 1);
3577 assert(convert!("hnsecs", "minutes")(600_000_000L) == 1);
3578 assert(convert!("hnsecs", "seconds")(10_000_000L) == 1);
3579 assert(convert!("hnsecs", "msecs")(10_000) == 1);
3580 assert(convert!("hnsecs", "usecs")(10) == 1);
3581
3582 assert(convert!("weeks", "days")(1) == 7);
3583 assert(convert!("days", "weeks")(7) == 1);
3584
3585 assert(convert!("days", "hours")(1) == 24);
3586 assert(convert!("hours", "days")(24) == 1);
3587
3588 assert(convert!("hours", "minutes")(1) == 60);
3589 assert(convert!("minutes", "hours")(60) == 1);
3590
3591 assert(convert!("minutes", "seconds")(1) == 60);
3592 assert(convert!("seconds", "minutes")(60) == 1);
3593
3594 assert(convert!("seconds", "msecs")(1) == 1000);
3595 assert(convert!("msecs", "seconds")(1000) == 1);
3596
3597 assert(convert!("msecs", "usecs")(1) == 1000);
3598 assert(convert!("usecs", "msecs")(1000) == 1);
3599
3600 assert(convert!("usecs", "hnsecs")(1) == 10);
3601 assert(convert!("hnsecs", "usecs")(10) == 1);
3602
3603 assert(convert!("weeks", "nsecs")(1) == 604_800_000_000_000L);
3604 assert(convert!("days", "nsecs")(1) == 86_400_000_000_000L);
3605 assert(convert!("hours", "nsecs")(1) == 3_600_000_000_000L);
3606 assert(convert!("minutes", "nsecs")(1) == 60_000_000_000L);
3607 assert(convert!("seconds", "nsecs")(1) == 1_000_000_000L);
3608 assert(convert!("msecs", "nsecs")(1) == 1_000_000);
3609 assert(convert!("usecs", "nsecs")(1) == 1000);
3610 assert(convert!("hnsecs", "nsecs")(1) == 100);
3611
3612 assert(convert!("nsecs", "weeks")(604_800_000_000_000L) == 1);
3613 assert(convert!("nsecs", "days")(86_400_000_000_000L) == 1);
3614 assert(convert!("nsecs", "hours")(3_600_000_000_000L) == 1);
3615 assert(convert!("nsecs", "minutes")(60_000_000_000L) == 1);
3616 assert(convert!("nsecs", "seconds")(1_000_000_000L) == 1);
3617 assert(convert!("nsecs", "msecs")(1_000_000) == 1);
3618 assert(convert!("nsecs", "usecs")(1000) == 1);
3619 assert(convert!("nsecs", "hnsecs")(100) == 1);
3620 }
3621
3622 /++
3623 Exception type used by core.time.
3624 +/
3625 class TimeException : Exception
3626 {
3627 /++
3628 Params:
3629 msg = The message for the exception.
3630 file = The file where the exception occurred.
3631 line = The line number where the exception occurred.
3632 next = The previous exception in the chain of exceptions, if any.
3633 +/
3634 this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null) @safe pure nothrow
3635 {
3636 super(msg, file, line, next);
3637 }
3638
3639 /++
3640 Params:
3641 msg = The message for the exception.
3642 next = The previous exception in the chain of exceptions.
3643 file = The file where the exception occurred.
3644 line = The line number where the exception occurred.
3645 +/
3646 this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__) @safe pure nothrow
3647 {
3648 super(msg, file, line, next);
3649 }
3650 }
3651
3652 unittest
3653 {
3654 {
3655 auto e = new TimeException("hello");
3656 assert(e.msg == "hello");
3657 assert(e.file == __FILE__);
3658 assert(e.line == __LINE__ - 3);
3659 assert(e.next is null);
3660 }
3661
3662 {
3663 auto next = new Exception("foo");
3664 auto e = new TimeException("goodbye", next);
3665 assert(e.msg == "goodbye");
3666 assert(e.file == __FILE__);
3667 assert(e.line == __LINE__ - 3);
3668 assert(e.next is next);
3669 }
3670 }
3671
3672
3673
3674 /++
3675 Returns the absolute value of a duration.
3676 +/
3677 Duration abs(Duration duration) @safe pure nothrow @nogc
3678 {
3679 return Duration(_abs(duration._hnsecs));
3680 }
3681
3682 /++ Ditto +/
3683 deprecated("TickDuration has been deprecated, please use Duration or MonoTime instead")
3684 TickDuration abs(TickDuration duration) @safe pure nothrow @nogc
3685 {
3686 return TickDuration(_abs(duration.length));
3687 }
3688
3689 unittest
3690 {
3691 assert(abs(dur!"msecs"(5)) == dur!"msecs"(5));
3692 assert(abs(dur!"msecs"(-5)) == dur!"msecs"(5));
3693 }
3694
3695 deprecated unittest
3696 {
3697 assert((abs(TickDuration(17)) == TickDuration(17)) == true);
3698 assert((abs(TickDuration(-17)) == TickDuration(17)) == true);
3699 }
3700
3701
3702 //==============================================================================
3703 // Private Section.
3704 //
3705 // Much of this is a copy or simplified copy of what's in std.datetime.
3706 //==============================================================================
3707 private:
3708
3709
3710 /+
3711 Template to help with converting between time units.
3712 +/
3713 template hnsecsPer(string units)
3714 if (units == "weeks" ||
3715 units == "days" ||
3716 units == "hours" ||
3717 units == "minutes" ||
3718 units == "seconds" ||
3719 units == "msecs" ||
3720 units == "usecs" ||
3721 units == "hnsecs")
3722 {
3723 static if (units == "hnsecs")
3724 enum hnsecsPer = 1L;
3725 else static if (units == "usecs")
3726 enum hnsecsPer = 10L;
3727 else static if (units == "msecs")
3728 enum hnsecsPer = 1000 * hnsecsPer!"usecs";
3729 else static if (units == "seconds")
3730 enum hnsecsPer = 1000 * hnsecsPer!"msecs";
3731 else static if (units == "minutes")
3732 enum hnsecsPer = 60 * hnsecsPer!"seconds";
3733 else static if (units == "hours")
3734 enum hnsecsPer = 60 * hnsecsPer!"minutes";
3735 else static if (units == "days")
3736 enum hnsecsPer = 24 * hnsecsPer!"hours";
3737 else static if (units == "weeks")
3738 enum hnsecsPer = 7 * hnsecsPer!"days";
3739 }
3740
3741 /+
3742 Splits out a particular unit from hnsecs and gives you the value for that
3743 unit and the remaining hnsecs. It really shouldn't be used unless all units
3744 larger than the given units have already been split out.
3745
3746 Params:
3747 units = The units to split out.
3748 hnsecs = The current total hnsecs. Upon returning, it is the hnsecs left
3749 after splitting out the given units.
3750
3751 Returns:
3752 The number of the given units from converting hnsecs to those units.
3753 +/
3754 long splitUnitsFromHNSecs(string units)(ref long hnsecs) @safe pure nothrow @nogc
3755 if (units == "weeks" ||
3756 units == "days" ||
3757 units == "hours" ||
3758 units == "minutes" ||
3759 units == "seconds" ||
3760 units == "msecs" ||
3761 units == "usecs" ||
3762 units == "hnsecs")
3763 {
3764 immutable value = convert!("hnsecs", units)(hnsecs);
3765 hnsecs -= convert!(units, "hnsecs")(value);
3766
3767 return value;
3768 }
3769
3770 unittest
3771 {
3772 auto hnsecs = 2595000000007L;
3773 immutable days = splitUnitsFromHNSecs!"days"(hnsecs);
3774 assert(days == 3);
3775 assert(hnsecs == 3000000007);
3776
3777 immutable minutes = splitUnitsFromHNSecs!"minutes"(hnsecs);
3778 assert(minutes == 5);
3779 assert(hnsecs == 7);
3780 }
3781
3782 /+
3783 Whether all of the given strings are among the accepted strings.
3784 +/
3785 bool allAreAcceptedUnits(acceptedUnits...)(scope string[] units)
3786 {
3787 foreach (unit; units)
3788 {
3789 bool found = false;
3790 foreach (acceptedUnit; acceptedUnits)
3791 {
3792 if (unit == acceptedUnit)
3793 {
3794 found = true;
3795 break;
3796 }
3797 }
3798 if (!found)
3799 return false;
3800 }
3801 return true;
3802 }
3803
3804 unittest
3805 {
3806 assert(allAreAcceptedUnits!("hours", "seconds")(["seconds", "hours"]));
3807 assert(!allAreAcceptedUnits!("hours", "seconds")(["minutes", "hours"]));
3808 assert(!allAreAcceptedUnits!("hours", "seconds")(["seconds", "minutes"]));
3809 assert(allAreAcceptedUnits!("days", "hours", "minutes", "seconds", "msecs")(["minutes"]));
3810 assert(!allAreAcceptedUnits!("days", "hours", "minutes", "seconds", "msecs")(["usecs"]));
3811 assert(!allAreAcceptedUnits!("days", "hours", "minutes", "seconds", "msecs")(["secs"]));
3812 }
3813
3814
3815 /+
3816 Whether the given time unit strings are arranged in order from largest to
3817 smallest.
3818 +/
3819 bool unitsAreInDescendingOrder(scope string[] units)
3820 {
3821 if (units.length <= 1)
3822 return true;
3823
3824 immutable string[] timeStrings = ["nsecs", "hnsecs", "usecs", "msecs", "seconds",
3825 "minutes", "hours", "days", "weeks", "months", "years"];
3826 size_t currIndex = 42;
3827 foreach (i, timeStr; timeStrings)
3828 {
3829 if (units[0] == timeStr)
3830 {
3831 currIndex = i;
3832 break;
3833 }
3834 }
3835 assert(currIndex != 42);
3836
3837 foreach (unit; units[1 .. $])
3838 {
3839 size_t nextIndex = 42;
3840 foreach (i, timeStr; timeStrings)
3841 {
3842 if (unit == timeStr)
3843 {
3844 nextIndex = i;
3845 break;
3846 }
3847 }
3848 assert(nextIndex != 42);
3849
3850 if (currIndex <= nextIndex)
3851 return false;
3852 currIndex = nextIndex;
3853 }
3854 return true;
3855 }
3856
3857 unittest
3858 {
3859 assert(unitsAreInDescendingOrder(["years", "months", "weeks", "days", "hours", "minutes",
3860 "seconds", "msecs", "usecs", "hnsecs", "nsecs"]));
3861 assert(unitsAreInDescendingOrder(["weeks", "hours", "msecs"]));
3862 assert(unitsAreInDescendingOrder(["days", "hours", "minutes"]));
3863 assert(unitsAreInDescendingOrder(["hnsecs"]));
3864 assert(!unitsAreInDescendingOrder(["days", "hours", "hours"]));
3865 assert(!unitsAreInDescendingOrder(["days", "hours", "days"]));
3866 }
3867
3868 version (Darwin)
3869 long machTicksPerSecond() @nogc nothrow
3870 {
3871 // Be optimistic that ticksPerSecond (1e9*denom/numer) is integral. So far
3872 // so good on Darwin based platforms OS X, iOS.
3873 import core.internal.abort : abort;
3874 mach_timebase_info_data_t info;
3875 if (mach_timebase_info(&info) != 0)
3876 abort("Failed in mach_timebase_info().");
3877
3878 long scaledDenom = 1_000_000_000L * info.denom;
3879 if (scaledDenom % info.numer != 0)
3880 abort("Non integral ticksPerSecond from mach_timebase_info.");
3881 return scaledDenom / info.numer;
3882 }
3883
3884 /+
3885 Local version of abs, since std.math.abs is in Phobos, not druntime.
3886 +/
3887 long _abs(long val) @safe pure nothrow @nogc
3888 {
3889 return val >= 0 ? val : -val;
3890 }
3891
3892 double _abs(double val) @safe pure nothrow @nogc
3893 {
3894 return val >= 0.0 ? val : -val;
3895 }
3896
3897
3898 version (CoreUnittest)
3899 string doubleToString(double value) @safe pure nothrow
3900 {
3901 string result;
3902 if (value < 0 && cast(long)value == 0)
3903 result = "-0";
3904 else
3905 result = signedToTempString(cast(long)value).idup;
3906 result ~= '.';
3907 result ~= unsignedToTempString(cast(ulong)(_abs((value - cast(long)value) * 1_000_000) + .5));
3908
3909 while (result[$-1] == '0')
3910 result = result[0 .. $-1];
3911 return result;
3912 }
3913
3914 unittest
3915 {
3916 auto a = 1.337;
3917 auto aStr = doubleToString(a);
3918 assert(aStr == "1.337", aStr);
3919
3920 a = 0.337;
3921 aStr = doubleToString(a);
3922 assert(aStr == "0.337", aStr);
3923
3924 a = -0.337;
3925 aStr = doubleToString(a);
3926 assert(aStr == "-0.337", aStr);
3927 }
3928
3929 version (CoreUnittest) const(char)* numToStringz()(long value) @trusted pure nothrow
3930 {
3931 return (signedToTempString(value) ~ "\0").ptr;
3932 }
3933
3934
3935 /+
3936 dmd @@@BUG18223@@@
3937 A selective import of `AliasSeq` happens to bleed through and causes symbol clashes downstream.
3938 +/
3939 version (none)
3940 import core.internal.traits : AliasSeq;
3941 else
3942 import core.internal.traits;
3943
3944
3945 /+ An adjusted copy of std.exception.assertThrown. +/
3946 version (CoreUnittest) void _assertThrown(T : Throwable = Exception, E)
3947 (lazy E expression,
3948 string msg = null,
3949 string file = __FILE__,
3950 size_t line = __LINE__)
3951 {
3952 bool thrown = false;
3953
3954 try
3955 expression();
3956 catch (T t)
3957 thrown = true;
3958
3959 if (!thrown)
3960 {
3961 immutable tail = msg.length == 0 ? "." : ": " ~ msg;
3962
3963 throw new AssertError("assertThrown() failed: No " ~ T.stringof ~ " was thrown" ~ tail, file, line);
3964 }
3965 }
3966
3967 unittest
3968 {
3969
3970 void throwEx(Throwable t)
3971 {
3972 throw t;
3973 }
3974
3975 void nothrowEx()
3976 {}
3977
3978 try
3979 _assertThrown!Exception(throwEx(new Exception("It's an Exception")));
3980 catch (AssertError)
3981 assert(0);
3982
3983 try
3984 _assertThrown!Exception(throwEx(new Exception("It's an Exception")), "It's a message");
3985 catch (AssertError)
3986 assert(0);
3987
3988 try
3989 _assertThrown!AssertError(throwEx(new AssertError("It's an AssertError", __FILE__, __LINE__)));
3990 catch (AssertError)
3991 assert(0);
3992
3993 try
3994 _assertThrown!AssertError(throwEx(new AssertError("It's an AssertError", __FILE__, __LINE__)), "It's a message");
3995 catch (AssertError)
3996 assert(0);
3997
3998
3999 {
4000 bool thrown = false;
4001 try
4002 _assertThrown!Exception(nothrowEx());
4003 catch (AssertError)
4004 thrown = true;
4005
4006 assert(thrown);
4007 }
4008
4009 {
4010 bool thrown = false;
4011 try
4012 _assertThrown!Exception(nothrowEx(), "It's a message");
4013 catch (AssertError)
4014 thrown = true;
4015
4016 assert(thrown);
4017 }
4018
4019 {
4020 bool thrown = false;
4021 try
4022 _assertThrown!AssertError(nothrowEx());
4023 catch (AssertError)
4024 thrown = true;
4025
4026 assert(thrown);
4027 }
4028
4029 {
4030 bool thrown = false;
4031 try
4032 _assertThrown!AssertError(nothrowEx(), "It's a message");
4033 catch (AssertError)
4034 thrown = true;
4035
4036 assert(thrown);
4037 }
4038 }
4039
4040 version (CoreUnittest) deprecated void _assertThrownDep(T : Throwable = Exception, E)
4041 (lazy E expression,
4042 string msg = null,
4043 string file = __FILE__,
4044 size_t line = __LINE__)
4045 {
4046 bool thrown = false;
4047
4048 try
4049 expression();
4050 catch (T t)
4051 thrown = true;
4052
4053 if (!thrown)
4054 {
4055 immutable tail = msg.length == 0 ? "." : ": " ~ msg;
4056
4057 throw new AssertError("assertThrown() failed: No " ~ T.stringof ~ " was thrown" ~ tail, file, line);
4058 }
4059 }
4060
4061
4062
4063 version (CoreUnittest) void assertApprox(D, E)(D actual,
4064 E lower,
4065 E upper,
4066 string msg = "unittest failure",
4067 size_t line = __LINE__)
4068 if (is(D : const Duration) && is(E : const Duration))
4069 {
4070 if (actual < lower)
4071 throw new AssertError(msg ~ ": lower: " ~ actual.toString(), __FILE__, line);
4072 if (actual > upper)
4073 throw new AssertError(msg ~ ": upper: " ~ actual.toString(), __FILE__, line);
4074 }
4075
4076 version (CoreUnittest) deprecated void assertApprox(D, E)(D actual,
4077 E lower,
4078 E upper,
4079 string msg = "unittest failure",
4080 size_t line = __LINE__)
4081 if (is(D : const TickDuration) && is(E : const TickDuration))
4082 {
4083 if (actual.length < lower.length || actual.length > upper.length)
4084 {
4085 throw new AssertError(msg ~ (": [" ~ signedToTempString(lower.length) ~ "] [" ~
4086 signedToTempString(actual.length) ~ "] [" ~
4087 signedToTempString(upper.length) ~ "]").idup,
4088 __FILE__, line);
4089 }
4090 }
4091
4092 version (CoreUnittest) void assertApprox(MT)(MT actual,
4093 MT lower,
4094 MT upper,
4095 string msg = "unittest failure",
4096 size_t line = __LINE__)
4097 if (is(MT == MonoTimeImpl!type, ClockType type))
4098 {
4099 assertApprox(actual._ticks, lower._ticks, upper._ticks, msg, line);
4100 }
4101
4102 version (CoreUnittest) void assertApprox()(long actual,
4103 long lower,
4104 long upper,
4105 string msg = "unittest failure",
4106 size_t line = __LINE__)
4107 {
4108 if (actual < lower)
4109 throw new AssertError(msg ~ ": lower: " ~ signedToTempString(actual).idup, __FILE__, line);
4110 if (actual > upper)
4111 throw new AssertError(msg ~ ": upper: " ~ signedToTempString(actual).idup, __FILE__, line);
4112 }