Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ type Encoder struct {
anchorNameMap map[string]struct{}
anchorCallback func(*ast.AnchorNode, interface{}) error
customMarshalerMap map[reflect.Type]func(interface{}) ([]byte, error)
autoInt bool
useLiteralStyleIfMultiline bool
commentMap map[*Path][]*Comment
written bool
Expand Down Expand Up @@ -547,6 +548,9 @@ func (e *Encoder) encodeFloat(v float64, bitSize int) ast.Node {
}
value := strconv.FormatFloat(v, 'g', -1, bitSize)
if !strings.Contains(value, ".") && !strings.Contains(value, "e") {
if e.autoInt {
return ast.Integer(token.New(value, value, e.pos(e.column)))
}
// append x.0 suffix to keep float value context
value = fmt.Sprintf("%s.0", value)
}
Expand Down
48 changes: 48 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1283,6 +1283,54 @@ func TestEncoder_CustomMarshaler(t *testing.T) {
})
}

func TestEncoder_AutoInt(t *testing.T) {
for _, test := range []struct {
desc string
input any
expected string
}{
{
desc: "int-convertible float64",
input: map[string]float64{
"key": 1.0,
},
expected: "key: 1\n",
},
{
desc: "non int-convertible float64",
input: map[string]float64{
"key": 1.1,
},
expected: "key: 1.1\n",
},
{
desc: "int-convertible float32",
input: map[string]float32{
"key": 1.0,
},
expected: "key: 1\n",
},
{
desc: "non int-convertible float32",
input: map[string]float32{
"key": 1.1,
},
expected: "key: 1.1\n",
},
} {
t.Run(test.desc, func(t *testing.T) {
var buf bytes.Buffer
enc := yaml.NewEncoder(&buf, yaml.AutoInt())
if err := enc.Encode(test.input); err != nil {
t.Fatalf("failed to encode: %s", err)
}
if actual := buf.String(); actual != test.expected {
t.Errorf("expect:\n%s\nactual\n%s\n", test.expected, actual)
}
})
}
}

func TestEncoder_MultipleDocuments(t *testing.T) {
var buf bytes.Buffer
enc := yaml.NewEncoder(&buf)
Expand Down
9 changes: 9 additions & 0 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,15 @@ func CustomMarshaler[T any](marshaler func(T) ([]byte, error)) EncodeOption {
}
}

// AutoInt automatically converts floating-point numbers to integers when the fractional part is zero.
// For example, a value of 1.0 will be encoded as 1.
func AutoInt() EncodeOption {
return func(e *Encoder) error {
e.autoInt = true
return nil
}
}

// CommentPosition type of the position for comment.
type CommentPosition int

Expand Down