pax_global_header00006660000000000000000000000064152035403620014512gustar00rootroot0000000000000052 comment=0a8d050977ff3d453039e25e53f99cee7b0ce938 strftime-1.2.0/000077500000000000000000000000001520354036200133475ustar00rootroot00000000000000strftime-1.2.0/.github/000077500000000000000000000000001520354036200147075ustar00rootroot00000000000000strftime-1.2.0/.github/FUNDING.yml000066400000000000000000000012061520354036200165230ustar00rootroot00000000000000# These are supported funding model platforms github: ["lestrrat"] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] strftime-1.2.0/.github/dependabot.yml000066400000000000000000000011311520354036200175330ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "gomod" directory: "/" schedule: interval: "daily" target-branch: "master" labels: - "go" - "dependencies" - "dependabot" - package-ecosystem: "gomod" directory: "/bench" schedule: interval: "daily" target-branch: "master" labels: - "go" - "dependencies" - "dependabot" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" target-branch: "master" labels: - "github-actions" - "dependencies" - "dependabot" strftime-1.2.0/.github/workflows/000077500000000000000000000000001520354036200167445ustar00rootroot00000000000000strftime-1.2.0/.github/workflows/ci.yml000066400000000000000000000023561520354036200200700ustar00rootroot00000000000000name: CI on: [push, pull_request] jobs: build: runs-on: ubuntu-latest strategy: matrix: go: [ '1.23', '1.22', '1.21' ] tags: [ 'strftime_native_errors', '' ] fail-fast: false name: "Go ${{ matrix.go }} test (tags: ${{ matrix.tags }})" steps: - name: Checkout repository uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Cache Go modules uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 with: path: | ~/go/pkg/mod ~/.cache/go-build key: ${{ runner.os }}-go-${{ matrix.go }}-${{ hashFiles('**/go.sum') }} restore-keys: | ${{ runner.os }}-go-${{ matrix.go }}- - name: Install Go stable version uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: go-version: ${{ matrix.go }} check-latest: true - name: Test with coverage run: make STRFTIME_TAGS=${{ matrix.tags }} cover - name: Upload code coverage to codecov if: matrix.go == '1.23' uses: codecov/codecov-action@e79a6962e0d4c0c17b229090214935d2e33f8354 # v6.0.1 with: file: ./coverage.out strftime-1.2.0/.github/workflows/lint.yml000066400000000000000000000010241520354036200204320ustar00rootroot00000000000000name: lint on: [push] jobs: golangci: name: lint runs-on: ubuntu-latest steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 with: go-version-file: "go.mod" check-latest: true - uses: golangci/golangci-lint-action@1e7e51e771db61008b38414a730f564565cf7c20 # v9.2.0 with: version: v2.11.4 - name: Run go vet run: | go vet ./... strftime-1.2.0/.gitignore000066400000000000000000000004121520354036200153340ustar00rootroot00000000000000# Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe *.test *.prof strftime-1.2.0/.golangci.yml000066400000000000000000000026111520354036200157330ustar00rootroot00000000000000version: "2" linters: default: all disable: - cyclop - depguard - dupl - err113 - errorlint - exhaustive - funcorder - funlen - gochecknoglobals - gochecknoinits - gocognit - gocritic - gocyclo - godot - godox - gosec - gosmopolitan - govet - inamedparam - ireturn - lll - maintidx - makezero - mnd - nakedret - nestif - nlreturn - noinlineerr - nonamedreturns - paralleltest - perfsprint - staticcheck - recvcheck - tagliatelle - testifylint - testpackage - thelper - varnamelen - wrapcheck - wsl - wsl_v5 settings: govet: disable: - shadow - fieldalignment enable-all: true exclusions: generated: lax presets: - comments - common-false-positives - legacy - std-error-handling rules: - linters: - contextcheck - exhaustruct path: /*.go - linters: - errcheck - errchkjson - forcetypeassert - goconst path: _test\.go paths: - third_party$ - builtin$ - examples$ issues: max-issues-per-linter: 0 max-same-issues: 0 formatters: enable: - gofmt - goimports exclusions: generated: lax paths: - third_party$ - builtin$ - examples$ strftime-1.2.0/Changes000066400000000000000000000043551520354036200146510ustar00rootroot00000000000000Changes ======= v1.2.0 - 21 May 2026 [New features] * Support a no-padding flag for numeric specifiers. A `-` (glibc) or `#` (Windows) flag placed between the `%` and the conversion specifier suppresses the leading zero/blank padding, e.g. `%-m` -> "1" instead of "01". (#91) * Add locale support for name-based specifiers (%A, %a, %B, %b, %p, etc.). A new `WithLocale` option accepts a `Locale`, with `DefaultLocale()` providing the English defaults. Supporting `MonthNames` / `WeekdayNames` types and a `LocaleOption` constructor are also exported. (#92) [Performance] * Speed up formatting and pattern compilation. (#93) [Bug fixes] * Fix the locking mechanism in the package-level `Lookup` function. (#76) [Miscellaneous] * Modernize CI and lint infrastructure. (#87) * Updated dependencies (testify, GitHub Actions, codecov). v1.1.1 - 29 Jul 2025 * Implement %G and %g (#67) v1.1.0 - 28 Aug 2024 [Miscellaneous] * github.com/pkg/errors has been removed (it has been two years :) * Updated build/test actions * Updated minimum required go version to go 1.21 * Fix week number handling v1.0.6 - 20 Apr 2022 [Miscellaneous] * Minimum go version is now go 1.13 * github.com/pkg/errors is going to be phased out in steps. In this release, users may opt-in to using native errors using `fmt.Errorf("%w")` by specifying the tag `strftime_native_errors`. In the next release, the default will be to use native errors, but users will be able to opt-in to using github.com/pkg/errors using a tag. The version after will remove github.com/pkg/errors. This is something that we normally would do over a major version upgrade but since we do not expect this library to receive API breaking changes in the near future and thus no v2 is expected, we have decided to do this over few non-major releases. v1.0.5 [New features] * `(strftime.Strftime).FormatBuffer([]byte, time.Time) []byte` has been added. This allows the user to provide the same underlying `[]byte` buffer for each call to `FormatBuffer`, which avoid allocation per call. * `%I` formatted midnight as `00`, where it should have been using `01` before v1.0.4 Apparently we have failed to provide Changes prior to v1.0.5 :( strftime-1.2.0/LICENSE000066400000000000000000000020511520354036200143520ustar00rootroot00000000000000MIT License Copyright (c) 2016 lestrrat 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. strftime-1.2.0/Makefile000066400000000000000000000010051520354036200150030ustar00rootroot00000000000000.PHONY: bench realclean cover viewcover test lint imports bench: go test -tags bench -benchmem -bench . @git checkout go.mod @rm go.sum realclean: rm coverage.out test: go test -v -race ./... cover: ifeq ($(strip $(STRFTIME_TAGS)),) go test -v -race -coverpkg=./... -coverprofile=coverage.out ./... else go test -v -tags $(STRFTIME_TAGS) -race -coverpkg=./... -coverprofile=coverage.out ./... endif viewcover: go tool cover -html=coverage.out lint: golangci-lint run ./... imports: goimports -w ./ strftime-1.2.0/README.md000066400000000000000000000277751520354036200146500ustar00rootroot00000000000000# strftime Fast strftime for Go [![](https://github.com/lestrrat-go/strftime/workflows/CI/badge.svg?branch=master)](https://github.com/lestrrat-go/strftime/actions?query=branch%3Amaster) [![Go Reference](https://pkg.go.dev/badge/github.com/lestrrat-go/strftime.svg)](https://pkg.go.dev/github.com/lestrrat-go/strftime) # SYNOPSIS ```go f, err := strftime.New(`.... pattern ...`) if err := f.Format(buf, time.Now()); err != nil { log.Println(err.Error()) } ``` # DESCRIPTION The goals for this library are * Optimized for the same pattern being called repeatedly * Be flexible about destination to write the results out * Be as complete as possible in terms of conversion specifications # API ## Format(string, time.Time) (string, error) Takes the pattern and the time, and formats it. This function is a utility function that recompiles the pattern every time the function is called. If you know beforehand that you will be formatting the same pattern multiple times, consider using `New` to create a `Strftime` object and reuse it. ## New(string) (\*Strftime, error) Takes the pattern and creates a new `Strftime` object. ## obj.Pattern() string Returns the pattern string used to create this `Strftime` object ## obj.Format(io.Writer, time.Time) error Formats the time according to the pre-compiled pattern, and writes the result to the specified `io.Writer` ## obj.FormatString(time.Time) string Formats the time according to the pre-compiled pattern, and returns the result string. # SUPPORTED CONVERSION SPECIFICATIONS | pattern | description | |:--------|:------------| | %A | national representation of the full weekday name | | %a | national representation of the abbreviated weekday | | %B | national representation of the full month name | | %b | national representation of the abbreviated month name | | %C | (year / 100) as decimal number; single digits are preceded by a zero | | %c | national representation of time and date | | %D | equivalent to %m/%d/%y | | %d | day of the month as a decimal number (01-31) | | %e | the day of the month as a decimal number (1-31); single digits are preceded by a blank | | %F | equivalent to %Y-%m-%d | | %G | the ISO week year with century as a decimal number with 4 digits | | %g | the ISO week year without century as a decimal number (00-99) with 2 digits | | %H | the hour (24-hour clock) as a decimal number (00-23) | | %h | same as %b | | %I | the hour (12-hour clock) as a decimal number (01-12) | | %j | the day of the year as a decimal number (001-366) | | %k | the hour (24-hour clock) as a decimal number (0-23); single digits are preceded by a blank | | %l | the hour (12-hour clock) as a decimal number (1-12); single digits are preceded by a blank | | %M | the minute as a decimal number (00-59) | | %m | the month as a decimal number (01-12) | | %n | a newline | | %p | national representation of either "ante meridiem" (a.m.) or "post meridiem" (p.m.) as appropriate. | | %R | equivalent to %H:%M | | %r | equivalent to %I:%M:%S %p | | %S | the second as a decimal number (00-60) | | %T | equivalent to %H:%M:%S | | %t | a tab | | %U | the week number of the year (Sunday as the first day of the week) as a decimal number (00-53) | | %u | the weekday (Monday as the first day of the week) as a decimal number (1-7) | | %V | the week number of the year (Monday as the first day of the week) as a decimal number (01-53) | | %v | equivalent to %e-%b-%Y | | %W | the week number of the year (Monday as the first day of the week) as a decimal number (00-53) | | %w | the weekday (Sunday as the first day of the week) as a decimal number (0-6) | | %X | national representation of the time | | %x | national representation of the date | | %Y | the year with century as a decimal number | | %y | the year without century as a decimal number (00-99) | | %Z | the time zone name | | %z | the time zone offset from UTC | | %% | a '%' | # NO-PADDING FLAG A `-` (glibc) or `#` (Windows) flag may be placed between the `%` and the conversion specifier to suppress the leading zero/blank padding on numeric fields. For example, given `2006-01-02 03:04:05`: | pattern | result | |---------|--------| | %m | 01 | | %-m | 1 | | %d | 02 | | %-d | 2 | | %H:%M | 03:04 | | %-H:%-M | 3:4 | The flag has no effect on non-numeric fields (e.g. `%-A` is identical to `%A`). # LOCALIZATION By default the name-producing specifiers (`%A`, `%a`, `%B`, `%b`, `%h`, `%p`) emit English. To localize them, build a `Locale` with `NewLocale` and pass it via `WithLocale`. The library ships no locale data of its own — you supply the names for your language: ```go french := strftime.NewLocale( strftime.WithMonths(strftime.MonthNames{ "janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre", }), strftime.WithWeekdays(strftime.WeekdayNames{ "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", }), // WithShortMonths, WithShortWeekdays, WithMeridiem ... optional ) s, _ := strftime.New(`%A %d %B %Y`, strftime.WithLocale(french)) // -> "lundi 02 janvier 2006" ``` `MonthNames` is indexed by month minus one (January is index 0); `WeekdayNames` is indexed by `time.Weekday` (Sunday is index 0). Any name left empty falls back to the English default, so a partial `Locale` never yields blank output. Numeric specifiers (`%d`, `%m`, `%Y`, ...) are locale-invariant and unaffected. `Locale` is an interface, so you can also implement it yourself to back the names with a map, computed values, or an external dataset. `DefaultLocale()` returns the English implementation. ## Inflected languages In some languages (Russian, Czech, Polish, Greek, ...) a month name changes form depending on whether it stands alone or appears next to a day number — e.g. Russian "январь" (stand-alone) vs "2 января" (in a date). Because a single `Locale` carries one form per name, format each context with its own compiled `Strftime`: ```go inDate, _ := strftime.New(`%d %B %Y`, strftime.WithLocale(ruInDate)) // января header, _ := strftime.New(`%B %Y`, strftime.WithLocale(ruStandalone)) // январь ``` # EXTENSIONS / CUSTOM SPECIFICATIONS This library in general tries to be POSIX compliant, but sometimes you just need that extra specification or two that is relatively widely used but is not included in the POSIX specification. For example, POSIX does not specify how to print out milliseconds, but popular implementations allow `%f` or `%L` to achieve this. For those instances, `strftime.Strftime` can be configured to use a custom set of specifications: ``` ss := strftime.NewSpecificationSet() ss.Set('L', ...) // provide implementation for `%L` // pass this new specification set to the strftime instance p, err := strftime.New(`%L`, strftime.WithSpecificationSet(ss)) p.Format(..., time.Now()) ``` The implementation must implement the `Appender` interface, which is ``` type Appender interface { Append([]byte, time.Time) []byte } ``` For commonly used extensions such as the millisecond example and Unix timestamp, we provide a default implementation so the user can do one of the following: ``` // (1) Pass a specification byte and the Appender // This allows you to pass arbitrary Appenders p, err := strftime.New( `%L`, strftime.WithSpecification('L', strftime.Milliseconds), ) // (2) Pass an option that knows to use strftime.Milliseconds p, err := strftime.New( `%L`, strftime.WithMilliseconds('L'), ) ``` Similarly for Unix Timestamp: ``` // (1) Pass a specification byte and the Appender // This allows you to pass arbitrary Appenders p, err := strftime.New( `%s`, strftime.WithSpecification('s', strftime.UnixSeconds), ) // (2) Pass an option that knows to use strftime.UnixSeconds p, err := strftime.New( `%s`, strftime.WithUnixSeconds('s'), ) ``` If a common specification is missing, please feel free to submit a PR (but please be sure to be able to defend how "common" it is) ## List of available extensions - [`Milliseconds`](https://pkg.go.dev/github.com/lestrrat-go/strftime?tab=doc#Milliseconds) (related option: [`WithMilliseconds`](https://pkg.go.dev/github.com/lestrrat-go/strftime?tab=doc#WithMilliseconds)); - [`Microseconds`](https://pkg.go.dev/github.com/lestrrat-go/strftime?tab=doc#Microseconds) (related option: [`WithMicroseconds`](https://pkg.go.dev/github.com/lestrrat-go/strftime?tab=doc#WithMicroseconds)); - [`UnixSeconds`](https://pkg.go.dev/github.com/lestrrat-go/strftime?tab=doc#UnixSeconds) (related option: [`WithUnixSeconds`](https://pkg.go.dev/github.com/lestrrat-go/strftime?tab=doc#WithUnixSeconds)). # PERFORMANCE / OTHER LIBRARIES The benchmarks live under `bench/` and compare this library against several others. ``` // AMD Ryzen 9 7900X3D, Linux/amd64 // go version go1.26.1 linux/amd64 % go test -benchmem -bench . goos: linux goarch: amd64 pkg: github.com/lestrrat-go/strftime/bench cpu: AMD Ryzen 9 7900X3D 12-Core Processor BenchmarkTebeka-24 728451 1458 ns/op 260 B/op 20 allocs/op BenchmarkJehiah-24 1898193 622.1 ns/op 256 B/op 17 allocs/op BenchmarkFastly-24 1356129 881.0 ns/op 168 B/op 6 allocs/op BenchmarkNcruces-24 5115555 230.7 ns/op 64 B/op 1 allocs/op BenchmarkNcrucesAppend-24 6263023 199.2 ns/op 0 B/op 0 allocs/op BenchmarkLestrrat-24 5860896 206.4 ns/op 128 B/op 2 allocs/op BenchmarkLestrratCachedString-24 6105082 189.2 ns/op 128 B/op 2 allocs/op BenchmarkLestrratCachedWriter-24 6648992 168.7 ns/op 64 B/op 1 allocs/op BenchmarkLestrratCachedFormatBuffer-24 8669540 136.7 ns/op 0 B/op 0 allocs/op PASS ok github.com/lestrrat-go/strftime/bench 13.281s ``` This library is the fastest of the bunch across every access pattern. The annotated list below ranks the relevant variants from fastest to slowest: | Import Path | ns/op | allocs | Note | |:------------------------------------|------:|-------:|:----------------------------------------------| | github.com/lestrrat-go/strftime | 136.7 | 0 | `FormatBuffer()` into a reused slice (cached) | | github.com/lestrrat-go/strftime | 168.7 | 1 | `Format()` to an `io.Writer` (cached) | | github.com/lestrrat-go/strftime | 189.2 | 2 | `FormatString()` (cached) | | github.com/ncruces/go-strftime | 199.2 | 0 | `AppendFormat()` | | github.com/lestrrat-go/strftime | 206.4 | 2 | package-level `Format()` (compiled patterns are cached) | | github.com/ncruces/go-strftime | 230.7 | 1 | `Format()` | | github.com/jehiah/go-strftime | 622.1 | 17 | | | github.com/fastly/go-utils/strftime | 881.0 | 6 | | | github.com/tebeka/strftime | 1458 | 20 | | The fastest path is reusing a `Strftime` object and appending into a slice you own (`FormatBuffer`), which allocates nothing. The package-level `Format()` caches compiled patterns internally (bounded), so even repeated one-off calls with the same pattern stay fast. However, depending on your pattern, this speed may vary. If you find a particular pattern that seems sluggish, please send in patches or tests. Please also note that this benchmark only uses the subset of conversion specifications that are supported by *ALL* of the libraries compared. Somethings to consider when making performance comparisons in the future: * Can it write to io.Writer? * Which `%specification` does it handle? strftime-1.2.0/appenders.go000066400000000000000000000241411520354036200156610ustar00rootroot00000000000000package strftime import ( "bytes" "fmt" "io" "strconv" "strings" "time" ) // These are all of the standard, POSIX compliant specifications. // Extensions should be in extensions.go var ( fullWeekDayName = StdlibFormat("Monday") abbrvWeekDayName = StdlibFormat("Mon") fullMonthName = StdlibFormat("January") abbrvMonthName = StdlibFormat("Jan") centuryDecimal = AppendFunc(appendCentury) timeAndDate = StdlibFormat("Mon Jan _2 15:04:05 2006") mdy = StdlibFormat("01/02/06") dayOfMonthZeroPad = StdlibFormat("02") dayOfMonthSpacePad = StdlibFormat("_2") ymd = StdlibFormat("2006-01-02") twentyFourHourClockZeroPad = StdlibFormat("15") twelveHourClockZeroPad = StdlibFormat("03") dayOfYear = AppendFunc(appendDayOfYear) twentyFourHourClockSpacePad = &hourPadded{twelveHour: false, pad: ' '} twelveHourClockSpacePad = &hourPadded{twelveHour: true, pad: ' '} minutesZeroPad = StdlibFormat("04") monthNumberZeroPad = StdlibFormat("01") newline = Verbatim("\n") ampm = StdlibFormat("PM") hm = StdlibFormat("15:04") imsp = hmsWAMPM{} secondsNumberZeroPad = StdlibFormat("05") hms = StdlibFormat("15:04:05") tab = Verbatim("\t") weekNumberSundayOrigin = weeknumberOffset(true) // week number of the year, Sunday first weekdayMondayOrigin = weekday(1) // monday as the first day, and 01 as the first value weekNumberMondayOriginOneOrigin = AppendFunc(appendWeekNumber) eby = StdlibFormat("_2-Jan-2006") weekyear = AppendFunc(appendWeekYear) // week year, with century weekyearNoCentury = AppendFunc(appendWeekYearNoCentury) // week year, without century // monday as the first day, and 00 as the first value weekNumberMondayOrigin = weeknumberOffset(false) // week number of the year, Monday first weekdaySundayOrigin = weekday(0) natReprTime = StdlibFormat("15:04:05") // national representation of the time XXX is this correct? natReprDate = StdlibFormat("01/02/06") // national representation of the date XXX is this correct? year = StdlibFormat("2006") // year with century yearNoCentury = StdlibFormat("06") // year w/o century timezone = StdlibFormat("MST") // time zone name timezoneOffset = StdlibFormat("-0700") // time zone ofset from UTC percent = Verbatim("%") ) // Appender is the interface that must be fulfilled by components that // implement the translation of specifications to actual time value. // // The Append method takes the accumulated byte buffer, and the time to // use to generate the textual representation. The resulting byte // sequence must be returned by this method, normally by using the // append() builtin function. type Appender interface { Append([]byte, time.Time) []byte } // AppendFunc is an utility type to allow users to create a // function-only version of an Appender type AppendFunc func([]byte, time.Time) []byte func (af AppendFunc) Append(b []byte, t time.Time) []byte { return af(b, t) } type appenderList []Appender type dumper interface { dump(io.Writer) } func (l appenderList) dump(out io.Writer) { var buf bytes.Buffer ll := len(l) for i, a := range l { if dumper, ok := a.(dumper); ok { dumper.dump(&buf) } else { fmt.Fprintf(&buf, "%#v", a) } if i < ll-1 { fmt.Fprintf(&buf, ",\n") } } if _, err := buf.WriteTo(out); err != nil { panic(err) } } // does the time.Format thing type stdlibFormat struct { s string } // StdlibFormat returns an Appender that simply goes through `time.Format()` // For example, if you know you want to display the abbreviated month name for %b, // you can create a StdlibFormat with the pattern `Jan` and register that // for specification `b`: // // a := StdlibFormat(`Jan`) // ss := NewSpecificationSet() // ss.Set('b', a) // does %b -> abbreviated month name func StdlibFormat(s string) Appender { return &stdlibFormat{s: s} } func (v stdlibFormat) Append(b []byte, t time.Time) []byte { return t.AppendFormat(b, v.s) } func (v stdlibFormat) str() string { return v.s } func (v stdlibFormat) canCombine() bool { return true } func (v stdlibFormat) combine(w combiner) Appender { return StdlibFormat(v.s + w.str()) } func (v stdlibFormat) dump(out io.Writer) { fmt.Fprintf(out, "stdlib: %s", v.s) } type verbatimw struct { s string } // Verbatim returns an Appender suitable for generating static text. // For static text, this method is slightly favorable than creating // your own appender, as adjacent verbatim blocks will be combined // at compile time to produce more efficient Appenders func Verbatim(s string) Appender { return &verbatimw{s: s} } func (v verbatimw) Append(b []byte, _ time.Time) []byte { return append(b, v.s...) } func (v verbatimw) canCombine() bool { return canCombine(v.s) } func (v verbatimw) combine(w combiner) Appender { if _, ok := w.(*stdlibFormat); ok { return StdlibFormat(v.s + w.str()) } return Verbatim(v.s + w.str()) } func (v verbatimw) str() string { return v.s } func (v verbatimw) dump(out io.Writer) { fmt.Fprintf(out, "verbatim: %s", v.s) } // unpadded wraps another Appender and strips the padding from the value it // produces. It implements the glibc '-' and Windows '#' flags, which suppress // the leading zeros or spaces on numeric fields (e.g. %-d -> "1" instead of // "01"). Non-numeric fields are emitted unchanged, matching libc behavior. type unpadded struct { inner Appender } func (v unpadded) Append(b []byte, t time.Time) []byte { var buf [64]byte s := v.inner.Append(buf[:0], t) // drop leading spaces (space-padded fields such as %e, %k, %l) i := 0 for i < len(s) && s[i] == ' ' { i++ } s = s[i:] // keep a leading sign, if any (e.g. the "+"/"-" of %z) if len(s) > 0 && (s[0] == '+' || s[0] == '-') { b = append(b, s[0]) s = s[1:] } // drop leading zeros, but always keep at least one digit j := 0 for j < len(s)-1 && s[j] == '0' { j++ } return append(b, s[j:]...) } func (v unpadded) dump(out io.Writer) { fmt.Fprintf(out, "unpadded[") if d, ok := v.inner.(dumper); ok { d.dump(out) } else { fmt.Fprintf(out, "%#v", v.inner) } fmt.Fprintf(out, "]") } // These words below, as well as any decimal character var combineExclusion = []string{ "Mon", "Monday", "Jan", "January", "MST", "PM", "pm", } func canCombine(s string) bool { if strings.ContainsAny(s, "0123456789") { return false } for _, word := range combineExclusion { if strings.Contains(s, word) { return false } } return true } type combiner interface { canCombine() bool combine(combiner) Appender str() string } // this is container for the compiler to keep track of appenders, // and combine them as we parse and compile the pattern type combiningAppend struct { list appenderList prev Appender prevCanCombine bool } func (ca *combiningAppend) Append(w Appender) { if ca.prevCanCombine { prev, prevOK := ca.prev.(combiner) if wc, ok := w.(combiner); ok && prevOK && wc.canCombine() { ca.prev = prev.combine(wc) ca.list[len(ca.list)-1] = ca.prev return } } ca.list = append(ca.list, w) ca.prev = w ca.prevCanCombine = false if comb, ok := w.(combiner); ok { if comb.canCombine() { ca.prevCanCombine = true } } } func appendCentury(b []byte, t time.Time) []byte { n := t.Year() / 100 if n < 10 { b = append(b, '0') } return append(b, strconv.Itoa(n)...) } type weekday int func (v weekday) Append(b []byte, t time.Time) []byte { n := int(t.Weekday()) if n < int(v) { n += 7 } return append(b, byte(n+48)) } type weeknumberOffset bool func (v weeknumberOffset) Append(b []byte, t time.Time) []byte { offset := int(t.Weekday()) if v { offset = 6 - offset } else if offset != 0 { offset = 7 - offset } n := (t.YearDay() + offset) / 7 if n < 10 { b = append(b, '0') } return append(b, strconv.Itoa(n)...) } func appendWeekYear(b []byte, t time.Time) []byte { year, _ := t.ISOWeek() // Handle negative years (BCE) if year < 0 { b = append(b, '-') year = -year } // Ensure 4-digit formatting if year < 1000 { if year < 10 { b = append(b, '0', '0', '0') } else if year < 100 { b = append(b, '0', '0') } else { b = append(b, '0') } } return append(b, strconv.Itoa(year)...) } func appendWeekYearNoCentury(b []byte, t time.Time) []byte { year, _ := t.ISOWeek() if year < 0 { b = append(b, '-') year = -year } yearNoCentury := year % 100 if yearNoCentury < 10 { b = append(b, '0') } return append(b, strconv.Itoa(yearNoCentury)...) } func appendWeekNumber(b []byte, t time.Time) []byte { _, n := t.ISOWeek() if n < 10 { b = append(b, '0') } return append(b, strconv.Itoa(n)...) } func appendDayOfYear(b []byte, t time.Time) []byte { n := t.YearDay() if n < 10 { b = append(b, '0', '0') } else if n < 100 { b = append(b, '0') } return append(b, strconv.Itoa(n)...) } type hourPadded struct { pad byte twelveHour bool } func (v hourPadded) Append(b []byte, t time.Time) []byte { h := t.Hour() if v.twelveHour && h > 12 { h = h - 12 } if v.twelveHour && h == 0 { h = 12 } if h < 10 { b = append(b, v.pad) b = append(b, byte(h+48)) } else { b = unrollTwoDigits(b, h) } return b } func unrollTwoDigits(b []byte, v int) []byte { b = append(b, byte((v/10)+48)) b = append(b, byte((v%10)+48)) return b } type hmsWAMPM struct{} func (v hmsWAMPM) Append(b []byte, t time.Time) []byte { h := t.Hour() var am bool if h == 0 { b = append(b, '1') b = append(b, '2') am = true } else { switch { case h == 12: // no op case h > 12: h = h - 12 default: am = true } b = unrollTwoDigits(b, h) } b = append(b, ':') b = unrollTwoDigits(b, t.Minute()) b = append(b, ':') b = unrollTwoDigits(b, t.Second()) b = append(b, ' ') if am { b = append(b, 'A') } else { b = append(b, 'P') } b = append(b, 'M') return b } strftime-1.2.0/bench/000077500000000000000000000000001520354036200144265ustar00rootroot00000000000000strftime-1.2.0/bench/bench_test.go000066400000000000000000000040421520354036200170730ustar00rootroot00000000000000package bench_test import ( "bytes" "log" "net/http" _ "net/http/pprof" "testing" "time" fastly "github.com/fastly/go-utils/strftime" jehiah "github.com/jehiah/go-strftime" lestrrat "github.com/lestrrat-go/strftime" ncruces "github.com/ncruces/go-strftime" tebeka "github.com/tebeka/strftime" ) func init() { go func() { log.Println(http.ListenAndServe("localhost:8080", nil)) }() } const benchfmt = `%A %a %B %b %d %H %I %M %m %p %S %Y %y %Z` func BenchmarkTebeka(b *testing.B) { var t time.Time for i := 0; i < b.N; i++ { tebeka.Format(benchfmt, t) } } func BenchmarkJehiah(b *testing.B) { // Grr, uses byte slices, and does it faster, but with more allocs var t time.Time for i := 0; i < b.N; i++ { jehiah.Format(benchfmt, t) } } func BenchmarkFastly(b *testing.B) { var t time.Time for i := 0; i < b.N; i++ { fastly.Strftime(benchfmt, t) } } func BenchmarkNcruces(b *testing.B) { var t time.Time for i := 0; i < b.N; i++ { ncruces.Format(benchfmt, t) } } func BenchmarkNcrucesAppend(b *testing.B) { var d []byte var t time.Time for i := 0; i < b.N; i++ { d = ncruces.AppendFormat(d[:0], benchfmt, t) } } func BenchmarkLestrrat(b *testing.B) { // This is expected to be rather slow, as it compiles the format string // every time it's called. var t time.Time for i := 0; i < b.N; i++ { lestrrat.Format(benchfmt, t) } } func BenchmarkLestrratCachedString(b *testing.B) { var t time.Time f, _ := lestrrat.New(benchfmt) // This benchmark does not take into effect the compilation time for i := 0; i < b.N; i++ { f.FormatString(t) } } func BenchmarkLestrratCachedWriter(b *testing.B) { var t time.Time f, _ := lestrrat.New(benchfmt) var buf bytes.Buffer b.ResetTimer() // This benchmark does not take into effect the compilation time for i := 0; i < b.N; i++ { buf.Reset() f.Format(&buf, t) } } func BenchmarkLestrratCachedFormatBuffer(b *testing.B) { var t time.Time f, _ := lestrrat.New(benchfmt) b.ResetTimer() var buf []byte for i := 0; i < b.N; i++ { buf = f.FormatBuffer(buf[:0], t) } } strftime-1.2.0/bench/go.mod000066400000000000000000000004661520354036200155420ustar00rootroot00000000000000module github.com/lestrrat-go/strftime/bench go 1.21 require ( github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 github.com/lestrrat-go/strftime v1.1.1 github.com/ncruces/go-strftime v1.0.0 github.com/tebeka/strftime v0.1.5 ) strftime-1.2.0/bench/go.sum000066400000000000000000000035541520354036200155700ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239 h1:Ghm4eQYC0nEPnSJdVkTrXpu9KtoVCSo1hg7mtI7G9KU= github.com/fastly/go-utils v0.0.0-20180712184237-d95a45783239/go.mod h1:Gdwt2ce0yfBxPvZrHkprdPPTTS3N5rwmLE8T22KBXlw= github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869 h1:IPJ3dvxmJ4uczJe5YQdrYB16oTJlGSC/OyZDqUk9xX4= github.com/jehiah/go-strftime v0.0.0-20171201141054-1d33003b3869/go.mod h1:cJ6Cj7dQo+O6GJNiMx+Pa94qKj+TG8ONdKHgMNIyyag= github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc h1:RKf14vYWi2ttpEmkA4aQ3j4u9dStX2t4M8UM6qqNsG8= github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is= github.com/lestrrat-go/strftime v1.1.1 h1:zgf8QCsgj27GlKBy3SU9/8MMgegZ8UCzlCyHYrUF0QU= github.com/lestrrat-go/strftime v1.1.1/go.mod h1:YDrzHJAODYQ+xxvrn5SG01uFIQAeDTzpxNVppCz7Nmw= github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/tebeka/strftime v0.1.5 h1:1NQKN1NiQgkqd/2moD6ySP/5CoZQsKa1d3ZhJ44Jpmg= github.com/tebeka/strftime v0.1.5/go.mod h1:29/OidkoWHdEKZqzyDLUyC+LmgDgdHo4WAFCDT7D/Ig= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= strftime-1.2.0/extension.go000066400000000000000000000032421520354036200157130ustar00rootroot00000000000000package strftime import ( "strconv" "time" ) // NOTE: declare private variable and iniitalize once in init(), // and leave the Milliseconds() function as returning static content. // This way, `go doc -all` does not show the contents of the // milliseconds function var milliseconds Appender var microseconds Appender var unixseconds Appender func init() { milliseconds = AppendFunc(func(b []byte, t time.Time) []byte { millisecond := t.Nanosecond() / int(time.Millisecond) if millisecond < 100 { b = append(b, '0') } if millisecond < 10 { b = append(b, '0') } return append(b, strconv.Itoa(millisecond)...) }) microseconds = AppendFunc(func(b []byte, t time.Time) []byte { microsecond := t.Nanosecond() / int(time.Microsecond) if microsecond < 100000 { b = append(b, '0') } if microsecond < 10000 { b = append(b, '0') } if microsecond < 1000 { b = append(b, '0') } if microsecond < 100 { b = append(b, '0') } if microsecond < 10 { b = append(b, '0') } return append(b, strconv.Itoa(microsecond)...) }) unixseconds = AppendFunc(func(b []byte, t time.Time) []byte { return append(b, strconv.FormatInt(t.Unix(), 10)...) }) } // Milliseconds returns the Appender suitable for creating a zero-padded, // 3-digit millisecond textual representation. func Milliseconds() Appender { return milliseconds } // Microseconds returns the Appender suitable for creating a zero-padded, // 6-digit microsecond textual representation. func Microseconds() Appender { return microseconds } // UnixSeconds returns the Appender suitable for creating // unix timestamp textual representation. func UnixSeconds() Appender { return unixseconds } strftime-1.2.0/go.mod000066400000000000000000000004701520354036200144560ustar00rootroot00000000000000module github.com/lestrrat-go/strftime go 1.21 require ( github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc github.com/stretchr/testify v1.11.1 ) require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) strftime-1.2.0/go.sum000066400000000000000000000021361520354036200145040ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc h1:RKf14vYWi2ttpEmkA4aQ3j4u9dStX2t4M8UM6qqNsG8= github.com/lestrrat-go/envload v0.0.0-20180220234015-a3eb8ddeffcc/go.mod h1:kopuH9ugFRkIXf3YoqHKyrJ9YfUFsckUU9S7B+XP+is= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= strftime-1.2.0/internal_test.go000066400000000000000000000010141520354036200165450ustar00rootroot00000000000000package strftime import ( "testing" "github.com/stretchr/testify/assert" ) func TestCombine(t *testing.T) { { s, err := New(`%A foo`) if !assert.NoError(t, err, `New should succeed`) { return } if !assert.Equal(t, 1, len(s.compiled), "there are 1 element") { return } } { s, _ := New(`%A 100`) if !assert.Equal(t, 2, len(s.compiled), "there are two elements") { return } } { s, _ := New(`%A Mon`) if !assert.Equal(t, 2, len(s.compiled), "there are two elements") { return } } } strftime-1.2.0/locale.go000066400000000000000000000154411520354036200151420ustar00rootroot00000000000000package strftime import ( "fmt" "io" "time" ) // MonthNames holds twelve month names, indexed by time.Month minus one // (January is index 0, December is index 11). It is used as the argument to // WithMonths and WithShortMonths. type MonthNames [12]string // WeekdayNames holds seven weekday names, indexed by time.Weekday (Sunday is // index 0, Saturday is index 6). It is used as the argument to WithWeekdays // and WithShortWeekdays. type WeekdayNames [7]string // Locale supplies the locale-dependent strings used by the name-producing // conversion specifiers (%A, %a, %B, %b, %h, %p). The library ships no locale // data of its own: build a Locale for your language with NewLocale, or // implement this interface yourself to back it with any source (a map, // computed values, an external CLDR dataset, ...). // // Months are addressed by time.Month and weekdays by time.Weekday, so an // implementation never has to worry about index conventions. // // Some languages (Russian, Czech, Polish, Greek, ...) inflect a month name // depending on whether it stands alone or sits next to a day number — e.g. // Russian "январь" (stand-alone) vs "2 января" (in a date). A Locale returns a // single form per month, so format each grammatical context with its own // Strftime object, each compiled with the Locale that holds the matching form. type Locale interface { Month(time.Month) string // full month name (%B) ShortMonth(time.Month) string // abbreviated month name (%b, %h) Weekday(time.Weekday) string // full weekday name (%A) ShortWeekday(time.Weekday) string // abbreviated weekday name (%a) Meridiem(hour int) string // AM/PM marker for the given 0-23 hour (%p) } // localeData is the array-backed Locale implementation produced by NewLocale // and DefaultLocale. Its fields are unexported and never mutated after // construction, so a Locale is safe to share across goroutines. type localeData struct { months [12]string shortMonths [12]string weekdays [7]string shortWeekdays [7]string meridiem [2]string } func (d *localeData) Month(m time.Month) string { return d.months[int(m)-1] } func (d *localeData) ShortMonth(m time.Month) string { return d.shortMonths[int(m)-1] } func (d *localeData) Weekday(w time.Weekday) string { return d.weekdays[int(w)] } func (d *localeData) ShortWeekday(w time.Weekday) string { return d.shortWeekdays[int(w)] } func (d *localeData) Meridiem(hour int) string { if hour < 12 { return d.meridiem[0] } return d.meridiem[1] } // englishLocaleData builds the English locale entirely from the standard // library's time package, so no name data is hard-coded here. func englishLocaleData() *localeData { d := &localeData{meridiem: [2]string{"AM", "PM"}} for m := time.January; m <= time.December; m++ { full := m.String() d.months[m-1] = full d.shortMonths[m-1] = full[:3] } for w := time.Sunday; w <= time.Saturday; w++ { full := w.String() d.weekdays[w] = full d.shortWeekdays[w] = full[:3] } return d } // DefaultLocale returns the English locale. It is the fallback for any name a // custom Locale leaves unset, and a convenient base for NewLocale. func DefaultLocale() Locale { return englishLocaleData() } // LocaleOption configures a Locale built by NewLocale. type LocaleOption interface { configureLocale(*localeData) } type localeOptionFunc func(*localeData) func (f localeOptionFunc) configureLocale(d *localeData) { f(d) } // NewLocale creates a Locale from the supplied options, starting from the // English locale. Any name an option leaves as the empty string keeps its // English default, so a partially-specified Locale never produces blank // output. func NewLocale(options ...LocaleOption) Locale { d := englishLocaleData() for _, o := range options { o.configureLocale(d) } return d } // WithMonths sets the full month names (%B), indexed by time.Month minus one. func WithMonths(names MonthNames) LocaleOption { return localeOptionFunc(func(d *localeData) { overlay12(&d.months, names) }) } // WithShortMonths sets the abbreviated month names (%b, %h). func WithShortMonths(names MonthNames) LocaleOption { return localeOptionFunc(func(d *localeData) { overlay12(&d.shortMonths, names) }) } // WithWeekdays sets the full weekday names (%A), indexed by time.Weekday. func WithWeekdays(names WeekdayNames) LocaleOption { return localeOptionFunc(func(d *localeData) { overlay7(&d.weekdays, names) }) } // WithShortWeekdays sets the abbreviated weekday names (%a). func WithShortWeekdays(names WeekdayNames) LocaleOption { return localeOptionFunc(func(d *localeData) { overlay7(&d.shortWeekdays, names) }) } // WithMeridiem sets the AM/PM markers (%p). An empty string keeps the English // default for that marker. func WithMeridiem(am, pm string) LocaleOption { return localeOptionFunc(func(d *localeData) { if am != "" { d.meridiem[0] = am } if pm != "" { d.meridiem[1] = pm } }) } func overlay12(dst *[12]string, src MonthNames) { for i, v := range src { if v != "" { dst[i] = v } } } func overlay7(dst *[7]string, src WeekdayNames) { for i, v := range src { if v != "" { dst[i] = v } } } // applyLocale registers the name-producing appenders that read from loc onto // the specification set. It is invoked before any explicit WithSpecification // overrides, so a caller can still replace an individual specifier. func applyLocale(ds SpecificationSet, loc Locale) error { pairs := []struct { b byte a Appender }{ {'A', weekdayNameAppender{loc: loc}}, {'a', weekdayNameAppender{loc: loc, short: true}}, {'B', monthNameAppender{loc: loc}}, {'b', monthNameAppender{loc: loc, short: true}}, {'h', monthNameAppender{loc: loc, short: true}}, {'p', meridiemAppender{loc: loc}}, } for _, p := range pairs { if err := ds.Set(p.b, p.a); err != nil { return fmt.Errorf("failed to apply locale for %%%c: %w", p.b, err) } } return nil } type monthNameAppender struct { loc Locale short bool } func (v monthNameAppender) Append(b []byte, t time.Time) []byte { if v.short { return append(b, v.loc.ShortMonth(t.Month())...) } return append(b, v.loc.Month(t.Month())...) } func (v monthNameAppender) dump(out io.Writer) { fmt.Fprintf(out, "monthName(short=%t)", v.short) } type weekdayNameAppender struct { loc Locale short bool } func (v weekdayNameAppender) Append(b []byte, t time.Time) []byte { if v.short { return append(b, v.loc.ShortWeekday(t.Weekday())...) } return append(b, v.loc.Weekday(t.Weekday())...) } func (v weekdayNameAppender) dump(out io.Writer) { fmt.Fprintf(out, "weekdayName(short=%t)", v.short) } type meridiemAppender struct { loc Locale } func (v meridiemAppender) Append(b []byte, t time.Time) []byte { return append(b, v.loc.Meridiem(t.Hour())...) } func (v meridiemAppender) dump(out io.Writer) { fmt.Fprintf(out, "meridiem") } strftime-1.2.0/locale_test.go000066400000000000000000000107321520354036200161770ustar00rootroot00000000000000package strftime_test import ( "testing" "time" "github.com/lestrrat-go/strftime" "github.com/stretchr/testify/require" ) // french is a representative non-inflecting locale. var french = strftime.NewLocale( strftime.WithMonths(strftime.MonthNames{ "janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre", }), strftime.WithShortMonths(strftime.MonthNames{ "janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc.", }), strftime.WithWeekdays(strftime.WeekdayNames{ "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", }), strftime.WithShortWeekdays(strftime.WeekdayNames{ "dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam.", }), ) // 2006-01-02 03:04:05 UTC is a Monday in January, before noon. var locref = time.Date(2006, time.January, 2, 3, 4, 5, 0, time.UTC) func TestLocaleFrench(t *testing.T) { for _, tc := range []struct { pattern string want string }{ {"%A", "lundi"}, {"%a", "lun."}, {"%B", "janvier"}, {"%b", "janv."}, {"%h", "janv."}, {"%A %d %B %Y", "lundi 02 janvier 2006"}, } { t.Run(tc.pattern, func(t *testing.T) { got, err := strftime.Format(tc.pattern, locref, strftime.WithLocale(french)) require.NoError(t, err) require.Equal(t, tc.want, got) }) } } // A Locale that sets only weekday names must still produce English month // names rather than blanks. func TestLocalePartialFallback(t *testing.T) { partial := strftime.NewLocale( strftime.WithWeekdays(strftime.WeekdayNames{ "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", }), ) got, err := strftime.Format("%A %B", locref, strftime.WithLocale(partial)) require.NoError(t, err) require.Equal(t, "lundi January", got) } // Numeric specifiers are locale-invariant. func TestLocaleNumericUnaffected(t *testing.T) { got, err := strftime.Format("%Y-%m-%d %H:%M:%S", locref, strftime.WithLocale(french)) require.NoError(t, err) require.Equal(t, "2006-01-02 03:04:05", got) } // DefaultLocale reproduces the stock English output. func TestLocaleDefaultMatchesEnglish(t *testing.T) { const pattern = "%A %a %B %b %p" english, err := strftime.Format(pattern, locref) require.NoError(t, err) withDefault, err := strftime.Format(pattern, locref, strftime.WithLocale(strftime.DefaultLocale())) require.NoError(t, err) require.Equal(t, english, withDefault) } func TestLocaleAMPM(t *testing.T) { loc := strftime.NewLocale(strftime.WithMeridiem("matin", "soir")) morning, err := strftime.Format("%p", locref, strftime.WithLocale(loc)) // 03:04 -> morning require.NoError(t, err) require.Equal(t, "matin", morning) afternoon := time.Date(2006, time.January, 2, 15, 0, 0, 0, time.UTC) evening, err := strftime.Format("%p", afternoon, strftime.WithLocale(loc)) require.NoError(t, err) require.Equal(t, "soir", evening) } // WithSpecification applied alongside WithLocale must win. func TestLocaleExplicitSpecificationOverrides(t *testing.T) { got, err := strftime.Format("%B", locref, strftime.WithLocale(french), strftime.WithSpecification('B', strftime.Verbatim("OVERRIDE")), ) require.NoError(t, err) require.Equal(t, "OVERRIDE", got) } // Inflecting languages: the correct in-date vs stand-alone form is selected // by compiling one Strftime per context, each with the matching Locale. func TestLocaleInflectionViaObjectSwap(t *testing.T) { weekdays := strftime.WithWeekdays(strftime.WeekdayNames{ "воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота", }) inDate := strftime.NewLocale(weekdays, strftime.WithMonths(strftime.MonthNames{ "января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря", })) standalone := strftime.NewLocale(weekdays, strftime.WithMonths(strftime.MonthNames{ "январь", "февраль", "март", "апрель", "май", "июнь", "июль", "август", "сентябрь", "октябрь", "ноябрь", "декабрь", })) dateFmt, err := strftime.New("%d %B %Y", strftime.WithLocale(inDate)) require.NoError(t, err) require.Equal(t, "02 января 2006", dateFmt.FormatString(locref)) headerFmt, err := strftime.New("%B %Y", strftime.WithLocale(standalone)) require.NoError(t, err) require.Equal(t, "январь 2006", headerFmt.FormatString(locref)) } strftime-1.2.0/options.go000066400000000000000000000047461520354036200154040ustar00rootroot00000000000000package strftime type Option interface { Name() string Value() any } type option struct { name string value any } func (o *option) Name() string { return o.name } func (o *option) Value() any { return o.value } const optSpecificationSet = `opt-specification-set` // WithSpecificationSet allows you to specify a custom specification set func WithSpecificationSet(ds SpecificationSet) Option { return &option{ name: optSpecificationSet, value: ds, } } const optLocale = `opt-locale` // WithLocale overrides the name-producing conversion specifiers (%A, %a, %B, // %b, %h, %p) with the localized names supplied by loc, which is typically // built with NewLocale. Numeric specifiers (%d, %m, %Y, ...) are // locale-invariant and are unaffected. // // Because a Locale supplies one form per name, format a context that needs // inflected month names (e.g. "%d %B" vs "%B %Y" in Slavic languages) by // compiling a separate Strftime object per context, each with the Locale // holding the appropriate form. See the Locale documentation for details. func WithLocale(loc Locale) Option { return &option{ name: optLocale, value: loc, } } type optSpecificationPair struct { name byte appender Appender } const optSpecification = `opt-specification` // WithSpecification allows you to create a new specification set on the fly, // to be used only for that invocation. func WithSpecification(b byte, a Appender) Option { return &option{ name: optSpecification, value: &optSpecificationPair{ name: b, appender: a, }, } } // WithMilliseconds is similar to WithSpecification, and specifies that // the Strftime object should interpret the pattern `%b` (where b // is the byte that you specify as the argument) // as the zero-padded, 3 letter milliseconds of the time. func WithMilliseconds(b byte) Option { return WithSpecification(b, Milliseconds()) } // WithMicroseconds is similar to WithSpecification, and specifies that // the Strftime object should interpret the pattern `%b` (where b // is the byte that you specify as the argument) // as the zero-padded, 3 letter microseconds of the time. func WithMicroseconds(b byte) Option { return WithSpecification(b, Microseconds()) } // WithUnixSeconds is similar to WithSpecification, and specifies that // the Strftime object should interpret the pattern `%b` (where b // is the byte that you specify as the argument) // as the unix timestamp in seconds func WithUnixSeconds(b byte) Option { return WithSpecification(b, UnixSeconds()) } strftime-1.2.0/specifications.go000066400000000000000000000073561520354036200167140ustar00rootroot00000000000000package strftime import ( "errors" "fmt" "sync" ) // because there is no such thing was a sync.RWLocker type rwLocker interface { RLock() RUnlock() sync.Locker } // SpecificationSet is a container for patterns that Strftime uses. // If you want a custom strftime, you can copy the default // SpecificationSet and tweak it type SpecificationSet interface { Lookup(byte) (Appender, error) Delete(byte) error Set(byte, Appender) error } type specificationSet struct { mutable bool lock rwLocker // store is indexed directly by the specification byte. Since keys are // always a single byte, a fixed array avoids the hashing cost of a map // on the hot compile path. A nil entry means "not set". store [256]Appender } // The default specification set does not need any locking as it is never // accessed from the outside, and is never mutated. var defaultSpecificationSet SpecificationSet func init() { defaultSpecificationSet = newImmutableSpecificationSet() } func newImmutableSpecificationSet() SpecificationSet { // Create a mutable one so that populateDefaultSpecifications work through // its magic, then copy the associated map // (NOTE: this is done this way because there used to be // two struct types for specification set, united under an interface. // it can now be removed, but we would need to change the entire // populateDefaultSpecifications method, and I'm currently too lazy // PRs welcome) tmp := newSpecificationSet() ss := &specificationSet{ mutable: false, lock: nil, // never used, so intentionally not initialized store: tmp.store, } return ss } // NewSpecificationSet creates a specification set with the default specifications. func NewSpecificationSet() SpecificationSet { return newSpecificationSet() } func newSpecificationSet() *specificationSet { ds := &specificationSet{ mutable: true, lock: &sync.RWMutex{}, } populateDefaultSpecifications(ds) return ds } var defaultSpecifications = map[byte]Appender{ 'A': fullWeekDayName, 'a': abbrvWeekDayName, 'B': fullMonthName, 'b': abbrvMonthName, 'C': centuryDecimal, 'c': timeAndDate, 'D': mdy, 'd': dayOfMonthZeroPad, 'e': dayOfMonthSpacePad, 'G': weekyear, 'g': weekyearNoCentury, 'F': ymd, 'H': twentyFourHourClockZeroPad, 'h': abbrvMonthName, 'I': twelveHourClockZeroPad, 'j': dayOfYear, 'k': twentyFourHourClockSpacePad, 'l': twelveHourClockSpacePad, 'M': minutesZeroPad, 'm': monthNumberZeroPad, 'n': newline, 'p': ampm, 'R': hm, 'r': imsp, 'S': secondsNumberZeroPad, 'T': hms, 't': tab, 'U': weekNumberSundayOrigin, 'u': weekdayMondayOrigin, 'V': weekNumberMondayOriginOneOrigin, 'v': eby, 'W': weekNumberMondayOrigin, 'w': weekdaySundayOrigin, 'X': natReprTime, 'x': natReprDate, 'Y': year, 'y': yearNoCentury, 'Z': timezone, 'z': timezoneOffset, '%': percent, } func populateDefaultSpecifications(ds SpecificationSet) { for c, handler := range defaultSpecifications { if err := ds.Set(c, handler); err != nil { panic(fmt.Sprintf("failed to set default specification for %c: %s", c, err)) } } } func (ds *specificationSet) Lookup(b byte) (Appender, error) { if ds.mutable { ds.lock.RLock() defer ds.lock.RUnlock() } v := ds.store[b] if v == nil { return nil, fmt.Errorf(`lookup failed: '%%%c' was not found in specification set`, b) } return v, nil } func (ds *specificationSet) Delete(b byte) error { if !ds.mutable { return errors.New(`delete failed: this specification set is marked immutable`) } ds.lock.Lock() defer ds.lock.Unlock() ds.store[b] = nil return nil } func (ds *specificationSet) Set(b byte, a Appender) error { if !ds.mutable { return errors.New(`set failed: this specification set is marked immutable`) } ds.lock.Lock() defer ds.lock.Unlock() ds.store[b] = a return nil } strftime-1.2.0/strftime.go000066400000000000000000000201271520354036200155350ustar00rootroot00000000000000package strftime import ( "errors" "fmt" "io" "strings" "sync" "sync/atomic" "time" ) type compileHandler interface { handleVerbatim(string) handleSpec(Appender) } // compile, and create an appender list type appenderListBuilder struct { list *combiningAppend } func (alb *appenderListBuilder) handleVerbatim(s string) { alb.list.Append(Verbatim(s)) } func (alb *appenderListBuilder) handleSpec(a Appender) { alb.list.Append(a) } // compile, and execute the appenders on the fly type appenderExecutor struct { t time.Time dst []byte } // handleVerbatim appends the static text directly, avoiding the heap // allocation that boxing it into a verbatimw Appender would incur on // this per-call compile path. func (ae *appenderExecutor) handleVerbatim(s string) { ae.dst = append(ae.dst, s...) } func (ae *appenderExecutor) handleSpec(a Appender) { ae.dst = a.Append(ae.dst, ae.t) } func compile(handler compileHandler, p string, ds SpecificationSet) error { for l := len(p); l > 0; l = len(p) { i := strings.IndexByte(p, '%') if i < 0 { handler.handleVerbatim(p) // this is silly, but I don't trust break keywords when there's a // possibility of this piece of code being rearranged p = p[l:] continue } if i == l-1 { return errors.New(`stray % at the end of pattern`) } // we found a '%'. we need the next byte to decide what to do next // we already know that i < l - 1 // everything up to the i is verbatim if i > 0 { handler.handleVerbatim(p[:i]) p = p[i:] } // An optional '-' (glibc) or '#' (Windows) flag between the '%' and // the conversion specifier suppresses padding on numeric fields. specIdx := 1 var noPad bool if c := p[1]; c == '-' || c == '#' { if len(p) < 3 { return errors.New(`stray % at the end of pattern`) } noPad = true specIdx = 2 } specification, err := ds.Lookup(p[specIdx]) if err != nil { return fmt.Errorf("pattern compilation failed: %w", err) } if noPad { specification = unpadded{inner: specification} } handler.handleSpec(specification) p = p[specIdx+1:] } return nil } func getSpecificationSetFor(options ...Option) (SpecificationSet, error) { ds := defaultSpecificationSet var extraSpecifications []*optSpecificationPair var locale Locale for _, option := range options { switch option.Name() { case optSpecificationSet: if v, ok := option.Value().(SpecificationSet); ok { ds = v } case optSpecification: if v, ok := option.Value().(*optSpecificationPair); ok { extraSpecifications = append(extraSpecifications, v) } case optLocale: if v, ok := option.Value().(Locale); ok { locale = v } } } if locale != nil || len(extraSpecifications) > 0 { // If ds is immutable, we're going to need to create a new // one. oh what a waste! if raw, ok := ds.(*specificationSet); ok && !raw.mutable { ds = NewSpecificationSet() } // Apply the locale first so an explicit WithSpecification can still // override an individual specifier. if locale != nil { if err := applyLocale(ds, locale); err != nil { return nil, err } } for _, v := range extraSpecifications { if err := ds.Set(v.name, v.appender); err != nil { return nil, err } } } return ds, nil } var fmtAppendExecutorPool = sync.Pool{ New: func() any { var h appenderExecutor h.dst = make([]byte, 0, 32) return &h }, } func getFmtAppendExecutor() *appenderExecutor { e, _ := fmtAppendExecutorPool.Get().(*appenderExecutor) return e } func releasdeFmtAppendExecutor(v *appenderExecutor) { // TODO: should we discard the buffer if it's too long? v.dst = v.dst[:0] fmtAppendExecutorPool.Put(v) } // formatCacheLimit caps the number of distinct patterns Format will keep // compiled. The bound keeps memory usage predictable even when patterns are // derived from untrusted input; once it is reached, additional patterns are // formatted on the fly without being cached. const formatCacheLimit = 1024 var ( formatCache sync.Map // pattern string -> *Strftime formatCacheLen atomic.Int64 ) // cachedStrftime returns a compiled Strftime for the default specification // set, reusing a previously compiled one when possible. The boolean result is // false (with no error) when the cache is full and the pattern was not already // cached, so the caller can fall back to compiling on the fly. func cachedStrftime(p string) (*Strftime, bool, error) { if v, ok := formatCache.Load(p); ok { f, _ := v.(*Strftime) return f, true, nil } if formatCacheLen.Load() >= formatCacheLimit { return nil, false, nil } f, err := New(p) if err != nil { return nil, false, err } if actual, loaded := formatCache.LoadOrStore(p, f); loaded { cached, _ := actual.(*Strftime) return cached, true, nil } formatCacheLen.Add(1) return f, true, nil } // Format takes the format `s` and the time `t` to produce the // format date/time. // // When called without options, compiled patterns are cached (up to an // internal limit) so that repeated calls with the same pattern avoid // recompilation. Calls that pass options always compile on the fly. // // If you know beforehand that you will be reusing the pattern // within your application, consider creating a `Strftime` object // and reusing it. func Format(p string, t time.Time, options ...Option) (string, error) { if len(options) == 0 { f, ok, err := cachedStrftime(p) if err != nil { return "", fmt.Errorf("failed to compile format: %w", err) } if ok { return f.FormatString(t), nil } // cache is full: fall through and format on the fly } ds, err := getSpecificationSetFor(options...) if err != nil { return "", fmt.Errorf("failed to get specification set: %w", err) } h := getFmtAppendExecutor() defer releasdeFmtAppendExecutor(h) h.t = t if err := compile(h, p, ds); err != nil { return "", fmt.Errorf("failed to compile format: %w", err) } return string(h.dst), nil } // Strftime is the object that represents a compiled strftime pattern type Strftime struct { pattern string compiled appenderList } // New creates a new Strftime object. If the compilation fails, then // an error is returned in the second argument. func New(p string, options ...Option) (*Strftime, error) { // TODO: this may be premature optimization ds, err := getSpecificationSetFor(options...) if err != nil { return nil, fmt.Errorf("failed to get specification set: %w", err) } var h appenderListBuilder h.list = &combiningAppend{} if err := compile(&h, p, ds); err != nil { return nil, fmt.Errorf("failed to compile format: %w", err) } return &Strftime{ pattern: p, compiled: h.list.list, }, nil } // Pattern returns the original pattern string func (f *Strftime) Pattern() string { return f.pattern } // Format takes the destination `dst` and time `t`. It formats the date/time // using the pre-compiled pattern, and outputs the results to `dst` func (f *Strftime) Format(dst io.Writer, t time.Time) error { const bufSize = 64 var b []byte bufLen := len(f.pattern) + 10 if bufLen < bufSize { var buf [bufSize]byte b = buf[:0] } else { b = make([]byte, 0, bufLen) } if _, err := dst.Write(f.format(b, t)); err != nil { return err } return nil } // FormatBuffer is equivalent to Format, but appends the result directly to // supplied slice dst, returning the updated slice. This avoids any internal // memory allocation. func (f *Strftime) FormatBuffer(dst []byte, t time.Time) []byte { return f.format(dst, t) } // Dump outputs the internal structure of the formatter, for debugging purposes. // Please do NOT assume the output format to be fixed: it is expected to change // in the future. func (f *Strftime) Dump(out io.Writer) { f.compiled.dump(out) } func (f *Strftime) format(b []byte, t time.Time) []byte { for _, w := range f.compiled { b = w.Append(b, t) } return b } // FormatString takes the time `t` and formats it, returning the // string containing the formated data. func (f *Strftime) FormatString(t time.Time) string { const bufSize = 64 var b []byte bufLen := len(f.pattern) + 10 if bufLen < bufSize { var buf [bufSize]byte b = buf[:0] } else { b = make([]byte, 0, bufLen) } return string(f.format(b, t)) } strftime-1.2.0/strftime_test.go000066400000000000000000000404001520354036200165700ustar00rootroot00000000000000package strftime_test import ( "bytes" "fmt" "os" "testing" "time" envload "github.com/lestrrat-go/envload" "github.com/lestrrat-go/strftime" "github.com/stretchr/testify/assert" ) var ref = time.Unix(1136239445, 123456789).UTC() func TestExclusion(t *testing.T) { s, err := strftime.New("%p PM") if !assert.NoError(t, err, `strftime.New should succeed`) { return } var tm time.Time if !assert.Equal(t, "AM PM", s.FormatString(tm)) { return } } func TestFormatCache(t *testing.T) { const pattern = `%Y-%m-%d %H:%M:%S` expected, err := strftime.New(pattern) if !assert.NoError(t, err, `strftime.New succeeds`) { return } // Repeated calls must return identical, correct results whether or not // the pattern was already cached. for i := 0; i < 3; i++ { s, err := strftime.Format(pattern, ref) if !assert.NoError(t, err, `strftime.Format succeeds`) { return } assert.Equal(t, expected.FormatString(ref), s, `cached Format matches compiled output`) } // Passing options bypasses the cache but must still work. withOpt, err := strftime.Format(`%L`, ref, strftime.WithMilliseconds('L')) if !assert.NoError(t, err, `strftime.Format with options succeeds`) { return } assert.Equal(t, "123", withOpt, `option-based Format produces milliseconds`) // Invalid patterns must return an error and must not be cached. for i := 0; i < 2; i++ { _, err := strftime.Format(`%`, ref) assert.Error(t, err, `invalid pattern returns error`) } } func TestInvalid(t *testing.T) { _, err := strftime.New("%") if !assert.Error(t, err, `strftime.New should return error`) { return } _, err = strftime.New(" %") if !assert.Error(t, err, `strftime.New should return error`) { return } _, err = strftime.New(" % ") if !assert.Error(t, err, `strftime.New should return error`) { return } } func TestFormatMethods(t *testing.T) { l := envload.New() defer l.Restore() t.Setenv("LC_ALL", "C") formatString := `%A %a %B %b %C %c %D %d %e %F %H %h %I %j %k %l %M %m %n %p %R %r %S %T %t %U %u %V %v %W %w %X %x %Y %y %Z %z` resultString := "Monday Mon January Jan 20 Mon Jan 2 22:04:05 2006 01/02/06 02 2 2006-01-02 22 Jan 10 002 22 10 04 01 \n PM 22:04 10:04:05 PM 05 22:04:05 \t 01 1 01 2-Jan-2006 01 1 22:04:05 01/02/06 2006 06 UTC +0000" s, err := strftime.Format(formatString, ref) if !assert.NoError(t, err, `strftime.Format succeeds`) { return } if !assert.Equal(t, resultString, s, `formatted result matches`) { return } formatter, err := strftime.New(formatString) if !assert.NoError(t, err, `strftime.New succeeds`) { return } if !assert.Equal(t, resultString, formatter.FormatString(ref), `formatted result matches`) { return } var buf bytes.Buffer err = formatter.Format(&buf, ref) if !assert.NoError(t, err, `Format method succeeds`) { return } if !assert.Equal(t, resultString, buf.String(), `formatted result matches`) { return } var dst []byte dst = formatter.FormatBuffer(dst, ref) if !assert.Equal(t, resultString, string(dst), `formatted result matches`) { return } dst = []byte("nonsense") dst = formatter.FormatBuffer(dst[:0], ref) if !assert.Equal(t, resultString, string(dst), `overwritten result matches`) { return } dst = []byte("nonsense") dst = formatter.FormatBuffer(dst, ref) if !assert.Equal(t, "nonsense"+resultString, string(dst), `appended result matches`) { return } } func TestFormatBlanks(t *testing.T) { l := envload.New() defer l.Restore() t.Setenv("LC_ALL", "C") { dt := time.Date(1, 1, 1, 18, 0, 0, 0, time.UTC) s, err := strftime.Format("%l", dt) if !assert.NoError(t, err, `strftime.Format succeeds`) { return } if !assert.Equal(t, " 6", s, "leading blank is properly set") { return } } { dt := time.Date(1, 1, 1, 6, 0, 0, 0, time.UTC) s, err := strftime.Format("%k", dt) if !assert.NoError(t, err, `strftime.Format succeeds`) { return } if !assert.Equal(t, " 6", s, "leading blank is properly set") { return } } } func TestFormatZeropad(t *testing.T) { l := envload.New() defer l.Restore() t.Setenv("LC_ALL", "C") { dt := time.Date(1, 1, 1, 1, 0, 0, 0, time.UTC) s, err := strftime.Format("%j", dt) if !assert.NoError(t, err, `strftime.Format succeeds`) { return } if !assert.Equal(t, "001", s, "padding is properly set") { return } } { dt := time.Date(1, 1, 10, 6, 0, 0, 0, time.UTC) s, err := strftime.Format("%j", dt) if !assert.NoError(t, err, `strftime.Format succeeds`) { return } if !assert.Equal(t, "010", s, "padding is properly set") { return } } { dt := time.Date(1, 6, 1, 6, 0, 0, 0, time.UTC) s, err := strftime.Format("%j", dt) if !assert.NoError(t, err, `strftime.Format succeeds`) { return } if !assert.Equal(t, "152", s, "padding is properly set") { return } } { dt := time.Date(100, 1, 1, 1, 0, 0, 0, time.UTC) s, err := strftime.Format("%C", dt) if !assert.NoError(t, err, `strftime.Format succeeds`) { return } if !assert.Equal(t, "01", s, "padding is properly set") { return } } } func TestGHIssue5(t *testing.T) { const expected = `apm-test/logs/apm.log.01000101` p, _ := strftime.New("apm-test/logs/apm.log.%Y%m%d") dt := time.Date(100, 1, 1, 1, 0, 0, 0, time.UTC) if !assert.Equal(t, expected, p.FormatString(dt), `patterns including 'pm' should be treated as verbatim formatter`) { return } } func TestGHPR7(t *testing.T) { const expected = `123` p, _ := strftime.New(`%L`, strftime.WithMilliseconds('L')) if !assert.Equal(t, expected, p.FormatString(ref), `patterns should match for custom specification`) { return } } func TestWithMicroseconds(t *testing.T) { const expected = `123456` p, _ := strftime.New(`%f`, strftime.WithMicroseconds('f')) if !assert.Equal(t, expected, p.FormatString(ref), `patterns should match for custom specification`) { return } } func TestWithUnixSeconds(t *testing.T) { const expected = `1136239445` p, _ := strftime.New(`%s`, strftime.WithUnixSeconds('s')) if !assert.Equal(t, expected, p.FormatString(ref), `patterns should match for custom specification`) { return } } func ExampleSpecificationSet() { { // I want %L as milliseconds! p, err := strftime.New(`%L`, strftime.WithMilliseconds('L')) if err != nil { fmt.Println(err) return } p.Format(os.Stdout, ref) os.Stdout.Write([]byte{'\n'}) } { // I want %f as milliseconds! p, err := strftime.New(`%f`, strftime.WithMilliseconds('f')) if err != nil { fmt.Println(err) return } p.Format(os.Stdout, ref) os.Stdout.Write([]byte{'\n'}) } { // I want %X to print out my name! a := strftime.Verbatim(`Daisuke Maki`) p, err := strftime.New(`%X`, strftime.WithSpecification('X', a)) if err != nil { fmt.Println(err) return } p.Format(os.Stdout, ref) os.Stdout.Write([]byte{'\n'}) } { // I want a completely new specification set, and I want %X to print out my name! a := strftime.Verbatim(`Daisuke Maki`) ds := strftime.NewSpecificationSet() ds.Set('X', a) p, err := strftime.New(`%X`, strftime.WithSpecificationSet(ds)) if err != nil { fmt.Println(err) return } p.Format(os.Stdout, ref) os.Stdout.Write([]byte{'\n'}) } { // I want %s as unix timestamp! p, err := strftime.New(`%s`, strftime.WithUnixSeconds('s')) if err != nil { fmt.Println(err) return } p.Format(os.Stdout, ref) os.Stdout.Write([]byte{'\n'}) } // OUTPUT: // 123 // 123 // Daisuke Maki // Daisuke Maki // 1136239445 } func TestGHIssue9(t *testing.T) { pattern, _ := strftime.New("/full1/test2/to3/proveIssue9isfixed/11%C22/12345%Y%m%d.%H.log.%C.log") testTime := time.Date(2020, 1, 1, 1, 1, 1, 1, time.UTC) correctString := "/full1/test2/to3/proveIssue9isfixed/112022/1234520200101.01.log.20.log" var buf bytes.Buffer pattern.Format(&buf, testTime) // Using a fixed time should give us a fixed output. if !assert.True(t, buf.String() == correctString) { t.Logf("Buffer [%s] should be [%s]", buf.String(), correctString) return } } func TestGHIssue18(t *testing.T) { testIH := func(twelveHour bool) func(t *testing.T) { var patternString string if twelveHour { patternString = "%I" } else { patternString = "%H" } return func(t *testing.T) { t.Helper() var buf bytes.Buffer pattern, _ := strftime.New(patternString) for i := 0; i < 24; i++ { testTime := time.Date(2020, 1, 1, i, 1, 1, 1, time.UTC) var correctString string switch { case twelveHour && i == 0: correctString = fmt.Sprintf("%02d", 12) case twelveHour && i > 12: correctString = fmt.Sprintf("%02d", i-12) default: correctString = fmt.Sprintf("%02d", i) } buf.Reset() pattern.Format(&buf, testTime) if !assert.Equal(t, correctString, buf.String(), "Buffer [%s] should be [%s] for time %s", buf.String(), correctString, testTime) { return } } } } testR := func(t *testing.T) { t.Helper() patternString := "%r" var buf bytes.Buffer pattern, _ := strftime.New(patternString) for i := 0; i < 24; i++ { testTime := time.Date(2020, 1, 1, i, 1, 1, 1, time.UTC) var correctString string switch { case i == 0: correctString = fmt.Sprintf("%02d:%02d:%02d AM", 12, testTime.Minute(), testTime.Second()) case i == 12: correctString = fmt.Sprintf("%02d:%02d:%02d PM", 12, testTime.Minute(), testTime.Second()) case i > 12: correctString = fmt.Sprintf("%02d:%02d:%02d PM", i-12, testTime.Minute(), testTime.Second()) default: correctString = fmt.Sprintf("%02d:%02d:%02d AM", i, testTime.Minute(), testTime.Second()) } buf.Reset() t.Logf("%s", correctString) pattern.Format(&buf, testTime) if !assert.Equal(t, correctString, buf.String(), "Buffer [%s] should be [%s] for time %s", buf.String(), correctString, testTime) { continue } } } t.Run("12 hour zero pad %I", testIH(true)) t.Run("24 hour zero pad %H", testIH(false)) t.Run("12 hour zero pad %r", testR) } func TestFormat12AM(t *testing.T) { s, err := strftime.Format(`%H %I %l`, time.Time{}) if !assert.NoError(t, err, `strftime.Format succeeds`) { return } if !assert.Equal(t, "00 12 12", s, "correctly format the hour") { return } } func TestFormat_WeekNumber(t *testing.T) { for y := 2000; y < 2020; y++ { sunday := "00" monday := "00" for d := 1; d < 8; d++ { base := time.Date(y, time.January, d, 0, 0, 0, 0, time.UTC) switch base.Weekday() { case time.Sunday: sunday = "01" case time.Monday: monday = "01" } if got, _ := strftime.Format("%U", base); got != sunday { t.Errorf("Format(%q, %d) = %q, want %q", "%U", base.Unix(), got, sunday) } if got, _ := strftime.Format("%W", base); got != monday { t.Errorf("Format(%q, %d) = %q, want %q", "%W", base.Unix(), got, monday) } } } } func TestFormat_WeekYear(t *testing.T) { // Note: According to ISO 8601, Week 1 is the week that contains the first Thursday of the year. testCases := []struct { name string date time.Time expectG string // %G - ISO week year (4 digits) expectg string // %g - ISO week year without century (2 digits) }{ { name: "New Year's Day 2005 (week belongs to 2004)", date: time.Date(2005, 1, 1, 0, 0, 0, 0, time.UTC), // Saturday expectG: "2004", expectg: "04", }, { name: "New Year's Day 2006 (week belongs to 2005)", date: time.Date(2006, 1, 1, 0, 0, 0, 0, time.UTC), // Sunday expectG: "2005", expectg: "05", }, { name: "Dec 31, 2007 (week belongs to 2008)", date: time.Date(2007, 12, 31, 0, 0, 0, 0, time.UTC), // Monday expectG: "2008", expectg: "08", }, { name: "Dec 30, 2008 (week belongs to 2009)", date: time.Date(2008, 12, 30, 0, 0, 0, 0, time.UTC), // Tuesday expectG: "2009", expectg: "09", }, { name: "Jan 3, 2010 (first week of 2010)", date: time.Date(2010, 1, 3, 0, 0, 0, 0, time.UTC), // Sunday expectG: "2009", expectg: "09", }, { name: "Jan 4, 2010 (first Monday, week 1 of 2010)", date: time.Date(2010, 1, 4, 0, 0, 0, 0, time.UTC), // Monday expectG: "2010", expectg: "10", }, { name: "Regular date mid-year", date: time.Date(2023, 7, 15, 0, 0, 0, 0, time.UTC), expectG: "2023", expectg: "23", }, { name: "Year 2000 (Y2K boundary)", date: time.Date(2000, 6, 15, 0, 0, 0, 0, time.UTC), expectG: "2000", expectg: "00", }, { name: "Year 1999 to 2000 transition", date: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), // Saturday expectG: "1999", expectg: "99", }, { name: "Single digit year case", date: time.Date(2009, 6, 15, 0, 0, 0, 0, time.UTC), expectG: "2009", expectg: "09", }, { name: "Edge case: Dec 29, 2014 (week 1 of 2015)", date: time.Date(2014, 12, 29, 0, 0, 0, 0, time.UTC), // Monday expectG: "2015", expectg: "15", }, { name: "Edge case: Jan 4, 2021 (first Monday of year)", date: time.Date(2021, 1, 4, 0, 0, 0, 0, time.UTC), // Monday expectG: "2021", expectg: "21", }, { name: "Edge case: Jan 3, 2021 (belongs to 2020)", date: time.Date(2021, 1, 3, 0, 0, 0, 0, time.UTC), // Sunday expectG: "2020", expectg: "20", }, // Test cases for BCE years { name: "Year 1 BCE mid-year", date: time.Date(-1, 6, 15, 0, 0, 0, 0, time.UTC), expectG: "-0001", expectg: "-01", }, { name: "Year 10 BCE", date: time.Date(-1, 3, 20, 0, 0, 0, 0, time.UTC), expectG: "-0001", expectg: "-01", }, { name: "Year 99 BCE", date: time.Date(-99, 8, 10, 0, 0, 0, 0, time.UTC), expectG: "-0099", expectg: "-99", }, { name: "Year 100 BCE (century boundary)", date: time.Date(-100, 12, 25, 0, 0, 0, 0, time.UTC), expectG: "-0100", expectg: "-00", }, { name: "Year 1234 BCE (4-digit BCE year)", date: time.Date(-1234, 9, 15, 0, 0, 0, 0, time.UTC), expectG: "-1234", expectg: "-34", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { // Test %G (4-digit ISO week year) gotG, err := strftime.Format("%G", tc.date) if !assert.NoError(t, err, "strftime.Format %%G should succeed") { return } if !assert.Equal(t, tc.expectG, gotG, "%%G format for %v", tc.date) { return } // Test %g (2-digit ISO week year) gotg, err := strftime.Format("%g", tc.date) if !assert.NoError(t, err, "strftime.Format %%g should succeed") { return } if !assert.Equal(t, tc.expectg, gotg, "%%g format for %v", tc.date) { return } // Verify consistency: last 2 digits of %G should equal %g expectedLastG := tc.expectG[len(tc.expectG)-2:] expectedLastg := tc.expectg[len(tc.expectg)-2:] if !assert.Equal(t, expectedLastG, expectedLastg, "%%g should be last 2 digits of %%G for %v", tc.date) { return } }) } } func TestFormat_WeekYearBoundaries(t *testing.T) { // Test the tricky boundary cases where calendar year != ISO week year boundaryTests := []struct { calendarYear int month time.Month day int expectedWeekYear int }{ // Cases where early January belongs to previous week year {2005, time.January, 1, 2004}, // Sat Jan 1, 2005 is in week 53 of 2004 {2005, time.January, 2, 2004}, // Sun Jan 2, 2005 is in week 53 of 2004 {2006, time.January, 1, 2005}, // Sun Jan 1, 2006 is in week 52 of 2005 // Cases where late December belongs to next week year {2007, time.December, 31, 2008}, // Mon Dec 31, 2007 is in week 1 of 2008 {2008, time.December, 29, 2009}, // Mon Dec 29, 2008 is in week 1 of 2009 {2008, time.December, 30, 2009}, // Tue Dec 30, 2008 is in week 1 of 2009 {2008, time.December, 31, 2009}, // Wed Dec 31, 2008 is in week 1 of 2009 } for _, bt := range boundaryTests { testDate := time.Date(bt.calendarYear, bt.month, bt.day, 0, 0, 0, 0, time.UTC) gotG, err := strftime.Format("%G", testDate) if !assert.NoError(t, err, "strftime.Format %%G should succeed") { continue } expectedG := fmt.Sprintf("%04d", bt.expectedWeekYear) if !assert.Equal(t, expectedG, gotG, "Calendar %d-%02d-%02d should be week year %d", bt.calendarYear, bt.month, bt.day, bt.expectedWeekYear) { continue } // Test %g as well gotg, err := strftime.Format("%g", testDate) if !assert.NoError(t, err, "strftime.Format %%g should succeed") { continue } expectedg := fmt.Sprintf("%02d", bt.expectedWeekYear%100) assert.Equal(t, expectedg, gotg, "Week year without century should match for %v", testDate) } } strftime-1.2.0/unpadded_test.go000066400000000000000000000040771520354036200165310ustar00rootroot00000000000000package strftime_test import ( "testing" "time" "github.com/lestrrat-go/strftime" "github.com/stretchr/testify/require" ) // unpadref is chosen so that every numeric field has a single significant // digit, making the effect of the '-'/'#' (no-pad) flag observable. // 2006-01-02 03:04:05 UTC: Jan(01) 2nd(02) 03:04:05, year-of-century 06, // day-of-year 002, UTC offset +0000. var unpadref = time.Date(2006, time.January, 2, 3, 4, 5, 0, time.UTC) func TestUnpaddedFlag(t *testing.T) { for _, tc := range []struct { spec byte padded string unpadded string }{ {'d', "02", "2"}, {'e', " 2", "2"}, {'H', "03", "3"}, {'I', "03", "3"}, {'j', "002", "2"}, {'k', " 3", "3"}, {'l', " 3", "3"}, {'M', "04", "4"}, {'m', "01", "1"}, {'S', "05", "5"}, {'y', "06", "6"}, {'z', "+0000", "+0"}, } { t.Run(string(tc.spec), func(t *testing.T) { padded, err := strftime.Format("%"+string(tc.spec), unpadref) require.NoError(t, err, "padded form should compile") require.Equal(t, tc.padded, padded, "padded baseline") for _, flag := range []string{"-", "#"} { got, err := strftime.Format("%"+flag+string(tc.spec), unpadref) require.NoErrorf(t, err, "%%%s%c should compile", flag, tc.spec) require.Equalf(t, tc.unpadded, got, "%%%s%c", flag, tc.spec) } }) } } func TestUnpaddedNonNumericUnchanged(t *testing.T) { // Non-numeric fields are emitted unchanged when the flag is present. for _, spec := range []string{"A", "B", "Z", "p"} { plain, err := strftime.Format("%"+spec, unpadref) require.NoError(t, err) flagged, err := strftime.Format("%-"+spec, unpadref) require.NoError(t, err) require.Equalf(t, plain, flagged, "%%-%s should match %%%s", spec, spec) } } func TestUnpaddedInContext(t *testing.T) { got, err := strftime.Format("%Y-%-m-%-d %-H:%-M:%-S", unpadref) require.NoError(t, err) require.Equal(t, "2006-1-2 3:4:5", got) } func TestUnpaddedStrayFlag(t *testing.T) { for _, p := range []string{"%-", "%#", "foo %-"} { _, err := strftime.Format(p, unpadref) require.Errorf(t, err, "pattern %q should error", p) } }