From 0e8f66b31a3652f0e6d6cd13e419bbcb1af93dd3 Mon Sep 17 00:00:00 2001 From: magiccwarss Date: Sun, 8 Nov 2026 11:19:36 +0400 Subject: [PATCH] struct: map uint8 fields as unsigned integers --- struct.go | 3 +-- struct_test.go | 45 ++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/struct.go b/struct.go index 819a6e5..80f8e59 100644 --- a/struct.go +++ b/struct.go @@ -208,8 +208,7 @@ func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim stri } else { field.SetInt(intVal) } - // byte is an alias for uint8, so supporting uint8 breaks support for byte - case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: durationVal, err := key.Duration() // Skip zero value if err == nil && uint64(durationVal) > 0 { diff --git a/struct_test.go b/struct_test.go index ad6ad04..419ffcd 100644 --- a/struct_test.go +++ b/struct_test.go @@ -172,17 +172,17 @@ AllowedIPs = 10.2.0.3/32,fd00:2::3/128 ` type unsupport struct { - Byte byte + Byte complex64 } type unsupport2 struct { Others struct { - Cities byte + Cities complex64 } } type Unsupport3 struct { - Cities byte + Cities complex64 } type unsupport4 struct { @@ -910,3 +910,42 @@ Title = Consultant Engineer ) }) } + +func TestMapToUint8(t *testing.T) { + type count uint8 + type config struct { + Value uint8 + Byte byte + Named count + Pointer *uint8 + NamedPointer *count + } + for _, value := range []uint8{0, 90, 255} { + for _, strict := range []bool{false, true} { + t.Run(fmt.Sprintf("%d/strict=%t", value, strict), func(t *testing.T) { + source := fmt.Sprintf("[mysection]\nValue=%d\nByte=%d\nNamed=%d\nPointer=%d\nNamedPointer=%d\n", value, value, value, value, value) + cfg, err := Load([]byte(source)) + require.NoError(t, err) + var got config + if strict { + err = cfg.Section("mysection").StrictMapTo(&got) + } else { + err = cfg.Section("mysection").MapTo(&got) + } + require.NoError(t, err) + assert.Equal(t, value, got.Value) + assert.Equal(t, value, got.Byte) + assert.Equal(t, count(value), got.Named) + require.NotNil(t, got.Pointer) + assert.Equal(t, value, *got.Pointer) + require.NotNil(t, got.NamedPointer) + assert.Equal(t, count(value), *got.NamedPointer) + reflected := Empty() + require.NoError(t, reflected.Section("mysection").ReflectFrom(&got)) + var roundtrip config + require.NoError(t, reflected.Section("mysection").StrictMapTo(&roundtrip)) + assert.Equal(t, got, roundtrip) + }) + } + } +}