本站源代码
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

93 lignes
1.9KB

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