|
| 1 | +package gitindex |
| 2 | + |
| 3 | +import "testing" |
| 4 | + |
| 5 | +func TestContentSlab(t *testing.T) { |
| 6 | + t.Run("fits in slab", func(t *testing.T) { |
| 7 | + s := newContentSlab(1024) |
| 8 | + b := s.alloc(100) |
| 9 | + if len(b) != 100 { |
| 10 | + t.Fatalf("len = %d, want 100", len(b)) |
| 11 | + } |
| 12 | + if cap(b) != 100 { |
| 13 | + t.Fatalf("cap = %d, want 100 (3-index slice)", cap(b)) |
| 14 | + } |
| 15 | + }) |
| 16 | + |
| 17 | + t.Run("cap is capped so append cannot corrupt adjacent data", func(t *testing.T) { |
| 18 | + s := newContentSlab(1024) |
| 19 | + a := s.alloc(10) |
| 20 | + copy(a, []byte("aaaaaaaaaa")) |
| 21 | + |
| 22 | + b := s.alloc(10) |
| 23 | + copy(b, []byte("bbbbbbbbbb")) |
| 24 | + |
| 25 | + // Appending to a must not overwrite b. |
| 26 | + a = append(a, 'X') // triggers new backing array since cap==len |
| 27 | + if string(b) != "bbbbbbbbbb" { |
| 28 | + t.Fatalf("adjacent data corrupted: got %q", b) |
| 29 | + } |
| 30 | + _ = a |
| 31 | + }) |
| 32 | + |
| 33 | + t.Run("slab rollover", func(t *testing.T) { |
| 34 | + s := newContentSlab(64) |
| 35 | + a := s.alloc(60) |
| 36 | + if len(a) != 60 || cap(a) != 60 { |
| 37 | + t.Fatalf("a: len=%d cap=%d", len(a), cap(a)) |
| 38 | + } |
| 39 | + // Next alloc doesn't fit in remaining 4 bytes → new slab. |
| 40 | + b := s.alloc(10) |
| 41 | + if len(b) != 10 || cap(b) != 10 { |
| 42 | + t.Fatalf("b: len=%d cap=%d", len(b), cap(b)) |
| 43 | + } |
| 44 | + // a and b should not share backing arrays. |
| 45 | + copy(a, make([]byte, 60)) |
| 46 | + copy(b, []byte("0123456789")) |
| 47 | + if string(b) != "0123456789" { |
| 48 | + t.Fatal("rollover corrupted data") |
| 49 | + } |
| 50 | + }) |
| 51 | + |
| 52 | + t.Run("oversized allocation", func(t *testing.T) { |
| 53 | + s := newContentSlab(64) |
| 54 | + b := s.alloc(128) |
| 55 | + if len(b) != 128 { |
| 56 | + t.Fatalf("len = %d, want 128", len(b)) |
| 57 | + } |
| 58 | + // Oversized alloc should not consume slab space. |
| 59 | + c := s.alloc(32) |
| 60 | + if len(c) != 32 || cap(c) != 32 { |
| 61 | + t.Fatalf("c: len=%d cap=%d", len(c), cap(c)) |
| 62 | + } |
| 63 | + }) |
| 64 | + |
| 65 | + t.Run("zero size", func(t *testing.T) { |
| 66 | + s := newContentSlab(64) |
| 67 | + b := s.alloc(0) |
| 68 | + if len(b) != 0 { |
| 69 | + t.Fatalf("len = %d, want 0", len(b)) |
| 70 | + } |
| 71 | + }) |
| 72 | +} |
0 commit comments