period.ha (2136B)
1 // SPDX-License-Identifier: MPL-2.0 2 // (c) Hare authors <https://harelang.org> 3 4 // Represents a span of time in the Gregorian chronology, using nominal units of 5 // time. Used for chronological arithmetic. 6 export type period = struct { 7 years: i64, 8 months: i64, 9 weeks: i64, 10 days: i64, 11 hours: i64, 12 minutes: i64, 13 seconds: i64, 14 nanoseconds: i64, 15 }; 16 17 // Returns true if two [[period]]s are numerically equal, false otherwise. 18 export fn peq(pa: period, pb: period) bool = { 19 return ( 20 pa.years == pb.years 21 && pa.months == pb.months 22 && pa.weeks == pb.weeks 23 && pa.days == pb.days 24 && pa.hours == pb.hours 25 && pa.minutes == pb.minutes 26 && pa.seconds == pb.seconds 27 && pa.nanoseconds == pb.nanoseconds 28 ); 29 }; 30 31 // Returns the sum [[period]] of a set of periods. 32 export fn sum(ps: period...) period = { 33 let out = period { ... }; 34 for (let p &.. ps) { 35 out.years += p.years; 36 out.months += p.months; 37 out.weeks += p.weeks; 38 out.days += p.days; 39 out.hours += p.hours; 40 out.minutes += p.minutes; 41 out.seconds += p.seconds; 42 out.nanoseconds += p.nanoseconds; 43 }; 44 return out; 45 }; 46 47 // Returns a [[period]] with its fields negated. 48 export fn neg(p: period) period = period { 49 years = -p.years, 50 months = -p.months, 51 weeks = -p.weeks, 52 days = -p.days, 53 hours = -p.hours, 54 minutes = -p.minutes, 55 seconds = -p.seconds, 56 nanoseconds = -p.nanoseconds, 57 }; 58 59 // Returns a [[period]] with its fields made absolute and positive. 60 export fn abs(p: period) period = period { 61 years = if (p.years < 0) -p.years else p.years, 62 months = if (p.months < 0) -p.months else p.months, 63 weeks = if (p.weeks < 0) -p.weeks else p.weeks, 64 days = if (p.days < 0) -p.days else p.days, 65 hours = if (p.hours < 0) -p.hours else p.hours, 66 minutes = if (p.minutes < 0) -p.minutes else p.minutes, 67 seconds = if (p.seconds < 0) -p.seconds else p.seconds, 68 nanoseconds = if (p.nanoseconds < 0) -p.nanoseconds else p.nanoseconds, 69 };