|
| 1 | +package systemd |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "testing" |
| 6 | +) |
| 7 | + |
| 8 | +func TestRangeToBits(t *testing.T) { |
| 9 | + testCases := []struct { |
| 10 | + in string |
| 11 | + out []byte |
| 12 | + isErr bool |
| 13 | + }{ |
| 14 | + {in: "", isErr: true}, |
| 15 | + {in: "0", out: []byte{1}}, |
| 16 | + {in: "1", out: []byte{2}}, |
| 17 | + {in: "0-1", out: []byte{3}}, |
| 18 | + {in: "0,1", out: []byte{3}}, |
| 19 | + {in: ",0,1,", out: []byte{3}}, |
| 20 | + {in: "0-3", out: []byte{0x0f}}, |
| 21 | + {in: "0,1,2-3", out: []byte{0x0f}}, |
| 22 | + {in: "4-7", out: []byte{0xf0}}, |
| 23 | + {in: "0-7", out: []byte{0xff}}, |
| 24 | + {in: "0-15", out: []byte{0xff, 0xff}}, |
| 25 | + {in: "16", out: []byte{1, 0, 0}}, |
| 26 | + {in: "0-3,32-33", out: []byte{3, 0, 0, 0, 0x0f}}, |
| 27 | + // extra spaces and tabs are ok |
| 28 | + {in: "1, 2, 1-2", out: []byte{6}}, |
| 29 | + {in: " , 1 , 3 , 5-7, ", out: []byte{0xea}}, |
| 30 | + // somewhat large values |
| 31 | + {in: "128-130,1", out: []byte{7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2}}, |
| 32 | + |
| 33 | + {in: "-", isErr: true}, |
| 34 | + {in: "1-", isErr: true}, |
| 35 | + {in: "-3", isErr: true}, |
| 36 | + // bad range (start > end) |
| 37 | + {in: "54-53", isErr: true}, |
| 38 | + // kernel does not allow extra spaces inside a range |
| 39 | + {in: "1 - 2", isErr: true}, |
| 40 | + } |
| 41 | + |
| 42 | + for _, tc := range testCases { |
| 43 | + t.Logf("case: %q", tc.in) |
| 44 | + out, err := rangeToBits(tc.in) |
| 45 | + if err != nil { |
| 46 | + t.Logf(" got error: %s", err) |
| 47 | + if !tc.isErr { |
| 48 | + t.Error(" ^^^ unexpected error") |
| 49 | + } |
| 50 | + |
| 51 | + continue |
| 52 | + } |
| 53 | + t.Logf(" expected %v, got %v", tc.out, out) |
| 54 | + if !bytes.Equal(out, tc.out) { |
| 55 | + t.Error(" ^^^ unexpected result") |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments