From 12dd6e8b39d3d24872b6a2de6f8c5c52f3bef3df Mon Sep 17 00:00:00 2001 From: Turiiya <34311583+ttytm@users.noreply.github.com> Date: Sun, 10 Sep 2023 16:32:02 +0200 Subject: [PATCH] toml: add comptime check if a supported type (struct) was passed to `toml.decode`, when the type has no custom `.from_toml` method defined (#19317) --- vlib/toml/tests/encode_and_decode_test.v | 10 ++++++++++ vlib/toml/toml.v | 3 +++ 2 files changed, 13 insertions(+) diff --git a/vlib/toml/tests/encode_and_decode_test.v b/vlib/toml/tests/encode_and_decode_test.v index 6f57bf7473..66e7192bf9 100644 --- a/vlib/toml/tests/encode_and_decode_test.v +++ b/vlib/toml/tests/encode_and_decode_test.v @@ -177,3 +177,13 @@ times = [ assert toml.encode[Arrs](a) == s assert toml.decode[Arrs](s)! == a } + +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' } + // ... +} diff --git a/vlib/toml/toml.v b/vlib/toml/toml.v index ad94095c38..fea73da731 100644 --- a/vlib/toml/toml.v +++ b/vlib/toml/toml.v @@ -23,6 +23,9 @@ pub fn decode[T](toml_txt string) !T { return typ } } + $if T !is $struct { + return error('toml.decode: expected struct, found ${T.name}') + } decode_struct[T](doc.to_any(), mut typ) return typ }