gob/datetime/duration.go
2023-11-03 20:33:26 +01:00

55 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package datetime
import (
"fmt"
)
// Unit est une unité de durée.
type Unit uint
// Duration est une durée entre deux repères de temps.
type Duration int
// NewDuration retourne une durée à partir d’une valeur et d’une unité.
func NewDuration(value int, unit Unit) Duration {
if unit == NoUnit {
return DurationNil
}
return (Duration(value) << bitsUnit) | Duration(unit)
}
// Value retourne la valeur de la durée, sans l’unité.
func (d Duration) Value() int { return int(d >> bitsUnit) }
// Unit retourne l’unité de durée.
func (d Duration) Unit() Unit { return Unit(d & maskUnit) }
// Duration retourne la valeur et l’unité de la durée.
func (d Duration) Duration() (int, Unit) { return d.Value(), d.Unit() }
// IsNil retourne vrai si la durée ne représente pas une durée valide.
func (d Duration) IsNil() bool { return d.Unit() == NoUnit }
// IsClock retourne vrai si la durée est dans une unité de temps sur 24h.
func (d Duration) IsClock() bool { u := d.Unit(); return u > NoUnit && u < Day }
// IsDate retourne vrai si la durée est dans une unité de date.
func (d Duration) IsDate() bool { return d.Unit() > Hour }
// Abs retourne la durée en valeur absolue.
func (d Duration) Abs() Duration { return NewDuration(abs(d.Value()), d.Unit()) }
// Neg retourne l’inverse négatif de la durée.
func (d Duration) Neg() Duration { return NewDuration(-d.Value(), d.Unit()) }
// String retourne la représentation textuelle de la durée.
func (d Duration) String() string {
if d.IsNil() {
return "-"
}
v, u := d.Value(), d.Unit()
return fmt.Sprintf("%d%c", v, unitToByte[u])
}