Skip to content
This repository has been archived by the owner on Feb 3, 2024. It is now read-only.

Commit

Permalink
validate provided table property values to prevent V panics (#32)
Browse files Browse the repository at this point in the history
* check that data is not empty

* ensure tabsize of at least 2

* validate padding

* provide a default value for Table.custom_style

* add test for the validation function
  • Loading branch information
Lukas Neubert authored Nov 17, 2020
1 parent 0ea2451 commit af60435
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
18 changes: 17 additions & 1 deletion termtable.v
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down
27 changes: 27 additions & 0 deletions termtable_test.v
Original file line number Diff line number Diff line change
@@ -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'],
Expand Down

0 comments on commit af60435

Please sign in to comment.