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	"io"
20)
21
22// A writer is a buffered writer used by vellum. It counts how many bytes have
23// been written and has some convenience methods used for encoding the data.
24type writer struct {
25	w       *bufio.Writer
26	counter int
27}
28
29func newWriter(w io.Writer) *writer {
30	return &writer{
31		w: bufio.NewWriter(w),
32	}
33}
34
35func (w *writer) Reset(newWriter io.Writer) {
36	w.w.Reset(newWriter)
37	w.counter = 0
38}
39
40func (w *writer) WriteByte(c byte) error {
41	err := w.w.WriteByte(c)
42	if err != nil {
43		return err
44	}
45	w.counter++
46	return nil
47}
48
49func (w *writer) Write(p []byte) (int, error) {
50	n, err := w.w.Write(p)
51	w.counter += n
52	return n, err
53}
54
55func (w *writer) Flush() error {
56	return w.w.Flush()
57}
58
59func (w *writer) WritePackedUintIn(v uint64, n int) error {
60	for shift := uint(0); shift < uint(n*8); shift += 8 {
61		err := w.WriteByte(byte(v >> shift))
62		if err != nil {
63			return err
64		}
65	}
66
67	return nil
68}
69
70func (w *writer) WritePackedUint(v uint64) error {
71	n := packedSize(v)
72	return w.WritePackedUintIn(v, n)
73}
74
75func packedSize(n uint64) int {
76	if n < 1<<8 {
77		return 1
78	} else if n < 1<<16 {
79		return 2
80	} else if n < 1<<24 {
81		return 3
82	} else if n < 1<<32 {
83		return 4
84	} else if n < 1<<40 {
85		return 5
86	} else if n < 1<<48 {
87		return 6
88	} else if n < 1<<56 {
89		return 7
90	}
91	return 8
92}
93