You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

count.go 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 zap
  15. import (
  16. "hash/crc32"
  17. "io"
  18. segment "github.com/blevesearch/scorch_segment_api/v2"
  19. )
  20. // CountHashWriter is a wrapper around a Writer which counts the number of
  21. // bytes which have been written and computes a crc32 hash
  22. type CountHashWriter struct {
  23. w io.Writer
  24. crc uint32
  25. n int
  26. s segment.StatsReporter
  27. }
  28. // NewCountHashWriter returns a CountHashWriter which wraps the provided Writer
  29. func NewCountHashWriter(w io.Writer) *CountHashWriter {
  30. return &CountHashWriter{w: w}
  31. }
  32. func NewCountHashWriterWithStatsReporter(w io.Writer, s segment.StatsReporter) *CountHashWriter {
  33. return &CountHashWriter{w: w, s: s}
  34. }
  35. // Write writes the provided bytes to the wrapped writer and counts the bytes
  36. func (c *CountHashWriter) Write(b []byte) (int, error) {
  37. n, err := c.w.Write(b)
  38. c.crc = crc32.Update(c.crc, crc32.IEEETable, b[:n])
  39. c.n += n
  40. if c.s != nil {
  41. c.s.ReportBytesWritten(uint64(n))
  42. }
  43. return n, err
  44. }
  45. // Count returns the number of bytes written
  46. func (c *CountHashWriter) Count() int {
  47. return c.n
  48. }
  49. // Sum32 returns the CRC-32 hash of the content written to this writer
  50. func (c *CountHashWriter) Sum32() uint32 {
  51. return c.crc
  52. }