coreutils

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 24, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package coreutils provides deterministic values and helpers shared by Diene Go libraries.

Index

Examples

Constants

View Source
const IANATimeZoneRelease = "2026b"

IANATimeZoneRelease identifies the bundled IANA timezone release used by the C0 contract. Go's embedded tzdata is used rather than host zoneinfo.

Variables

View Source
var C0Temporal = C0TemporalContract{
	Provenance:      C0TemporalProvenance{ContractVersion: "1", C0Section: "C0 §1 Serialization", C0Source: "goals/c0-contracts.md", IANARelease: IANATimeZoneRelease, IANAArchiveURL: "https://data.iana.org/time-zones/releases/tzdata2026b.tar.gz", IANAArchiveSHA256: "114543d9f19a6bfeb5bca43686aea173d38755a3db1f2eec112647ae92c6f544"},
	Dates:           C0Cases{Valid: []string{"2026-07-21", "2000-02-29", "0001-01-01", "9999-12-31"}, Invalid: []string{"21-07-2026", "2026-02-30", "2026-13-01", "2026-7-1", "2026/07/21"}},
	Times:           C0Cases{Valid: []string{"00:00:00", "01:02:03", "23:59:59"}, Invalid: []string{"24:00:00", "01:60:00", "01:02:60", "1:02:03", "01:02"}},
	Durations:       C0Cases{Valid: []string{"P1DT2H3M4.5S", "PT0.5S", "P1Y2M3DT4H5M6S", "P1W"}, Invalid: []string{"10 minutes", "P", "PT", "1DT2H", "P1H"}},
	Timezones:       C0Cases{Valid: []string{"Asia/Singapore", "America/Argentina/Buenos_Aires", "Etc/UTC", "UTC", "US/Eastern", "EST", "GMT"}, Invalid: []string{"Area/NotAnIanaZone", "+08:00", "asia/singapore", "Area/../Location", "PST", ""}},
	Instants:        []C0InstantVector{{Input: "2026-07-21T09:02:03+08:00", CanonicalUTC: "2026-07-21T01:02:03.000Z"}, {Input: "2026-07-21T01:02:03Z", CanonicalUTC: "2026-07-21T01:02:03.000Z"}, {Input: "2026-07-21T01:02:03.456Z", CanonicalUTC: "2026-07-21T01:02:03.456Z"}},
	InvalidInstants: []string{"2026-07-21T01:02:03+00:00", "2026-07-21T01:02:03+08:00", "2026-07-21T01:02:03", "2026-02-30T01:02:03Z", "2026-07-21 01:02:03Z"},
}

C0Temporal is the single, version-pinned temporal contract for Go consumers.

Functions

func CanonicalConfigKey

func CanonicalConfigKey(key string) string

CanonicalConfigKey removes separators and lowercases a configuration key.

func CoerceEnvironmentScalar

func CoerceEnvironmentScalar(value string) any

CoerceEnvironmentScalar converts a configuration scalar into nil, bool, an IEEE-754-safe integer, float64, or its original string. It is not a money or wire-decimal codec.

func ConfigKeysMatch

func ConfigKeysMatch(left string, right string) bool

ConfigKeysMatch reports whether two configuration keys identify one logical key.

func DeepClone

func DeepClone(value any) any

DeepClone returns an independent clone of a JSON-like value.

func DeepMerge

func DeepMerge(base map[string]any, overlay map[string]any) map[string]any

DeepMerge immutably overlays overlay onto base. Nested maps merge while scalars and lists replace; map keys match across snake, kebab, camel, and Pascal spellings.

func DeepMergeAll

func DeepMergeAll(layers ...map[string]any) map[string]any

DeepMergeAll merges layers in declaration order.

func EnvironmentToNestedMap

func EnvironmentToNestedMap(environment map[string]string, prefix string) (map[string]any, error)

EnvironmentToNestedMap converts prefixed environment values into a nested JSON-like map. Double underscores separate components and numeric components materialize contiguous zero-based lists.

Example
package main

import (
	"fmt"

	"github.com/AtomiCloud/diene.go-core-utils/lib/coreutils"
)

func main() {
	config, _ := coreutils.EnvironmentToNestedMap(map[string]string{"ATOMI_AUTH__SCOPES__0": "openid"}, "ATOMI_")
	fmt.Println(config["auth"])
}
Output:
map[scopes:[openid]]

func FormatRFC3339UTC

func FormatRFC3339UTC(value time.Time) (string, error)

FormatRFC3339UTC formats value as a canonical millisecond RFC 3339 UTC instant.

func HashFile

func HashFile(ctx context.Context, filesystem interfaces.Vfs, path string) (string, error)

HashFile reads path through the virtual filesystem seam and returns the lowercase hex SHA-256 of its bytes. Any read error is returned unwrapped so the caller keeps the seam's problem typing.

Example
package main

import (
	"context"
	"fmt"

	"github.com/AtomiCloud/diene.go-core-utils/lib/coreutils"
	"github.com/AtomiCloud/diene.go-interfaces/lib/interfaces"
	"github.com/AtomiCloud/diene.go-interfaces/testhelper"
)

func main() {
	filesystem := testhelper.NewInMemoryVfs(testhelper.InMemoryVfsOptions{})
	_ = filesystem.WriteText(context.Background(), "/greeting.txt", "hello", interfaces.WriteOptions{CreateParents: true})
	digest, _ := coreutils.HashFile(context.Background(), filesystem, "/greeting.txt")
	fmt.Println(digest)
}
Output:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

func IsIanaTimezone

func IsIanaTimezone(value string) bool

IsIanaTimezone reports whether value is a valid, case-sensitive IANA zone. It accepts canonical identifiers and IANA aliases while rejecting host-local names, offsets, path traversal, and unknown abbreviations.

func MapConcurrent

func MapConcurrent[Input any, Output any](
	ctx context.Context,
	items []Input,
	concurrency int,
	transform func(context.Context, Input) (Output, error),
) ([]Output, error)

MapConcurrent applies transform to every item using at most concurrency workers while preserving input order in the result. It returns the first error reported by any invocation and cancels the derived context handed to pending work; a concurrency below one is raised to one. When the parent context is cancelled before the work completes the cancellation error is returned and no partial result is exposed.

Example
package main

import (
	"context"
	"fmt"

	"github.com/AtomiCloud/diene.go-core-utils/lib/coreutils"
)

func main() {
	doubled, _ := coreutils.MapConcurrent(context.Background(), []int{1, 2, 3}, 2,
		func(_ context.Context, value int) (int, error) { return value * 2, nil })
	fmt.Println(doubled)
}
Output:
[2 4 6]

func NamespacedKey

func NamespacedKey(namespace string, key string) (string, error)

NamespacedKey builds a normalized namespace:key value. Invalid components return a problem-typed validation error.

Example
package main

import (
	"fmt"

	"github.com/AtomiCloud/diene.go-core-utils/lib/coreutils"
)

func main() {
	key, _ := coreutils.NamespacedKey("Mobile App", "Current User")
	fmt.Println(key)
}
Output:
mobile-app:current-user

func NowWireInstant

func NowWireInstant(system interfaces.System) (string, error)

NowWireInstant reads the current instant from the system clock seam and formats it as a canonical millisecond RFC 3339 UTC string. Routing every "now" through the C0 wire codec removes the ad hoc time formatting that produced the zinc_date defect class. The seam error is returned unwrapped so the caller keeps its problem typing.

Example
package main

import (
	"fmt"
	"time"

	"github.com/AtomiCloud/diene.go-core-utils/lib/coreutils"
	"github.com/AtomiCloud/diene.go-interfaces/testhelper"
)

func main() {
	system := testhelper.NewInMemorySystem(testhelper.InMemorySystemOptions{})
	system.SetNow(time.Date(2026, 7, 21, 1, 2, 3, 456000000, time.UTC))
	instant, _ := coreutils.NowWireInstant(system)
	fmt.Println(instant)
}
Output:
2026-07-21T01:02:03.456Z

func ParseRFC3339UTC

func ParseRFC3339UTC(value string) (time.Time, error)

ParseRFC3339UTC parses a strict RFC 3339 instant ending in Z.

func Sleep

func Sleep(ctx context.Context, duration time.Duration) error

Sleep waits for duration or returns when ctx is cancelled. Negative durations are rejected before a timer is scheduled.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/AtomiCloud/diene.go-core-utils/lib/coreutils"
)

func main() {
	_ = coreutils.Sleep(context.Background(), time.Duration(0))
	fmt.Println("complete")
}
Output:
complete

func Slugify

func Slugify(input string) string

Slugify normalizes input with NFKD and returns a lowercase ASCII kebab slug.

func StableHash

func StableHash(value any) (string, error)

StableHash returns the lowercase hex SHA-256 of the canonical JSON encoding of a JSON-like value. Object keys are emitted in sorted order, so values that differ only by map iteration order hash identically. Values that cannot be encoded as JSON (for example channels or functions) return an error.

Example
package main

import (
	"fmt"

	"github.com/AtomiCloud/diene.go-core-utils/lib/coreutils"
)

func main() {
	first, _ := coreutils.StableHash(map[string]any{"a": 1, "b": 2})
	second, _ := coreutils.StableHash(map[string]any{"b": 2, "a": 1})
	fmt.Println(first == second)
}
Output:
true

Types

type C0Cases

type C0Cases struct {
	// Valid contains values that must round-trip.
	Valid []string
	// Invalid contains values that must be rejected.
	Invalid []string
}

C0Cases contains positive and negative wire cases.

type C0InstantVector

type C0InstantVector struct {
	// Input is an RFC 3339 value, potentially with an offset.
	Input string
	// CanonicalUTC is its RFC 3339 UTC Z representation.
	CanonicalUTC string
}

C0InstantVector fixes an input instant and canonical UTC output.

type C0TemporalContract

type C0TemporalContract struct {
	// Provenance pins the contract inputs.
	Provenance C0TemporalProvenance
	// Dates contains calendar-date cases.
	Dates C0Cases
	// Times contains wall-clock cases.
	Times C0Cases
	// Durations contains ISO duration cases.
	Durations C0Cases
	// Timezones contains IANA timezone cases.
	Timezones C0Cases
	// Instants contains normalization vectors.
	Instants []C0InstantVector
	// InvalidInstants contains strict-parser rejection cases.
	InvalidInstants []string
}

C0TemporalContract is the shared, deterministic C0 temporal contract.

func (C0TemporalContract) DigestPayload

func (contract C0TemporalContract) DigestPayload() string

DigestPayload deterministically serializes the temporal vectors for stale-fixture detection.

type C0TemporalProvenance

type C0TemporalProvenance struct {
	// ContractVersion is the monotonic C0 vector version.
	ContractVersion string
	// C0Section identifies the binding C0 contract section.
	C0Section string
	// C0Source identifies the repository contract source.
	C0Source string
	// IANARelease identifies the required IANA timezone release.
	IANARelease string
	// IANAArchiveURL is the official source archive URL.
	IANAArchiveURL string
	// IANAArchiveSHA256 is the official archive digest.
	IANAArchiveSHA256 string
}

C0TemporalProvenance records the source and reproducibility pins for C0 vectors.

type EnvironmentCoercionError

type EnvironmentCoercionError struct {
	// Key is the source environment key or its materialized path.
	Key string
	// Reason describes why the path is invalid.
	Reason string
}

EnvironmentCoercionError reports an invalid or ambiguous environment path.

func (*EnvironmentCoercionError) Error

func (errorValue *EnvironmentCoercionError) Error() string

Error implements error.

type IanaTimezone

type IanaTimezone struct {
	// contains filtered or unexported fields
}

IanaTimezone is a validated IANA timezone identifier.

func ParseIanaTimezone

func ParseIanaTimezone(value string) (IanaTimezone, error)

ParseIanaTimezone validates an IANA timezone identifier.

func (IanaTimezone) String

func (value IanaTimezone) String() string

String returns the original IANA identifier.

type IsoDuration

type IsoDuration struct {
	// contains filtered or unexported fields
}

IsoDuration is a validated ISO 8601 duration kept as text to avoid lossy conversion.

func ParseIsoDuration

func ParseIsoDuration(value string) (IsoDuration, error)

ParseIsoDuration validates an ISO 8601 duration and normalizes decimal commas.

func (IsoDuration) String

func (value IsoDuration) String() string

String returns the canonical duration text.

type WireCodec

type WireCodec struct{}

WireCodec encodes and decodes the C0 temporal wire forms.

Example
package main

import (
	"fmt"

	"github.com/AtomiCloud/diene.go-core-utils/lib/coreutils"
)

func main() {
	value, _ := coreutils.NewWireDate(2026, 7, 21)
	fmt.Println(coreutils.WireCodec{}.EncodeDate(value))
}
Output:
2026-07-21

func (WireCodec) DecodeDate

func (WireCodec) DecodeDate(value string) (WireDate, error)

DecodeDate decodes a WireDate.

func (WireCodec) DecodeDuration

func (WireCodec) DecodeDuration(value string) (IsoDuration, error)

DecodeDuration decodes an ISO duration.

func (WireCodec) DecodeInstant

func (WireCodec) DecodeInstant(value string) (time.Time, error)

DecodeInstant decodes a UTC instant.

func (WireCodec) DecodeTime

func (WireCodec) DecodeTime(value string) (WireTime, error)

DecodeTime decodes a WireTime.

func (WireCodec) DecodeTimezone

func (WireCodec) DecodeTimezone(value string) (IanaTimezone, error)

DecodeTimezone decodes an IANA timezone.

func (WireCodec) EncodeDate

func (WireCodec) EncodeDate(value WireDate) string

EncodeDate encodes a WireDate.

func (WireCodec) EncodeDuration

func (WireCodec) EncodeDuration(value IsoDuration) string

EncodeDuration encodes an ISO duration.

func (WireCodec) EncodeInstant

func (WireCodec) EncodeInstant(value time.Time) (string, error)

EncodeInstant encodes a UTC instant.

func (WireCodec) EncodeTime

func (WireCodec) EncodeTime(value WireTime) string

EncodeTime encodes a WireTime.

func (WireCodec) EncodeTimezone

func (WireCodec) EncodeTimezone(value IanaTimezone) string

EncodeTimezone encodes an IANA timezone.

type WireDate

type WireDate struct {
	// Year is in the inclusive range 1 through 9999.
	Year int
	// Month is the calendar month.
	Month int
	// Day is the day within Month.
	Day int
}

WireDate is a validated C0 YYYY-MM-DD calendar date.

func NewWireDate

func NewWireDate(year int, month int, day int) (WireDate, error)

NewWireDate validates and creates a WireDate.

func ParseWireDate

func ParseWireDate(value string) (WireDate, error)

ParseWireDate parses a strict YYYY-MM-DD calendar date.

func (WireDate) String

func (value WireDate) String() string

String formats WireDate in canonical YYYY-MM-DD form.

type WireTime

type WireTime struct {
	// Hour is in the inclusive range 0 through 23.
	Hour int
	// Minute is in the inclusive range 0 through 59.
	Minute int
	// Second is in the inclusive range 0 through 59.
	Second int
}

WireTime is a validated C0 HH:mm:ss wall-clock time.

func NewWireTime

func NewWireTime(hour int, minute int, second int) (WireTime, error)

NewWireTime validates and creates a WireTime.

func ParseWireTime

func ParseWireTime(value string) (WireTime, error)

ParseWireTime parses a strict HH:mm:ss wall-clock time.

func (WireTime) String

func (value WireTime) String() string

String formats WireTime in canonical HH:mm:ss form.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL