Repository: fxamacker/cbor
Pull request #682 (2025-07-11 15:55:12)

Use TextUnmarshaler on byte strings with ByteStringToStringAllowed.
<!--
Thank you for your interest in contributing to fxamacker/cbor!
-->

### Description

Decode modes that allow unmarshaling CBOR byte strings into Go strings and recognize TextUnmarshalers should also allow unmarshaling CBOR byte strings into TextUnmarshalers. When interoperating with an encode mode that marshals Go strings to CBOR byte strings, this preserves roundtrippability of TextMarshaler -> CBOR text string -> Go string -> CBOR byte string -> TextUnmarshaler.

<!-- For code contributions, please complete all the items below this line. -->
<!-- For documentation-only contributions, please delete everything below this line. -->

#### PR Was Proposed and Welcomed in Currently Open Issue

- [ ] This PR was proposed and welcomed by maintainer(s) in issue #___
- [x] Closes or Updates Issue #675 

#### Checklist (for code PR only, ignore for docs PR)

- [x] Include unit tests that cover the new code
- [x] Pass all unit tests 
- [x] Pass all lint checks in CI (goimports, gosec, staticcheck, etc.)
- [x] Sign each commit with your real name and email.  
      Last line of each commit message should be in this format:  
      Signed-off-by: Firstname Lastname <firstname.lastname@example.com>
- [x] Certify the Developer's Certificate of Origin 1.1
      (see next section).

#### Certify the Developer's Certificate of Origin 1.1

- [x] By marking this item as completed, I certify 
      the Developer Certificate of Origin 1.1.

```
Developer Certificate of Origin
Version 1.1

Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA

Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
```




Patch:
diff --git a/decode.go b/decode.go
index 2a4482e..f0bdc3b 100644
--- a/decode.go
+++ b/decode.go
@@ -1570,7 +1570,7 @@ func (d *decoder) parseToValue(v reflect.Value, tInfo *typeInfo) error { //nolin
 			return err
 		}
 		copied = copied || converted
-		return fillByteString(t, b, !copied, v, d.dm.byteStringToString, d.dm.binaryUnmarshaler)
+		return fillByteString(t, b, !copied, v, d.dm.byteStringToString, d.dm.binaryUnmarshaler, d.dm.textUnmarshaler)
 
 	case cborTypeTextString:
 		b, err := d.parseTextString()
@@ -1629,7 +1629,7 @@ func (d *decoder) parseToValue(v reflect.Value, tInfo *typeInfo) error { //nolin
 				return nil
 			}
 			if tInfo.nonPtrKind == reflect.Slice || tInfo.nonPtrKind == reflect.Array {
-				return fillByteString(t, b, !copied, v, ByteStringToStringForbidden, d.dm.binaryUnmarshaler)
+				return fillByteString(t, b, !copied, v, ByteStringToStringForbidden, d.dm.binaryUnmarshaler, d.dm.textUnmarshaler)
 			}
 			if bi.IsUint64() {
 				return fillPositiveInt(t, bi.Uint64(), v)
@@ -1652,7 +1652,7 @@ func (d *decoder) parseToValue(v reflect.Value, tInfo *typeInfo) error { //nolin
 				return nil
 			}
 			if tInfo.nonPtrKind == reflect.Slice || tInfo.nonPtrKind == reflect.Array {
-				return fillByteString(t, b, !copied, v, ByteStringToStringForbidden, d.dm.binaryUnmarshaler)
+				return fillByteString(t, b, !copied, v, ByteStringToStringForbidden, d.dm.binaryUnmarshaler, d.dm.textUnmarshaler)
 			}
 			if bi.IsInt64() {
 				return fillNegativeInt(t, bi.Int64(), v)
@@ -3180,7 +3180,7 @@ func fillFloat(t cborType, val float64, v reflect.Value) error {
 	return &UnmarshalTypeError{CBORType: t.String(), GoType: v.Type().String()}
 }
 
-func fillByteString(t cborType, val []byte, shared bool, v reflect.Value, bsts ByteStringToStringMode, bum BinaryUnmarshalerMode) error {
+func fillByteString(t cborType, val []byte, shared bool, v reflect.Value, bsts ByteStringToStringMode, bum BinaryUnmarshalerMode, tum TextUnmarshalerMode) error {
 	if bum == BinaryUnmarshalerByteString && reflect.PointerTo(v.Type()).Implements(typeBinaryUnmarshaler) {
 		if v.CanAddr() {
 			v = v.Addr()
@@ -3193,9 +3193,26 @@ func fillByteString(t cborType, val []byte, shared bool, v reflect.Value, bsts B
 		}
 		return errors.New("cbor: cannot set new value for " + v.Type().String())
 	}
-	if bsts != ByteStringToStringForbidden && v.Kind() == reflect.String {
-		v.SetString(string(val))
-		return nil
+	if bsts != ByteStringToStringForbidden {
+		if tum == TextUnmarshalerTextString && reflect.PointerTo(v.Type()).Implements(typeTextUnmarshaler) {
+			if v.CanAddr() {
+				v = v.Addr()
+				if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
+					// The contract of TextUnmarshaler forbids retaining the input
+					// bytes, so no copying is required even if val is shared.
+					if err := u.UnmarshalText(val); err != nil {
+						return fmt.Errorf("cbor: cannot unmarshal text for %s: %w", v.Type(), err)
+					}
+					return nil
+				}
+			}
+			return errors.New("cbor: cannot set new value for " + v.Type().String())
+		}
+
+		if v.Kind() == reflect.String {
+			v.SetString(string(val))
+			return nil
+		}
 	}
 	if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 {
 		src := val


Test patch:
diff --git a/decode_test.go b/decode_test.go
index 65cafe3..53753c2 100644
--- a/decode_test.go
+++ b/decode_test.go
@@ -10779,6 +10779,15 @@ func TestTextUnmarshalerMode(t *testing.T) {
 			in:   []byte("\x65hello"), // "hello"
 			want: testTextUnmarshaler("hello"),
 		},
+		{
+			name: "UnmarshalText is called for byte string with TextUnmarshalerTextString and ByteStringToStringAllowed",
+			opts: DecOptions{
+				TextUnmarshaler:    TextUnmarshalerTextString,
+				ByteStringToString: ByteStringToStringAllowed,
+			},
+			in:   []byte("\x45hello"), // 'hello'
+			want: testTextUnmarshaler("UnmarshalText"),
+		},
 	} {
 		t.Run(tc.name, func(t *testing.T) {
 			dm, err := tc.opts.DecMode()