pax_global_header00006660000000000000000000000064151443662230014520gustar00rootroot0000000000000052 comment=f9852571bd8727ddce91bc0f2e41eb88fa14d119 golang-github-sosodev-duration-1.3.0/000077500000000000000000000000001514436622300175535ustar00rootroot00000000000000golang-github-sosodev-duration-1.3.0/.github/000077500000000000000000000000001514436622300211135ustar00rootroot00000000000000golang-github-sosodev-duration-1.3.0/.github/dependabot.yml000066400000000000000000000003721514436622300237450ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: gomod directory: "/" schedule: interval: daily time: "11:00" open-pull-requests-limit: 10 - package-ecosystem: "github-actions" directory: "/" schedule: interval: daily time: "11:00" golang-github-sosodev-duration-1.3.0/.github/workflows/000077500000000000000000000000001514436622300231505ustar00rootroot00000000000000golang-github-sosodev-duration-1.3.0/.github/workflows/ci.yml000066400000000000000000000006571514436622300242760ustar00rootroot00000000000000on: [push, pull_request] name: CI jobs: test: strategy: matrix: go-version: [1.17.x, oldstable, stable] platform: [ubuntu-latest] runs-on: ${{ matrix.platform }} steps: - name: Install Go uses: actions/setup-go@v5 with: go-version: ${{ matrix.go-version }} - name: Checkout uses: actions/checkout@v4 - name: Test run: go test ./... golang-github-sosodev-duration-1.3.0/.github/workflows/spellchecker.yml000066400000000000000000000004051514436622300263360ustar00rootroot00000000000000name: spell checking on: [pull_request] jobs: typos: name: Spell Check with Typos runs-on: ubuntu-latest steps: - name: Checkout Actions Repository uses: actions/checkout@v4 - name: typos-action uses: crate-ci/typos@v1.21.0 golang-github-sosodev-duration-1.3.0/.gitignore000066400000000000000000000000061514436622300215370ustar00rootroot00000000000000.idea golang-github-sosodev-duration-1.3.0/LICENSE000066400000000000000000000020551514436622300205620ustar00rootroot00000000000000MIT License Copyright (c) 2022 Kyle McGough Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. golang-github-sosodev-duration-1.3.0/duration.go000066400000000000000000000166071514436622300217410ustar00rootroot00000000000000package duration import ( "encoding/json" "errors" "fmt" "math" "strconv" "strings" "time" "unicode" ) // Duration holds all the smaller units that make up the duration type Duration struct { Years float64 Months float64 Weeks float64 Days float64 Hours float64 Minutes float64 Seconds float64 Negative bool } const ( parsingPeriod = iota parsingTime hoursPerDay = 24 hoursPerWeek = hoursPerDay * 7 hoursPerMonth = hoursPerYear / 12 hoursPerYear = hoursPerDay * 365 nsPerSecond = 1000000000 nsPerMinute = nsPerSecond * 60 nsPerHour = nsPerMinute * 60 nsPerDay = nsPerHour * hoursPerDay nsPerWeek = nsPerHour * hoursPerWeek nsPerMonth = nsPerHour * hoursPerMonth nsPerYear = nsPerHour * hoursPerYear ) var ( // ErrUnexpectedInput is returned when an input in the duration string does not match expectations ErrUnexpectedInput = errors.New("unexpected input") ) // Parse attempts to parse the given duration string into a *Duration, // if parsing fails an error is returned instead. func Parse(d string) (*Duration, error) { state := parsingPeriod duration := &Duration{} num := "" var err error switch { case strings.HasPrefix(d, "P"): // standard duration case strings.HasPrefix(d, "-P"): // negative duration duration.Negative = true d = strings.TrimPrefix(d, "-") // remove the negative sign default: return nil, ErrUnexpectedInput } for _, char := range d { switch char { case 'P': if state != parsingPeriod { return nil, ErrUnexpectedInput } case 'T': state = parsingTime case 'Y': if state != parsingPeriod { return nil, ErrUnexpectedInput } duration.Years, err = strconv.ParseFloat(num, 64) if err != nil { return nil, err } num = "" case 'M': if state == parsingPeriod { duration.Months, err = strconv.ParseFloat(num, 64) if err != nil { return nil, err } num = "" } else if state == parsingTime { duration.Minutes, err = strconv.ParseFloat(num, 64) if err != nil { return nil, err } num = "" } case 'W': if state != parsingPeriod { return nil, ErrUnexpectedInput } duration.Weeks, err = strconv.ParseFloat(num, 64) if err != nil { return nil, err } num = "" case 'D': if state != parsingPeriod { return nil, ErrUnexpectedInput } duration.Days, err = strconv.ParseFloat(num, 64) if err != nil { return nil, err } num = "" case 'H': if state != parsingTime { return nil, ErrUnexpectedInput } duration.Hours, err = strconv.ParseFloat(num, 64) if err != nil { return nil, err } num = "" case 'S': if state != parsingTime { return nil, ErrUnexpectedInput } duration.Seconds, err = strconv.ParseFloat(num, 64) if err != nil { return nil, err } num = "" default: if unicode.IsNumber(char) || char == '.' { num += string(char) continue } return nil, ErrUnexpectedInput } } return duration, nil } // FromTimeDuration converts the given time.Duration into duration.Duration. // Note that for *Duration's with period values of a month or year that the duration becomes a bit fuzzy // since obviously those things vary month to month and year to year. func FromTimeDuration(d time.Duration) *Duration { duration := &Duration{} if d == 0 { return duration } if d < 0 { d = -d duration.Negative = true } if d.Hours() >= hoursPerYear { duration.Years = math.Floor(d.Hours() / hoursPerYear) d -= time.Duration(duration.Years) * nsPerYear } if d.Hours() >= hoursPerMonth { duration.Months = math.Floor(d.Hours() / hoursPerMonth) d -= time.Duration(duration.Months) * nsPerMonth } if d.Hours() >= hoursPerWeek { duration.Weeks = math.Floor(d.Hours() / hoursPerWeek) d -= time.Duration(duration.Weeks) * nsPerWeek } if d.Hours() >= hoursPerDay { duration.Days = math.Floor(d.Hours() / hoursPerDay) d -= time.Duration(duration.Days) * nsPerDay } if d.Hours() >= 1 { duration.Hours = math.Floor(d.Hours()) d -= time.Duration(duration.Hours) * nsPerHour } if d.Minutes() >= 1 { duration.Minutes = math.Floor(d.Minutes()) d -= time.Duration(duration.Minutes) * nsPerMinute } duration.Seconds = d.Seconds() return duration } // Format formats the given time.Duration into an ISO 8601 duration string (e.g., P1DT6H5M), // negative durations are prefixed with a minus sign, for a zero duration "PT0S" is returned. // Note that for *Duration's with period values of a month or year that the duration becomes a bit fuzzy // since obviously those things vary month to month and year to year. func Format(d time.Duration) string { return FromTimeDuration(d).String() } // ToTimeDuration converts the *Duration to the standard library's time.Duration. // Note that for *Duration's with period values of a month or year that the duration becomes a bit fuzzy // since obviously those things vary month to month and year to year. func (duration *Duration) ToTimeDuration() time.Duration { var timeDuration time.Duration // zero checks are here to avoid unnecessary math operations, on a duration such as `PT5M` if duration.Years != 0 { timeDuration += time.Duration(math.Round(duration.Years * nsPerYear)) } if duration.Months != 0 { timeDuration += time.Duration(math.Round(duration.Months * nsPerMonth)) } if duration.Weeks != 0 { timeDuration += time.Duration(math.Round(duration.Weeks * nsPerWeek)) } if duration.Days != 0 { timeDuration += time.Duration(math.Round(duration.Days * nsPerDay)) } if duration.Hours != 0 { timeDuration += time.Duration(math.Round(duration.Hours * nsPerHour)) } if duration.Minutes != 0 { timeDuration += time.Duration(math.Round(duration.Minutes * nsPerMinute)) } if duration.Seconds != 0 { timeDuration += time.Duration(math.Round(duration.Seconds * nsPerSecond)) } if duration.Negative { timeDuration = -timeDuration } return timeDuration } // String returns the ISO8601 duration string for the *Duration func (duration *Duration) String() string { d := "P" hasTime := false appendD := func(designator string, value float64, isTime bool) { if !hasTime && isTime { d += "T" hasTime = true } d += strconv.FormatFloat(value, 'f', -1, 64) + designator } if duration.Years != 0 { appendD("Y", duration.Years, false) } if duration.Months != 0 { appendD("M", duration.Months, false) } if duration.Weeks != 0 { appendD("W", duration.Weeks, false) } if duration.Days != 0 { appendD("D", duration.Days, false) } if duration.Hours != 0 { appendD("H", duration.Hours, true) } if duration.Minutes != 0 { appendD("M", duration.Minutes, true) } if duration.Seconds != 0 { appendD("S", duration.Seconds, true) } // if the duration is zero, return "PT0S" if d == "P" { d += "T0S" } if duration.Negative { return "-" + d } return d } // MarshalJSON satisfies the Marshaler interface by return a valid JSON string representation of the duration func (duration Duration) MarshalJSON() ([]byte, error) { return json.Marshal(duration.String()) } // UnmarshalJSON satisfies the Unmarshaler interface by return a valid JSON string representation of the duration func (duration *Duration) UnmarshalJSON(source []byte) error { durationString := "" err := json.Unmarshal(source, &durationString) if err != nil { return err } parsed, err := Parse(durationString) if err != nil { return fmt.Errorf("failed to parse duration: %w", err) } *duration = *parsed return nil } golang-github-sosodev-duration-1.3.0/duration_test.go000066400000000000000000000147541514436622300230010ustar00rootroot00000000000000package duration import ( "encoding/json" "reflect" "testing" "time" ) func TestParse(t *testing.T) { type args struct { d string } tests := []struct { name string args args want *Duration wantErr bool }{ { name: "invalid-duration-1", args: args{d: "T0S"}, want: nil, wantErr: true, }, { name: "invalid-duration-2", args: args{d: "P-T0S"}, want: nil, wantErr: true, }, { name: "invalid-duration-3", args: args{d: "PT0SP0D"}, want: nil, wantErr: true, }, { name: "period-only", args: args{d: "P4Y"}, want: &Duration{ Years: 4, }, wantErr: false, }, { name: "time-only-decimal", args: args{d: "PT2.5S"}, want: &Duration{ Seconds: 2.5, }, wantErr: false, }, { name: "full", args: args{d: "P3Y6M4DT12H30M5.5S"}, want: &Duration{ Years: 3, Months: 6, Days: 4, Hours: 12, Minutes: 30, Seconds: 5.5, }, wantErr: false, }, { name: "negative", args: args{d: "-PT5M"}, want: &Duration{ Minutes: 5, Negative: true, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := Parse(tt.args.d) if (err != nil) != tt.wantErr { t.Errorf("Parse() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("Parse() got = %v, want %v", got, tt.want) } }) } } func TestFromTimeDuration(t *testing.T) { tests := []struct { give time.Duration want *Duration }{ { give: 0, want: &Duration{}, }, { give: time.Minute * 94, want: &Duration{ Hours: 1, Minutes: 34, }, }, { give: -time.Second * 10, want: &Duration{ Seconds: 10, Negative: true, }, }, } for _, tt := range tests { t.Run(tt.give.String(), func(t *testing.T) { got := FromTimeDuration(tt.give) if !reflect.DeepEqual(got, tt.want) { t.Errorf("Format() got = %s, want %s", got, tt.want) } }) } } func TestFormat(t *testing.T) { tests := []struct { give time.Duration want string }{ { give: 0, want: "PT0S", }, { give: time.Minute * 94, want: "PT1H34M", }, { give: time.Hour * 72, want: "P3D", }, { give: time.Hour * 26, want: "P1DT2H", }, { give: time.Second * 465461651, want: "P14Y9M3DT12H54M11S", }, { give: -time.Hour * 99544, want: "-P11Y4M1W4D", }, { give: -time.Second * 10, want: "-PT10S", }, } for _, tt := range tests { t.Run(tt.want, func(t *testing.T) { got := Format(tt.give) if !reflect.DeepEqual(got, tt.want) { t.Errorf("Format() got = %s, want %s", got, tt.want) } }) } } func TestDuration_ToTimeDuration(t *testing.T) { type fields struct { Years float64 Months float64 Weeks float64 Days float64 Hours float64 Minutes float64 Seconds float64 Negative bool } tests := []struct { name string fields fields want time.Duration }{ { name: "seconds", fields: fields{ Seconds: 33.3, }, want: time.Second*33 + time.Millisecond*300, }, { name: "hours, minutes, and seconds", fields: fields{ Hours: 2, Minutes: 33, Seconds: 17, }, want: time.Hour*2 + time.Minute*33 + time.Second*17, }, { name: "days", fields: fields{ Days: 2, }, want: time.Hour * 24 * 2, }, { name: "weeks", fields: fields{ Weeks: 1, }, want: time.Hour * 24 * 7, }, { name: "fractional weeks", fields: fields{ Weeks: 12.5, }, want: time.Hour*24*7*12 + time.Hour*84, }, { name: "negative", fields: fields{ Hours: 2, Negative: true, }, want: -time.Hour * 2, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { duration := &Duration{ Years: tt.fields.Years, Months: tt.fields.Months, Weeks: tt.fields.Weeks, Days: tt.fields.Days, Hours: tt.fields.Hours, Minutes: tt.fields.Minutes, Seconds: tt.fields.Seconds, Negative: tt.fields.Negative, } if got := duration.ToTimeDuration(); got != tt.want { t.Errorf("ToTimeDuration() = %v, want %v", got, tt.want) } }) } } func TestDuration_String(t *testing.T) { duration, err := Parse("P3Y6M4DT12H30M5.5S") if err != nil { t.Fatal(err) } if duration.String() != "P3Y6M4DT12H30M5.5S" { t.Errorf("expected: %s, got: %s", "P3Y6M4DT12H30M5.5S", duration.String()) } duration.Seconds = 33.3333 if duration.String() != "P3Y6M4DT12H30M33.3333S" { t.Errorf("expected: %s, got: %s", "P3Y6M4DT12H30M33.3333S", duration.String()) } smallDuration, err := Parse("PT0.0000000000001S") if err != nil { t.Fatal(err) } if smallDuration.String() != "PT0.0000000000001S" { t.Errorf("expected: %s, got: %s", "PT0.0000000000001S", smallDuration.String()) } negativeDuration, err := Parse("-PT2H5M") if err != nil { t.Fatal(err) } if negativeDuration.String() != "-PT2H5M" { t.Errorf("expected: %s, got: %s", "-PT2H5M", negativeDuration.String()) } } func TestDuration_MarshalJSON(t *testing.T) { td, err := Parse("P3Y6M4DT12H30M5.5S") if err != nil { t.Fatal(err) } jsonVal, err := json.Marshal(struct { Dur *Duration `json:"d"` }{Dur: td}) if err != nil { t.Errorf("did not expect error: %s", err.Error()) } if string(jsonVal) != `{"d":"P3Y6M4DT12H30M5.5S"}` { t.Errorf("expected: %s, got: %s", `{"d":"P3Y6M4DT12H30M5.5S"}`, string(jsonVal)) } jsonVal, err = json.Marshal(struct { Dur Duration `json:"d"` }{Dur: *td}) if err != nil { t.Errorf("did not expect error: %s", err.Error()) } if string(jsonVal) != `{"d":"P3Y6M4DT12H30M5.5S"}` { t.Errorf("expected: %s, got: %s", `{"d":"P3Y6M4DT12H30M5.5S"}`, string(jsonVal)) } } func TestDuration_UnmarshalJSON(t *testing.T) { jsonStr := ` { "d": "P3Y6M4DT12H30M5.5S" } ` expected, err := Parse("P3Y6M4DT12H30M5.5S") if err != nil { t.Fatal(err) } var durStructPtr struct { Dur *Duration `json:"d"` } err = json.Unmarshal([]byte(jsonStr), &durStructPtr) if err != nil { t.Errorf("did not expect error: %s", err.Error()) } if !reflect.DeepEqual(durStructPtr.Dur, expected) { t.Errorf("JSON Unmarshal ptr got = %s, want %s", durStructPtr.Dur, expected) } var durStruct struct { Dur Duration `json:"d"` } err = json.Unmarshal([]byte(jsonStr), &durStruct) if err != nil { t.Errorf("did not expect error: %s", err.Error()) } if !reflect.DeepEqual(durStruct.Dur, *expected) { t.Errorf("JSON Unmarshal ptr got = %s, want %s", &(durStruct.Dur), expected) } } golang-github-sosodev-duration-1.3.0/go.mod000066400000000000000000000000541514436622300206600ustar00rootroot00000000000000module github.com/sosodev/duration go 1.17 golang-github-sosodev-duration-1.3.0/readme.md000066400000000000000000000027561514436622300213440ustar00rootroot00000000000000# duration [![Go Reference](https://pkg.go.dev/badge/github.com/sosodev/duration.svg)](https://pkg.go.dev/github.com/sosodev/duration) It's a Go module for parsing [ISO 8601 durations](https://en.wikipedia.org/wiki/ISO_8601#Durations) and converting them to the often much more useful `time.Duration`. ## why? ISO 8601 is a pretty common standard and sometimes these durations show up in the wild. ## installation `go get github.com/sosodev/duration` ## [usage](https://go.dev/play/p/Nz5akjy1c6W) ```go package main import ( "fmt" "time" "github.com/sosodev/duration" ) func main() { d, err := duration.Parse("P3Y6M4DT12H30M5.5S") if err != nil { panic(err) } fmt.Println(d.Years) // 3 fmt.Println(d.Months) // 6 fmt.Println(d.Days) // 4 fmt.Println(d.Hours) // 12 fmt.Println(d.Minutes) // 30 fmt.Println(d.Seconds) // 5.5 d, err = duration.Parse("PT33.3S") if err != nil { panic(err) } fmt.Println(d.ToTimeDuration() == time.Second*33+time.Millisecond*300) // true } ``` ## correctness This module aims to implement the ISO 8601 duration specification correctly. It properly supports fractional units and has unit tests that assert the correctness of it's parsing and conversion to a `time.Duration`. With that said durations with months or years specified will be converted to `time.Duration` with a little fuzziness. Since I couldn't find a standard value, and they obviously vary, for those I used `2.628e+15` nanoseconds for a month and `3.154e+16` nanoseconds for a year.