From a2f7e0636d19c2e498bcb76a3772ef32bfd97f68 Mon Sep 17 00:00:00 2001 From: Takahiro Yaota Date: Fri, 11 Dec 2020 14:54:23 +0900 Subject: [PATCH] time: `-` operator overloading (#7259) --- vlib/time/time.v | 7 +++++++ vlib/time/time_test.v | 14 ++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/vlib/time/time.v b/vlib/time/time.v index 7479fec121..5afe6ffced 100644 --- a/vlib/time/time.v +++ b/vlib/time/time.v @@ -348,6 +348,13 @@ pub fn (t Time) str() string { return t.format_ss() } +// Time subtract using eperator overloading +pub fn (lhs Time) -(rhs Time) Duration { + lhs_micro := lhs.unix * 1000 * 1000 + u64(lhs.microsecond) + rhs_micro := rhs.unix * 1000 * 1000 + u64(rhs.microsecond) + return (i64(lhs_micro) - i64(rhs_micro)) * microsecond +} + fn convert_ctime(t C.tm, microsecond int) Time { return Time{ year: t.tm_year + 1900 diff --git a/vlib/time/time_test.v b/vlib/time/time_test.v index c348ce1c90..fd97f1e4b0 100644 --- a/vlib/time/time_test.v +++ b/vlib/time/time_test.v @@ -164,6 +164,20 @@ fn test_str() { assert '1980-07-11 21:23:42' == time_to_test.str() } +fn test_subtract() { + d_seconds := 3 + d_microseconds := 13 + duration := d_seconds * time.second + d_microseconds * time.microsecond + t1 := time_to_test + t2 := time.unix2(int(t1.unix) + d_seconds, t1.microsecond + d_microseconds) + d1 := t2 - t1 + d2 := t1 - t2 + assert d1 > 0 + assert d1 == duration + assert d2 < 0 + assert d2 == -duration +} + // not optimal test but will find obvious bugs fn test_now() { now := time.now()