1// Copyright (c) 2017 Couchbase, Inc. 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 15package vellum 16 17import ( 18 "bufio" 19 "errors" 20 "fmt" 21 "testing" 22) 23 24func TestPackedSize(t *testing.T) { 25 tests := []struct { 26 input uint64 27 want int 28 }{ 29 {0, 1}, 30 {1<<8 - 1, 1}, 31 {1 << 8, 2}, 32 {1<<16 - 1, 2}, 33 {1 << 16, 3}, 34 {1<<24 - 1, 3}, 35 {1 << 24, 4}, 36 {1<<32 - 1, 4}, 37 {1 << 32, 5}, 38 {1<<40 - 1, 5}, 39 {1 << 40, 6}, 40 {1<<48 - 1, 6}, 41 {1 << 48, 7}, 42 {1<<56 - 1, 7}, 43 {1 << 56, 8}, 44 {1<<64 - 1, 8}, 45 } 46 47 for _, test := range tests { 48 t.Run(fmt.Sprintf("input %d", test.input), func(t *testing.T) { 49 got := packedSize(test.input) 50 if got != test.want { 51 t.Errorf("wanted: %d, got: %d", test.want, got) 52 } 53 }) 54 } 55} 56 57var errStub = errors.New("stub error") 58 59type stubWriter struct { 60 err error 61} 62 63func (s *stubWriter) Write(p []byte) (n int, err error) { 64 err = s.err 65 return 66} 67 68func TestWriteByteErr(t *testing.T) { 69 // create writer, force underlying buffered writer to size 1 70 w := &writer{ 71 w: bufio.NewWriterSize(&stubWriter{errStub}, 1), 72 } 73 74 // then write 2 bytes, which should force error 75 _ = w.WriteByte('a') 76 err := w.WriteByte('a') 77 if err != errStub { 78 t.Errorf("expected %v, got %v", errStub, err) 79 } 80} 81 82func TestWritePackedUintErr(t *testing.T) { 83 // create writer, force underlying buffered writer to size 1 84 w := &writer{ 85 w: bufio.NewWriterSize(&stubWriter{errStub}, 1), 86 } 87 88 err := w.WritePackedUint(36592) 89 if err != errStub { 90 t.Errorf("expected %v, got %v", errStub, err) 91 } 92} 93