diff --git a/vlib/toml/tests/encode_and_decode_test.v b/vlib/toml/tests/encode_and_decode_test.v index 66e7192bf97cfa..963319c58c505f 100644 --- a/vlib/toml/tests/encode_and_decode_test.v +++ b/vlib/toml/tests/encode_and_decode_test.v @@ -178,6 +178,20 @@ times = [ assert toml.decode[Arrs](s)! == a } +fn test_decode_doc() { + doc := toml.parse_text('name = "Peter" +age = 28 +is_human = true +salary = 100000.5 +title = 2')! + e := doc.decode[Employee]()! + assert e.name == 'Peter' + assert e.age == 28 + assert e.salary == 100000.5 + assert e.is_human == true + assert e.title == .manager +} + fn test_unsupported_type() { s := 'name = "Peter"' err_msg := 'toml.decode: expected struct, found ' @@ -186,4 +200,8 @@ fn test_unsupported_type() { toml.decode[int](s) or { assert err.msg() == err_msg + 'int' } toml.decode[[]f32](s) or { assert err.msg() == err_msg + '[]f32' } // ... + + doc := toml.parse_text('name = "Peter"')! + assert doc.value('name').string() == 'Peter' + doc.decode[string]() or { assert err.msg() == 'Doc.decode: expected struct, found string' } } diff --git a/vlib/toml/toml.v b/vlib/toml/toml.v index fea73da731f908..2ff708826633b5 100644 --- a/vlib/toml/toml.v +++ b/vlib/toml/toml.v @@ -252,6 +252,16 @@ fn parse_array_key(key string) (string, int) { return k, index } +// decode decodes a TOML `string` into the target struct type `T`. +pub fn (d Doc) decode[T]() !T { + mut typ := T{} + $if T !is $struct { + return error('Doc.decode: expected struct, found ${T.name}') + } + decode_struct(d.to_any(), mut typ) + return typ +} + // to_any converts the `Doc` to toml.Any type. pub fn (d Doc) to_any() Any { return ast_to_any(d.ast.table)