diff --git a/termtable.v b/termtable.v index eb202e1..458c72a 100644 --- a/termtable.v +++ b/termtable.v @@ -34,10 +34,14 @@ pub mut: align Alignment = .left padding int = 1 tabsize int = 4 - custom_style StyleConfig + custom_style StyleConfig = StyleConfig{} } pub fn (t Table) str() string { + validate_table_properties(t) or { + eprintln('termtable: $err') + exit(1) + } edata := expand_tabs(t.data, t.tabsize) rowdata, coldata := get_row_and_col_data(edata, t.orientation) colmaxes := max_column_sizes(coldata) @@ -68,6 +72,18 @@ pub fn (t Table) str() string { return final_str.trim_space() } +fn validate_table_properties(t Table) ? { + if t.data == [][]string{} { + return error('Table.data should not be empty.') + } + if t.tabsize < 2 { + return error('tabsize should be at least 2 (got $t.tabsize).') + } + if t.padding < 0 { + return error('cannot use a negative padding (got $t.padding).') + } +} + fn expand_tabs(raw_data [][]string, tabsize int) [][]string { mut edata := [][]string{} for d in raw_data { diff --git a/termtable_test.v b/termtable_test.v index 1924469..ddeb29c 100644 --- a/termtable_test.v +++ b/termtable_test.v @@ -1,5 +1,32 @@ module termtable +fn test_validate_table_properties() { + tables := { + 'no_data': Table{} + 'small_tab': Table{ + data: [['Foo\t']] + tabsize: 1 + } + 'negative_pad': Table{ + data: [['Foo']] + padding: -1 + } + } + error_suffixes := { + 'no_data': 'Table.data should not be empty.' + 'small_tab': 'tabsize should be at least 2 (got 1).' + 'negative_pad': 'cannot use a negative padding (got -1).' + } + mut errors := 0 + for k, t in tables { + validate_table_properties(t) or { + errors++ + assert err == error_suffixes[k] + } + } + assert errors == tables.len +} + fn test_expand_tabs() { tabs := [ ['\tName', 'Sex\t\t'],