Repository navigation
Parse durations exactly and fix edge cases - #4
Merged
Merged
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Parseconverted each component withstrconv.ParseFloatandfmt.Sprintf("%f")before callingtime.ParseDuration. That rounding lost precision and left several edge cases. This replaces it with exact integer arithmetic: components are summed as 128-bit fixed-point nanoseconds and rounded once, with halves rounded away from zero.Fixes
PT0.0000001Sparsed as0s; it now gives100nsP1Mwas2629743.0012sinstead of2629743.00012stime.Durationvalues could not be parsed-Pand-PTreturned(0, nil); they now returnErrInvalidString,is now accepted as a decimal separator, as ISO 8601 allows (PT1,5S)Parsing is about three times faster, and allocations dropped from 14 to 2 per call.
Behaviour changes
The exported API is unchanged, but some results differ from v0.0.3:
-Pand-now returnErrInvalidStringI compared about 200,000 generated inputs against v0.0.3. Every difference falls into the categories above, and every result matches an exact reference calculation written with
math/big. Because results change, I suggest tagging this as v0.1.0.Tests and docs
time.Durationvalues and check errors witherrors.Is;TestCompareWithTimeParseDurationno longer ignores errors-P/-PT/-, months vs minutes, and the length limitFuzzParsechecks the error contract, that the sign of the result matches the input, and that adding-negates the result exactlygo get …@latestgo vetandgo test -racepass with 100% coverage on Go 1.27.4, and fuzzing found no failures.