Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

toml: implement decode method for Doc #19318

Merged
merged 1 commit into from
Sep 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 42 additions & 4 deletions vlib/toml/tests/encode_and_decode_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -178,12 +178,50 @@ 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 '
toml.decode[string](s) or { assert err.msg() == err_msg + 'string' }
toml.decode[[]string](s) or { assert err.msg() == err_msg + '[]string' }
toml.decode[int](s) or { assert err.msg() == err_msg + 'int' }
toml.decode[[]f32](s) or { assert err.msg() == err_msg + '[]f32' }
if _ := toml.decode[string](s) {
assert false
} else {
assert err.msg() == err_msg + 'string'
}
if _ := toml.decode[[]string](s) {
assert false
} else {
assert err.msg() == err_msg + '[]string'
}
if _ := toml.decode[int](s) {
assert false
} else {
assert err.msg() == err_msg + 'int'
}
if _ := toml.decode[[]f32](s) {
assert false
} else {
assert err.msg() == err_msg + '[]f32'
}
// ...

doc := toml.parse_text('name = "Peter"')!
assert doc.value('name').string() == 'Peter'
if _ := doc.decode[string]() {
assert false
} else {
assert err.msg() == 'Doc.decode: expected struct, found string'
}
}
10 changes: 10 additions & 0 deletions vlib/toml/toml.v
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
$if T !is $struct {
return error('Doc.decode: expected struct, found ${T.name}')
}
mut typ := T{}
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)
Expand Down
Loading