github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/buffer/buffer_test.go (about) 1 // Copyright 2021 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package buffer 16 17 import ( 18 "bytes" 19 "testing" 20 ) 21 22 func TestBufferRemove(t *testing.T) { 23 sample := []byte("01234567") 24 25 // Success cases 26 for _, tc := range []struct { 27 desc string 28 data []byte 29 rng Range 30 want []byte 31 }{ 32 { 33 desc: "empty slice", 34 }, 35 { 36 desc: "empty range", 37 data: sample, 38 want: sample, 39 }, 40 { 41 desc: "empty range with positive begin", 42 data: sample, 43 rng: Range{begin: 1, end: 1}, 44 want: sample, 45 }, 46 { 47 desc: "range at beginning", 48 data: sample, 49 rng: Range{begin: 0, end: 1}, 50 want: sample[1:], 51 }, 52 { 53 desc: "range in middle", 54 data: sample, 55 rng: Range{begin: 2, end: 4}, 56 want: []byte("014567"), 57 }, 58 { 59 desc: "range at end", 60 data: sample, 61 rng: Range{begin: 7, end: 8}, 62 want: sample[:7], 63 }, 64 { 65 desc: "range all", 66 data: sample, 67 rng: Range{begin: 0, end: 8}, 68 }, 69 } { 70 t.Run(tc.desc, func(t *testing.T) { 71 var buf buffer 72 buf.initWithData(tc.data) 73 if ok := buf.Remove(tc.rng); !ok { 74 t.Errorf("buf.Remove(%#v) = false, want true", tc.rng) 75 } else if got := buf.ReadSlice(); !bytes.Equal(got, tc.want) { 76 t.Errorf("buf.ReadSlice() = %q, want %q", got, tc.want) 77 } 78 }) 79 } 80 81 // Failure cases 82 for _, tc := range []struct { 83 desc string 84 data []byte 85 rng Range 86 }{ 87 { 88 desc: "begin out-of-range", 89 data: sample, 90 rng: Range{begin: -1, end: 4}, 91 }, 92 { 93 desc: "end out-of-range", 94 data: sample, 95 rng: Range{begin: 4, end: 9}, 96 }, 97 { 98 desc: "both out-of-range", 99 data: sample, 100 rng: Range{begin: -100, end: 100}, 101 }, 102 } { 103 t.Run(tc.desc, func(t *testing.T) { 104 var buf buffer 105 buf.initWithData(tc.data) 106 if ok := buf.Remove(tc.rng); ok { 107 t.Errorf("buf.Remove(%#v) = true, want false", tc.rng) 108 } 109 }) 110 } 111 }