From 4d8b2e999543f84132740ef0edfd87862f657d30 Mon Sep 17 00:00:00 2001 From: Turiiya <34311583+ttytm@users.noreply.github.com> Date: Wed, 13 Sep 2023 11:48:14 +0200 Subject: [PATCH] toml: fix custom `to_toml` for complex structs (#19338) --- vlib/toml/tests/encode_and_decode_test.v | 28 ++++++++++++++++++++++++ vlib/toml/toml.v | 12 +++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/vlib/toml/tests/encode_and_decode_test.v b/vlib/toml/tests/encode_and_decode_test.v index 1e1ba3154baab3..f69fbdb2700fcd 100644 --- a/vlib/toml/tests/encode_and_decode_test.v +++ b/vlib/toml/tests/encode_and_decode_test.v @@ -121,6 +121,34 @@ title = 2' assert y.title == .worker } +struct Example1 { + arr []Problem +} + +struct Example2 { + arr []Problem +} + +struct Problem { + x int +} + +pub fn (example Example1) to_toml() string { + return '[This is Valid]' +} + +pub fn (problem Problem) to_toml() string { + return 'a problem' +} + +fn test_custom_encode_of_complex_struct() { + assert toml.encode(Example1{}) == '[This is Valid]' + assert toml.encode(Example2{[Problem{}, Problem{}]}) == 'arr = [ + "a problem", + "a problem" +]' +} + fn test_array_encode_decode() { a := Arrs{ strs: ['foo', 'bar'] diff --git a/vlib/toml/toml.v b/vlib/toml/toml.v index a933591f6c28ef..faeacc8f50be69 100644 --- a/vlib/toml/toml.v +++ b/vlib/toml/toml.v @@ -101,7 +101,17 @@ fn encode_struct[T](typ T) map[string]Any { } $else $if field.is_array { mut arr := []Any{} for v in value { - arr << Any(v) + $if v is Date { + arr << Any(v) + } $else $if v is Time { + arr << Any(v) + } $else $if v is DateTime { + arr << Any(v) + } $else $if v is $struct { + arr << Any(encode(v)) + } $else { + arr << Any(v) + } } mp[field.name] = arr } $else {