Repository: fxamacker/cbor
Pull request #352 (2022-06-06 14:27:47)

add option to enforce nil container marshaling as empty containers
<!--
Thank you for your interest in contributing to fxamacker/cbor!
-->

### Description
PR for Issue #351

<!-- 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 #351 
- [x] Closes or Updates Issue #351 

#### 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 18 ci linters (golint, 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 79ccaf8..3110766 100644
--- a/decode.go
+++ b/decode.go
@@ -200,6 +200,23 @@ func (m IndefLengthMode) valid() bool {
 	return m < maxIndefLengthMode
 }
 
+// NilContainersMode specifies how to encode []Type(nil) and map[Key]Type(nil).
+type NilContainersMode int
+
+const (
+	// NullForNil enforces null for []Type(nil)/map[Key]Type(nil).
+	NullForNil NilContainersMode = iota
+
+	// EmptyForNil enforces empty map/list for []Type(nil)/map[Key]Type(nil).
+	EmptyForNil
+
+	maxNilContainersMode
+)
+
+func (m NilContainersMode) valid() bool {
+	return m < maxNilContainersMode
+}
+
 // TagsMode specifies whether to allow CBOR tags.
 type TagsMode int
 
diff --git a/encode.go b/encode.go
index 95d2c23..6691d38 100644
--- a/encode.go
+++ b/encode.go
@@ -292,6 +292,9 @@ type EncOptions struct {
 	// IndefLength specifies whether to allow indefinite length CBOR items.
 	IndefLength IndefLengthMode
 
+	// NilContainers specifies how to encode map[Key]Type(nil)/[]Type(nil)
+	NilContainers NilContainersMode
+
 	// TagsMd specifies whether to allow CBOR tags (major type 6).
 	TagsMd TagsMode
 }
@@ -464,6 +467,9 @@ func (opts EncOptions) encMode() (*encMode, error) {
 	if !opts.IndefLength.valid() {
 		return nil, errors.New("cbor: invalid IndefLength " + strconv.Itoa(int(opts.IndefLength)))
 	}
+	if !opts.NilContainers.valid() {
+		return nil, errors.New("cbor: invalid NilContainers " + strconv.Itoa(int(opts.NilContainers)))
+	}
 	if !opts.TagsMd.valid() {
 		return nil, errors.New("cbor: invalid TagsMd " + strconv.Itoa(int(opts.TagsMd)))
 	}
@@ -479,6 +485,7 @@ func (opts EncOptions) encMode() (*encMode, error) {
 		time:          opts.Time,
 		timeTag:       opts.TimeTag,
 		indefLength:   opts.IndefLength,
+		nilContainers: opts.NilContainers,
 		tagsMd:        opts.TagsMd,
 	}
 	return &em, nil
@@ -501,6 +508,7 @@ type encMode struct {
 	time          TimeMode
 	timeTag       EncTagMode
 	indefLength   IndefLengthMode
+	nilContainers NilContainersMode
 	tagsMd        TagsMode
 }
 
@@ -787,7 +795,7 @@ func encodeFloat64(e *encoderBuffer, f64 float64) error {
 
 func encodeByteString(e *encoderBuffer, em *encMode, v reflect.Value) error {
 	vk := v.Kind()
-	if vk == reflect.Slice && v.IsNil() {
+	if vk == reflect.Slice && v.IsNil() && em.nilContainers == NullForNil {
 		e.Write(cborNil)
 		return nil
 	}
@@ -824,7 +832,7 @@ type arrayEncodeFunc struct {
 }
 
 func (ae arrayEncodeFunc) encode(e *encoderBuffer, em *encMode, v reflect.Value) error {
-	if v.Kind() == reflect.Slice && v.IsNil() {
+	if v.Kind() == reflect.Slice && v.IsNil() && em.nilContainers == NullForNil {
 		e.Write(cborNil)
 		return nil
 	}
@@ -849,7 +857,7 @@ type mapEncodeFunc struct {
 }
 
 func (me mapEncodeFunc) encode(e *encoderBuffer, em *encMode, v reflect.Value) error {
-	if v.IsNil() {
+	if v.IsNil() && em.nilContainers == NullForNil {
 		e.Write(cborNil)
 		return nil
 	}


Test patch:
diff --git a/encode_test.go b/encode_test.go
index 229f755..7468c08 100644
--- a/encode_test.go
+++ b/encode_test.go
@@ -2852,6 +2852,50 @@ func TestInvalidInfConvert(t *testing.T) {
 	}
 }
 
+func TestNilContainers(t *testing.T) {
+	nilContainersNull := EncOptions{NilContainers: NullForNil}
+	nilContainersEmpty := EncOptions{NilContainers: EmptyForNil}
+	testCases := []struct {
+		name         string
+		v            interface{}
+		opts         EncOptions
+		wantCborData []byte
+	}{
+		{"map(nil) as null", map[string]string(nil), nilContainersNull, hexDecode("f6")},
+		{"map(nil) as empty map", map[string]string(nil), nilContainersEmpty, hexDecode("a0")},
+
+		{"slice(nil) as null", []int(nil), nilContainersNull, hexDecode("f6")},
+		{"slice(nil) as empty list", []int(nil), nilContainersEmpty, hexDecode("80")},
+
+		{"[]byte(nil) as null", []byte(nil), nilContainersNull, hexDecode("f6")},
+		{"[]byte(nil) as empty bytestring", []byte(nil), nilContainersEmpty, hexDecode("40")},
+	}
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			em, err := tc.opts.EncMode()
+			if err != nil {
+				t.Errorf("EncMode() returned an error %v", err)
+			}
+			b, err := em.Marshal(tc.v)
+			if err != nil {
+				t.Errorf("Marshal(%v) returned error %v", tc.v, err)
+			} else if !bytes.Equal(b, tc.wantCborData) {
+				t.Errorf("Marshal(%v) = 0x%x, want 0x%x", tc.v, b, tc.wantCborData)
+			}
+		})
+	}
+}
+
+func TestInvalidNilContainers(t *testing.T) {
+	wantErrorMsg := "cbor: invalid NilContainers 100"
+	_, err := EncOptions{NilContainers: NilContainersMode(100)}.EncMode()
+	if err == nil {
+		t.Errorf("EncMode() didn't return an error")
+	} else if err.Error() != wantErrorMsg {
+		t.Errorf("EncMode() returned error %q, want %q", err.Error(), wantErrorMsg)
+	}
+}
+
 // Keith Randall's workaround for constant propagation issue https://github.com/golang/go/issues/36400
 const (
 	// qnan 32 bits constants
@@ -3306,6 +3350,7 @@ func TestEncOptions(t *testing.T) {
 		Time:          TimeRFC3339Nano,
 		TimeTag:       EncTagRequired,
 		IndefLength:   IndefLengthForbidden,
+		NilContainers: NullForNil,
 		TagsMd:        TagsAllowed,
 	}
 	em, err := opts1.EncMode()