2021-12-03 13:40:46 +03:00
|
|
|
import toml
|
|
|
|
|
|
|
|
const toml_text = '# This TOML can reflect to a struct
|
|
|
|
name = "Tom"
|
|
|
|
age = 45
|
|
|
|
height = 1.97
|
|
|
|
|
|
|
|
birthday = 1980-04-23
|
|
|
|
|
2022-01-21 22:20:44 +03:00
|
|
|
strings = [
|
|
|
|
"v matures",
|
|
|
|
"like rings",
|
|
|
|
"spread in the",
|
|
|
|
"water"
|
|
|
|
]
|
|
|
|
|
|
|
|
bools = [true, false, true, true]
|
|
|
|
|
|
|
|
floats = [0.0, 1.0, 2.0, 3.0]
|
|
|
|
|
|
|
|
int_map = {"a" = 0, "b" = 1, "c" = 2, "d" = 3}
|
|
|
|
|
2021-12-03 13:40:46 +03:00
|
|
|
[bio]
|
|
|
|
text = "Tom has done many great things"
|
|
|
|
years_of_service = 5
|
|
|
|
|
2022-08-22 20:39:55 +03:00
|
|
|
[field_remap]
|
|
|
|
txt = "I am remapped"
|
|
|
|
uint64 = 100
|
|
|
|
|
2021-12-03 13:40:46 +03:00
|
|
|
[config]
|
|
|
|
data = [ 1, 2, 3 ]
|
|
|
|
levels = { "info" = 1, "warn" = 2, "critical" = 3 }
|
|
|
|
'
|
|
|
|
|
2022-08-22 20:39:55 +03:00
|
|
|
struct FieldRemap {
|
|
|
|
text string [toml: 'txt']
|
|
|
|
num u64 [toml: 'uint64']
|
|
|
|
}
|
|
|
|
|
2021-12-03 13:40:46 +03:00
|
|
|
struct Bio {
|
|
|
|
text string
|
|
|
|
years_of_service int
|
|
|
|
}
|
|
|
|
|
|
|
|
struct User {
|
|
|
|
name string
|
|
|
|
age int
|
|
|
|
height f64
|
|
|
|
birthday toml.Date
|
2022-01-21 22:20:44 +03:00
|
|
|
strings []string
|
|
|
|
bools []bool
|
|
|
|
floats []f32
|
|
|
|
int_map map[string]int
|
2021-12-03 13:40:46 +03:00
|
|
|
|
|
|
|
config toml.Any
|
|
|
|
mut:
|
2022-08-22 20:39:55 +03:00
|
|
|
bio Bio
|
|
|
|
remap FieldRemap
|
2021-12-03 13:40:46 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
fn test_reflect() {
|
2022-03-19 00:32:06 +03:00
|
|
|
toml_doc := toml.parse_text(toml_text) or { panic(err) }
|
2021-12-03 13:40:46 +03:00
|
|
|
|
|
|
|
mut user := toml_doc.reflect<User>()
|
|
|
|
user.bio = toml_doc.value('bio').reflect<Bio>()
|
2022-08-22 20:39:55 +03:00
|
|
|
user.remap = toml_doc.value('field_remap').reflect<FieldRemap>()
|
2021-12-03 13:40:46 +03:00
|
|
|
|
|
|
|
assert user.name == 'Tom'
|
|
|
|
assert user.age == 45
|
|
|
|
assert user.height == 1.97
|
|
|
|
assert user.birthday.str() == '1980-04-23'
|
2022-01-21 22:20:44 +03:00
|
|
|
assert user.strings == ['v matures', 'like rings', 'spread in the', 'water']
|
|
|
|
assert user.bools == [true, false, true, true]
|
|
|
|
assert user.floats == [f32(0.0), 1.0, 2.0, 3.0]
|
|
|
|
assert user.int_map == {
|
|
|
|
'a': 0
|
|
|
|
'b': 1
|
|
|
|
'c': 2
|
|
|
|
'd': 3
|
|
|
|
}
|
2021-12-03 13:40:46 +03:00
|
|
|
assert user.bio.text == 'Tom has done many great things'
|
|
|
|
assert user.bio.years_of_service == 5
|
|
|
|
|
2022-08-22 20:39:55 +03:00
|
|
|
assert user.remap.text == 'I am remapped'
|
|
|
|
assert user.remap.num == 100
|
|
|
|
|
2021-12-03 13:40:46 +03:00
|
|
|
assert user.config.value('data[0]').int() == 1
|
|
|
|
assert user.config.value('levels.warn').int() == 2
|
|
|
|
}
|