[
  {
    "path": ".gitignore",
    "content": "# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture specific extensions/prefixes\n*.[568vq]\n[568vq].out\n\n*.cgo1.go\n*.cgo2.c\n_cgo_defun.c\n_cgo_gotypes.go\n_cgo_export.*\n\n_testmain.go\n\n*.exe\n*.test\n*~\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2014, 2015 Jason E. Aten, Ph.D.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE."
  },
  {
    "path": "README.md",
    "content": "rbuf: a circular ring buffer in Golang\n====\n\n\ntype FixedSizeRingBuf struct:\n\n   * is a fixed-size circular ring buffer. Yes, just what is says.\n     This structure is only for bytes, as it was written to\n     optimize I/O, but could be easily adapted to any other type.\n\n   * We keep a pair of ping/pong buffers so that we can linearize\n   the circular buffer into a contiguous slice if need be.\n\nFor efficiency, a FixedSizeRingBuf may be vastly preferred to\na bytes.Buffer. The ReadWithoutAdvance(), Advance(), and Adopt()\nmethods are all non-standard methods written for speed.\n\nFor an I/O heavy application, I have replaced bytes.Buffer with\nFixedSizeRingBuf and seen memory consumption go from 8GB to 25MB.\nYes, that is a 300x reduction in memory footprint. Everything ran\nfaster too.\n\nNote that Bytes(), while inescapable at times, is expensive: avoid\nit if possible. If all you need is len(Bytes()), then it is better \nto use the FixedSizeRingBuf.Readable member directly.\nBytes() is expensive because it may copy the back and then \nthe front of a wrapped buffer A[Use] into A[1-Use] in order to \nget a contiguous, unwrapped, slice. If possible use ContigLen()\nfirst to get the size that can be read without copying, Read() that\namount, and then Read() a second time -- to avoid the copy.\n\ncopyright (c) 2014, Jason E. Aten\n\nlicense: MIT\n"
  },
  {
    "path": "atomic_rbuf.go",
    "content": "package rbuf\n\n// AtomicFixedSizeRingBuf: Synchronized version of FixedSizeRingBuf,\n// safe for concurrent access.\n//\n// copyright (c) 2014, Jason E. Aten\n// license: MIT\n//\n// Some text from the Golang standard library doc is adapted and\n// reproduced in fragments below to document the expected behaviors\n// of the interface functions Read()/Write()/ReadFrom()/WriteTo() that\n// are implemented here. Those descriptions (see\n// http://golang.org/pkg/io/#Reader for example) are\n// copyright 2010 The Go Authors.\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"sync\"\n)\n\n// AtomicFixedSizeRingBuf: see FixedSizeRingBuf for the full\n// details; this is the same, just safe for current access\n// (and thus paying the price of synchronization on each call\n// as well.)\n//\ntype AtomicFixedSizeRingBuf struct {\n\tA        [2][]byte // a pair of ping/pong buffers. Only one is active.\n\tUse      int       // which A buffer is in active use, 0 or 1\n\tN        int       // MaxViewInBytes, the size of A[0] and A[1] in bytes.\n\tBeg      int       // start of data in A[Use]\n\treadable int       // number of bytes available to read in A[Use]\n\ttex      sync.Mutex\n}\n\n// Readable() returns the number of bytes available for reading.\nfunc (b *AtomicFixedSizeRingBuf) Readable() int {\n\tb.tex.Lock()\n\tdefer b.tex.Unlock()\n\treturn b.readable\n}\n\n// ContigLen gets the length of the largest read that we can provide to a contiguous slice\n// without an extra linearizing copy of all bytes internally.\nfunc (b *AtomicFixedSizeRingBuf) ContigLen() int {\n\tb.tex.Lock()\n\tdefer b.tex.Unlock()\n\n\textent := b.Beg + b.readable\n\tfirstContigLen := intMin2(extent, b.N) - b.Beg\n\treturn firstContigLen\n}\n\n// constructor. NewAtomicFixedSizeRingBuf will allocate internally\n// two buffers of size maxViewInBytes.\nfunc NewAtomicFixedSizeRingBuf(maxViewInBytes int) *AtomicFixedSizeRingBuf {\n\tn := maxViewInBytes\n\tr := &AtomicFixedSizeRingBuf{\n\t\tUse: 0, // 0 or 1, whichever is actually in use at the moment.\n\t\t// If we are asked for Bytes() and we wrap, linearize into the other.\n\n\t\tN:        n,\n\t\tBeg:      0,\n\t\treadable: 0,\n\t}\n\tr.A[0] = make([]byte, n, n)\n\tr.A[1] = make([]byte, n, n)\n\n\treturn r\n}\n\n// Bytes() returns a slice of the contents of the unread portion of the buffer.\n//\n// To avoid copying, see the companion BytesTwo() call.\n//\n// Unlike the standard library Bytes() method (on bytes.Buffer for example),\n// the result of the AtomicFixedSizeRingBuf::Bytes(true) is a completely new\n// returned slice, so modifying that slice will have no impact on the contents\n// of the internal ring.\n//\n// Bytes(false) acts like the standard library bytes.Buffer::Bytes() call,\n// in that it returns a slice which is backed by the buffer itself (so\n// no copy is involved).\n//\n// The largest slice Bytes ever returns is bounded above by the maxViewInBytes\n// value used when calling NewAtomicFixedSizeRingBuf().\n//\n// Possible side-effect: may modify b.Use, the buffer in use.\n//\nfunc (b *AtomicFixedSizeRingBuf) Bytes(makeCopy bool) []byte {\n\tb.tex.Lock()\n\tdefer b.tex.Unlock()\n\n\textent := b.Beg + b.readable\n\tif extent <= b.N {\n\t\t// we fit contiguously in this buffer without wrapping to the other\n\t\treturn b.A[b.Use][b.Beg:(b.Beg + b.readable)]\n\t}\n\n\t// wrap into the other buffer\n\tsrc := b.Use\n\tdest := 1 - b.Use\n\n\tn := copy(b.A[dest], b.A[src][b.Beg:])\n\tn += copy(b.A[dest][n:], b.A[src][0:(extent%b.N)])\n\n\tb.Use = dest\n\tb.Beg = 0\n\n\tif makeCopy {\n\t\tret := make([]byte, n)\n\t\tcopy(ret, b.A[b.Use][:n])\n\t\treturn ret\n\t}\n\treturn b.A[b.Use][:n]\n}\n\n// TwoBuffers: the return value of BytesTwo(). TwoBuffers\n// holds two slices to the contents of the readable\n// area of the internal buffer. The slices contents are logically\n// ordered First then Second, but the Second will actually\n// be physically before the First. Either or both of\n// First and Second may be empty slices.\ntype TwoBuffers struct {\n\tFirst  []byte // the first part of the contents\n\tSecond []byte // the second part of the contents\n}\n\n// BytesTwo returns all readable bytes, but in two separate slices,\n// to avoid copying. The two slices are from the same buffer, but\n// are not contiguous. Either or both may be empty slices.\nfunc (b *AtomicFixedSizeRingBuf) BytesTwo() TwoBuffers {\n\tb.tex.Lock()\n\tdefer b.tex.Unlock()\n\treturn b.unatomic_BytesTwo()\n}\n\nfunc (b *AtomicFixedSizeRingBuf) unatomic_BytesTwo() TwoBuffers {\n\textent := b.Beg + b.readable\n\tif extent <= b.N {\n\t\t// we fit contiguously in this buffer without wrapping to the other.\n\t\t// Let second stay an empty slice.\n\t\treturn TwoBuffers{First: b.A[b.Use][b.Beg:(b.Beg + b.readable)], Second: []byte{}}\n\t}\n\n\treturn TwoBuffers{First: b.A[b.Use][b.Beg:(b.Beg + b.readable)], Second: b.A[b.Use][0:(extent % b.N)]}\n}\n\n// Purpose of BytesTwo() and AdvanceBytesTwo(): avoid extra copying of data.\n//\n// AdvanceBytesTwo() takes a TwoBuffers as input, this must have been\n// from a previous call to BytesTwo(); no intervening calls to Bytes()\n// or Adopt() are allowed (or any other future routine or client data\n// access that changes the internal data location or contents) can have\n// been made.\n//\n// After sanity checks, AdvanceBytesTwo() advances the internal buffer, effectively\n// calling Advance( len(tb.First) + len(tb.Second)).\n//\n// If intervening-calls that changed the buffers (other than appending\n// data to the buffer) are detected, we will panic as a safety/sanity/\n// aid-to-debugging measure.\n//\nfunc (b *AtomicFixedSizeRingBuf) AdvanceBytesTwo(tb TwoBuffers) {\n\tb.tex.Lock()\n\tdefer b.tex.Unlock()\n\n\ttblen := len(tb.First) + len(tb.Second)\n\n\tif tblen == 0 {\n\t\treturn // nothing to do\n\t}\n\n\t// sanity check: insure we have re-located in the meantime\n\tif tblen > b.readable {\n\t\tpanic(fmt.Sprintf(\"tblen was %d, and this was greater than b.readerable = %d. Usage error detected and data loss may have occurred (available data appears to have shrunken out from under us!).\", tblen, b.readable))\n\t}\n\n\ttbnow := b.unatomic_BytesTwo()\n\n\tif len(tb.First) > 0 {\n\t\tif tb.First[0] != tbnow.First[0] {\n\t\t\tpanic(fmt.Sprintf(\"slice contents of First have changed out from under us!: '%s' vs '%s'\", string(tb.First), string(tbnow.First)))\n\t\t}\n\t}\n\tif len(tb.Second) > 0 {\n\t\tif len(tb.First) > len(tbnow.First) {\n\t\t\tpanic(fmt.Sprintf(\"slice contents of Second have changed out from under us! tbnow.First length(%d) is less than tb.First(%d.\", len(tbnow.First), len(tb.First)))\n\t\t}\n\t\tif len(tbnow.Second) == 0 {\n\t\t\tpanic(fmt.Sprintf(\"slice contents of Second have changed out from under us! tbnow.Second is empty, but tb.Second was not\"))\n\t\t}\n\t\tif tb.Second[0] != tbnow.Second[0] {\n\t\t\tpanic(fmt.Sprintf(\"slice contents of Second have changed out from under us!: '%s' vs '%s'\", string(tb.Second), string(tbnow.Second)))\n\t\t}\n\t}\n\n\tb.unatomic_advance(tblen)\n}\n\n// Read():\n//\n// From bytes.Buffer.Read(): Read reads the next len(p) bytes\n// from the buffer or until the buffer is drained. The return\n// value n is the number of bytes read. If the buffer has no data\n// to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.\n//\n//  from the description of the Reader interface,\n//     http://golang.org/pkg/io/#Reader\n//\n/*\nReader is the interface that wraps the basic Read method.\n\nRead reads up to len(p) bytes into p. It returns the number\nof bytes read (0 <= n <= len(p)) and any error encountered.\nEven if Read returns n < len(p), it may use all of p as scratch\nspace during the call. If some data is available but not\nlen(p) bytes, Read conventionally returns what is available\ninstead of waiting for more.\n\nWhen Read encounters an error or end-of-file condition after\nsuccessfully reading n > 0 bytes, it returns the number of bytes\nread. It may return the (non-nil) error from the same call or\nreturn the error (and n == 0) from a subsequent call. An instance\nof this general case is that a Reader returning a non-zero number\nof bytes at the end of the input stream may return\neither err == EOF or err == nil. The next Read should\nreturn 0, EOF regardless.\n\nCallers should always process the n > 0 bytes returned before\nconsidering the error err. Doing so correctly handles I/O errors\nthat happen after reading some bytes and also both of the\nallowed EOF behaviors.\n\nImplementations of Read are discouraged from returning a zero\nbyte count with a nil error, and callers should treat that\nsituation as a no-op.\n*/\n//\nfunc (b *AtomicFixedSizeRingBuf) Read(p []byte) (n int, err error) {\n\treturn b.ReadAndMaybeAdvance(p, true)\n}\n\n// ReadWithoutAdvance(): if you want to Read the data and leave\n// it in the buffer, so as to peek ahead for example.\nfunc (b *AtomicFixedSizeRingBuf) ReadWithoutAdvance(p []byte) (n int, err error) {\n\treturn b.ReadAndMaybeAdvance(p, false)\n}\n\nfunc (b *AtomicFixedSizeRingBuf) ReadAndMaybeAdvance(p []byte, doAdvance bool) (n int, err error) {\n\tb.tex.Lock()\n\tdefer b.tex.Unlock()\n\n\tif len(p) == 0 {\n\t\treturn 0, nil\n\t}\n\tif b.readable == 0 {\n\t\treturn 0, io.EOF\n\t}\n\textent := b.Beg + b.readable\n\tif extent <= b.N {\n\t\tn += copy(p, b.A[b.Use][b.Beg:extent])\n\t} else {\n\t\tn += copy(p, b.A[b.Use][b.Beg:b.N])\n\t\tif n < len(p) {\n\t\t\tn += copy(p[n:], b.A[b.Use][0:(extent%b.N)])\n\t\t}\n\t}\n\tif doAdvance {\n\t\tb.unatomic_advance(n)\n\t}\n\treturn\n}\n\n//\n// Write writes len(p) bytes from p to the underlying data stream.\n// It returns the number of bytes written from p (0 <= n <= len(p))\n// and any error encountered that caused the write to stop early.\n// Write must return a non-nil error if it returns n < len(p).\n//\n// Write doesn't modify b.User, so once a []byte is pinned with\n// a call to Bytes(), it should remain valid even with additional\n// calls to Write() that come after the Bytes() call.\n//\nfunc (b *AtomicFixedSizeRingBuf) Write(p []byte) (n int, err error) {\n\tb.tex.Lock()\n\tdefer b.tex.Unlock()\n\n\tfor {\n\t\tif len(p) == 0 {\n\t\t\t// nothing (left) to copy in; notice we shorten our\n\t\t\t// local copy p (below) as we read from it.\n\t\t\treturn\n\t\t}\n\n\t\twriteCapacity := b.N - b.readable\n\t\tif writeCapacity <= 0 {\n\t\t\t// we are all full up already.\n\t\t\treturn n, io.ErrShortWrite\n\t\t}\n\t\tif len(p) > writeCapacity {\n\t\t\terr = io.ErrShortWrite\n\t\t\t// leave err set and\n\t\t\t// keep going, write what we can.\n\t\t}\n\n\t\twriteStart := (b.Beg + b.readable) % b.N\n\n\t\tupperLim := intMin2(writeStart+writeCapacity, b.N)\n\n\t\tk := copy(b.A[b.Use][writeStart:upperLim], p)\n\n\t\tn += k\n\t\tb.readable += k\n\t\tp = p[k:]\n\n\t\t// we can fill from b.A[b.Use][0:something] from\n\t\t// p's remainder, so loop\n\t}\n}\n\n// WriteTo and ReadFrom avoid intermediate allocation and copies.\n\n// WriteTo avoids intermediate allocation and copies.\n// WriteTo writes data to w until there's no more data to write\n// or when an error occurs. The return value n is the number of\n// bytes written. Any error encountered during the write is also returned.\nfunc (b *AtomicFixedSizeRingBuf) WriteTo(w io.Writer) (n int64, err error) {\n\tb.tex.Lock()\n\tdefer b.tex.Unlock()\n\n\tif b.readable == 0 {\n\t\treturn 0, io.EOF\n\t}\n\n\textent := b.Beg + b.readable\n\tfirstWriteLen := intMin2(extent, b.N) - b.Beg\n\tsecondWriteLen := b.readable - firstWriteLen\n\tif firstWriteLen > 0 {\n\t\tm, e := w.Write(b.A[b.Use][b.Beg:(b.Beg + firstWriteLen)])\n\t\tn += int64(m)\n\t\tb.unatomic_advance(m)\n\n\t\tif e != nil {\n\t\t\treturn n, e\n\t\t}\n\t\t// all bytes should have been written, by definition of\n\t\t// Write method in io.Writer\n\t\tif m != firstWriteLen {\n\t\t\treturn n, io.ErrShortWrite\n\t\t}\n\t}\n\tif secondWriteLen > 0 {\n\t\tm, e := w.Write(b.A[b.Use][0:secondWriteLen])\n\t\tn += int64(m)\n\t\tb.unatomic_advance(m)\n\n\t\tif e != nil {\n\t\t\treturn n, e\n\t\t}\n\t\t// all bytes should have been written, by definition of\n\t\t// Write method in io.Writer\n\t\tif m != secondWriteLen {\n\t\t\treturn n, io.ErrShortWrite\n\t\t}\n\t}\n\n\treturn n, nil\n}\n\n// ReadFrom avoids intermediate allocation and copies.\n// ReadFrom() reads data from r until EOF or error. The return value n\n// is the number of bytes read. Any error except io.EOF encountered\n// during the read is also returned.\nfunc (b *AtomicFixedSizeRingBuf) ReadFrom(r io.Reader) (n int64, err error) {\n\tb.tex.Lock()\n\tdefer b.tex.Unlock()\n\n\tfor {\n\t\twriteCapacity := b.N - b.readable\n\t\tif writeCapacity <= 0 {\n\t\t\t// we are all full\n\t\t\treturn n, nil\n\t\t}\n\t\twriteStart := (b.Beg + b.readable) % b.N\n\t\tupperLim := intMin2(writeStart+writeCapacity, b.N)\n\n\t\tm, e := r.Read(b.A[b.Use][writeStart:upperLim])\n\t\tn += int64(m)\n\t\tb.readable += m\n\t\tif e == io.EOF {\n\t\t\treturn n, nil\n\t\t}\n\t\tif e != nil {\n\t\t\treturn n, e\n\t\t}\n\t}\n}\n\n// Reset quickly forgets any data stored in the ring buffer. The\n// data is still there, but the ring buffer will ignore it and\n// overwrite those buffers as new data comes in.\nfunc (b *AtomicFixedSizeRingBuf) Reset() {\n\tb.tex.Lock()\n\tdefer b.tex.Unlock()\n\n\tb.Beg = 0\n\tb.readable = 0\n\tb.Use = 0\n}\n\n// Advance(): non-standard, but better than Next(),\n// because we don't have to unwrap our buffer and pay the cpu time\n// for the copy that unwrapping may need.\n// Useful in conjuction/after ReadWithoutAdvance() above.\nfunc (b *AtomicFixedSizeRingBuf) Advance(n int) {\n\tb.tex.Lock()\n\tdefer b.tex.Unlock()\n\n\tb.unatomic_advance(n)\n}\n\n// unatomic_advance(): private implementation of Advance() without\n// the locks. See Advance() above for description.\n// Necessary so that other methods that already hold\n// locks can advance, and there are no recursive mutexes\n// in Go.\nfunc (b *AtomicFixedSizeRingBuf) unatomic_advance(n int) {\n\tif n <= 0 {\n\t\treturn\n\t}\n\tif n > b.readable {\n\t\tn = b.readable\n\t}\n\tb.readable -= n\n\tb.Beg = (b.Beg + n) % b.N\n}\n\n// Adopt(): non-standard.\n//\n// For efficiency's sake, (possibly) take ownership of\n// already allocated slice offered in me.\n//\n// If me is large we will adopt it, and we will potentially then\n// write to the me buffer.\n// If we already have a bigger buffer, copy me into the existing\n// buffer instead.\n//\n// Side-effect: may change b.Use, among other internal state changes.\n//\nfunc (b *AtomicFixedSizeRingBuf) Adopt(me []byte) {\n\tb.tex.Lock()\n\tdefer b.tex.Unlock()\n\n\tn := len(me)\n\tif n > b.N {\n\t\tb.A[0] = me\n\t\tb.A[1] = make([]byte, n, n)\n\t\tb.N = n\n\t\tb.Use = 0\n\t\tb.Beg = 0\n\t\tb.readable = n\n\t} else {\n\t\t// we already have a larger buffer, reuse it.\n\t\tcopy(b.A[0], me)\n\t\tb.Use = 0\n\t\tb.Beg = 0\n\t\tb.readable = n\n\t}\n}\n\n// keep the atomic_rbuf.go standalone and usable without\n// the rbuf.go file, by simply duplicating intMin from rbuf.go\n//\nfunc intMin2(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}\n"
  },
  {
    "path": "atomic_rbuf_test.go",
    "content": "package rbuf\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"testing\"\n\n\tcv \"github.com/glycerine/goconvey/convey\"\n)\n\n// new tests just for atomic version\n\n// same set of tests for non-atomic rbuf:\nfunc TestAtomicRingBufReadWrite(t *testing.T) {\n\tb := NewAtomicFixedSizeRingBuf(5)\n\n\tdata := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n\n\tcv.Convey(\"Given a AtomicFixedSizeRingBuf of size 5\", t, func() {\n\t\tcv.Convey(\"Write(), Bytes(), and Read() should put and get bytes\", func() {\n\t\t\tn, err := b.Write(data[0:5])\n\t\t\tcv.So(n, cv.ShouldEqual, 5)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(b.readable, cv.ShouldEqual, 5)\n\t\t\tif n != 5 {\n\t\t\t\tfmt.Printf(\"should have been able to write 5 bytes.\\n\")\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tcv.So(b.Bytes(false), cv.ShouldResemble, data[0:5])\n\n\t\t\tsink := make([]byte, 3)\n\t\t\tn, err = b.Read(sink)\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(b.Bytes(false), cv.ShouldResemble, data[3:5])\n\t\t\tcv.So(sink, cv.ShouldResemble, data[0:3])\n\t\t})\n\n\t\tcv.Convey(\"Write() more than 5 should give back ErrShortWrite\", func() {\n\t\t\tb.Reset()\n\t\t\tcv.So(b.readable, cv.ShouldEqual, 0)\n\t\t\tn, err := b.Write(data[0:10])\n\t\t\tcv.So(n, cv.ShouldEqual, 5)\n\t\t\tcv.So(err, cv.ShouldEqual, io.ErrShortWrite)\n\t\t\tcv.So(b.readable, cv.ShouldEqual, 5)\n\t\t\tif n != 5 {\n\t\t\t\tfmt.Printf(\"should have been able to write 5 bytes.\\n\")\n\t\t\t}\n\t\t\tcv.So(b.Bytes(false), cv.ShouldResemble, data[0:5])\n\n\t\t\tsink := make([]byte, 3)\n\t\t\tn, err = b.Read(sink)\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(b.Bytes(false), cv.ShouldResemble, data[3:5])\n\t\t\tcv.So(sink, cv.ShouldResemble, data[0:3])\n\t\t})\n\n\t\tcv.Convey(\"we should be able to wrap data and then get it back in Bytes(false)\", func() {\n\t\t\tb.Reset()\n\n\t\t\tn, err := b.Write(data[0:3])\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\n\t\t\tsink := make([]byte, 3)\n\t\t\tn, err = b.Read(sink) // put b.beg at 3\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(b.readable, cv.ShouldEqual, 0)\n\n\t\t\tn, err = b.Write(data[3:8]) // wrap 3 bytes around to the front\n\t\t\tcv.So(n, cv.ShouldEqual, 5)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\n\t\t\tby := b.Bytes(false)\n\t\t\tcv.So(by, cv.ShouldResemble, data[3:8]) // but still get them back from the ping-pong buffering\n\n\t\t})\n\n\t\tcv.Convey(\"AtomicFixedSizeRingBuf::WriteTo() should work with wrapped data\", func() {\n\t\t\tb.Reset()\n\n\t\t\tn, err := b.Write(data[0:3])\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\n\t\t\tsink := make([]byte, 3)\n\t\t\tn, err = b.Read(sink) // put b.beg at 3\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(b.readable, cv.ShouldEqual, 0)\n\n\t\t\tn, err = b.Write(data[3:8]) // wrap 3 bytes around to the front\n\n\t\t\tvar bb bytes.Buffer\n\t\t\tm, err := b.WriteTo(&bb)\n\n\t\t\tcv.So(m, cv.ShouldEqual, 5)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\n\t\t\tby := bb.Bytes()\n\t\t\tcv.So(by, cv.ShouldResemble, data[3:8]) // but still get them back from the ping-pong buffering\n\n\t\t})\n\n\t\tcv.Convey(\"AtomicFixedSizeRingBuf::ReadFrom() should work with wrapped data\", func() {\n\t\t\tb.Reset()\n\t\t\tvar bb bytes.Buffer\n\t\t\tn, err := b.ReadFrom(&bb)\n\t\t\tcv.So(n, cv.ShouldEqual, 0)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\n\t\t\t// write 4, then read 4 bytes\n\t\t\tm, err := b.Write(data[0:4])\n\t\t\tcv.So(m, cv.ShouldEqual, 4)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\n\t\t\tsink := make([]byte, 4)\n\t\t\tk, err := b.Read(sink) // put b.beg at 4\n\t\t\tcv.So(k, cv.ShouldEqual, 4)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(b.readable, cv.ShouldEqual, 0)\n\t\t\tcv.So(b.Beg, cv.ShouldEqual, 4)\n\n\t\t\tbbread := bytes.NewBuffer(data[4:9])\n\t\t\tn, err = b.ReadFrom(bbread) // wrap 4 bytes around to the front, 5 bytes total.\n\n\t\t\tby := b.Bytes(false)\n\t\t\tcv.So(by, cv.ShouldResemble, data[4:9]) // but still get them back continguous from the ping-pong buffering\n\t\t})\n\n\t})\n\n}\n"
  },
  {
    "path": "fbuf.go",
    "content": "package rbuf\n\n// copyright (c) 2016, Jason E. Aten\n// license: MIT\n\nimport (\n\t\"io\"\n)\n\n// Float64RingBuf:\n//\n//  a fixed-size circular ring buffer of float64\n//\ntype Float64RingBuf struct {\n\tA        []float64\n\tN        int // MaxView, the total size of A, whether or not in use.\n\tBeg      int // start of in-use data in A\n\tReadable int // number of float64 available in A (in use)\n}\n\n// constructor. NewFloat64RingBuf will allocate internally\n// a slice of maxViewItems float64.\nfunc NewFloat64RingBuf(maxViewItems int) *Float64RingBuf {\n\tn := maxViewItems\n\tr := &Float64RingBuf{\n\t\tN:        n,\n\t\tBeg:      0,\n\t\tReadable: 0,\n\t}\n\tr.A = make([]float64, n, n)\n\n\treturn r\n}\n\n// TwoContig returns all readable float64, but in two separate slices,\n// to avoid copying. The two slices are from the same buffer, but\n// are not contiguous. Either or both may be empty slices.\nfunc (b *Float64RingBuf) TwoContig(makeCopy bool) (first []float64, second []float64) {\n\n\textent := b.Beg + b.Readable\n\tif extent <= b.N {\n\t\t// we fit contiguously in this buffer without wrapping to the other.\n\t\t// Let second stay an empty slice.\n\t\treturn b.A[b.Beg:(b.Beg + b.Readable)], second\n\t}\n\n\treturn b.A[b.Beg:b.N], b.A[0:(extent % b.N)]\n}\n\n// Earliest returns the earliest written value v. ok will be\n// true unless the ring is empty, in which case ok will be false,\n// and v will be zero.\nfunc (b *Float64RingBuf) Earliest() (v float64, ok bool) {\n\tif b.Readable == 0 {\n\t\treturn\n\t}\n\n\treturn b.A[b.Beg], true\n}\n\n// Values returns all readable float64 in a single buffer. Calling this function\n// might allocate a new buffer to store the elements contiguously.\nfunc (b *Float64RingBuf) Values() []float64 {\n\tfirst, second := b.TwoContig(false)\n\n\tif len(first) == 0 {\n\t\treturn second\n\t}\n\n\tif len(second) == 0 {\n\t\treturn first\n\t}\n\n\tout := make([]float64, len(first) + len(second))\n\n\tcopy(out, first)\n\tcopy(out[len(first):], second)\n\n\treturn out\n}\n\n// ReadFloat64():\n//\n// from bytes.Buffer.Read(): Read reads the next len(p) float64\n// pointers from the buffer or until the buffer is drained. The return\n// value n is the number of bytes read. If the buffer has no data\n// to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.\nfunc (b *Float64RingBuf) ReadFloat64(p []float64) (n int, err error) {\n\treturn b.readAndMaybeAdvance(p, true)\n}\n\n// ReadWithoutAdvance(): if you want to Read the data and leave\n// it in the buffer, so as to peek ahead for example.\nfunc (b *Float64RingBuf) ReadWithoutAdvance(p []float64) (n int, err error) {\n\treturn b.readAndMaybeAdvance(p, false)\n}\n\nfunc (b *Float64RingBuf) readAndMaybeAdvance(p []float64, doAdvance bool) (n int, err error) {\n\tif len(p) == 0 {\n\t\treturn 0, nil\n\t}\n\tif b.Readable == 0 {\n\t\treturn 0, io.EOF\n\t}\n\textent := b.Beg + b.Readable\n\tif extent <= b.N {\n\t\tn += copy(p, b.A[b.Beg:extent])\n\t} else {\n\t\tn += copy(p, b.A[b.Beg:b.N])\n\t\tif n < len(p) {\n\t\t\tn += copy(p[n:], b.A[0:(extent%b.N)])\n\t\t}\n\t}\n\tif doAdvance {\n\t\tb.Advance(n)\n\t}\n\treturn\n}\n\n//\n// WriteAndMaybeOverwriteOldestData always consumes the full\n// buffer p, even if that means blowing away the oldest\n// unread bytes in the ring to make room. In reality, only the last\n// min(len(p),b.N) bytes of p will end up being written to the ring.\n//\n// This allows the ring to act as a record of the most recent\n// b.N bytes of data -- a kind of temporal LRU cache, so the\n// speak. The linux kernel's dmesg ring buffer is similar.\n//\nfunc (b *Float64RingBuf) WriteAndMaybeOverwriteOldestData(p []float64) (n int, err error) {\n\twriteCapacity := b.N - b.Readable\n\tif len(p) > writeCapacity {\n\t\tb.Advance(len(p) - writeCapacity)\n\t}\n\tstartPos := 0\n\tif len(p) > b.N {\n\t\tstartPos = len(p) - b.N\n\t}\n\tn, err = b.Write(p[startPos:])\n\tif err != nil {\n\t\treturn n, err\n\t}\n\treturn len(p), nil\n}\n\n//\n// Write writes len(p) float64 values from p to\n// the underlying data stream.\n// It returns the number of bytes written from p (0 <= n <= len(p))\n// and any error encountered that caused the write to stop early.\n// Write must return a non-nil error if it returns n < len(p).\n//\nfunc (b *Float64RingBuf) Write(p []float64) (n int, err error) {\n\tfor {\n\t\tif len(p) == 0 {\n\t\t\t// nothing (left) to copy in; notice we shorten our\n\t\t\t// local copy p (below) as we read from it.\n\t\t\treturn\n\t\t}\n\n\t\twriteCapacity := b.N - b.Readable\n\t\tif writeCapacity <= 0 {\n\t\t\t// we are all full up already.\n\t\t\treturn n, io.ErrShortWrite\n\t\t}\n\t\tif len(p) > writeCapacity {\n\t\t\terr = io.ErrShortWrite\n\t\t\t// leave err set and\n\t\t\t// keep going, write what we can.\n\t\t}\n\n\t\twriteStart := (b.Beg + b.Readable) % b.N\n\n\t\tupperLim := intMin(writeStart+writeCapacity, b.N)\n\n\t\tk := copy(b.A[writeStart:upperLim], p)\n\n\t\tn += k\n\t\tb.Readable += k\n\t\tp = p[k:]\n\n\t\t// we can fill from b.A[0:something] from\n\t\t// p's remainder, so loop\n\t}\n}\n\n// Reset quickly forgets any data stored in the ring buffer. The\n// data is still there, but the ring buffer will ignore it and\n// overwrite those buffers as new data comes in.\nfunc (b *Float64RingBuf) Reset() {\n\tb.Beg = 0\n\tb.Readable = 0\n}\n\n// Advance(): non-standard, but better than Next(),\n// because we don't have to unwrap our buffer and pay the cpu time\n// for the copy that unwrapping may need.\n// Useful in conjuction/after ReadWithoutAdvance() above.\nfunc (b *Float64RingBuf) Advance(n int) {\n\tif n <= 0 {\n\t\treturn\n\t}\n\tif n > b.Readable {\n\t\tn = b.Readable\n\t}\n\tb.Readable -= n\n\tb.Beg = (b.Beg + n) % b.N\n}\n\n// Adopt(): non-standard.\n//\n// For efficiency's sake, (possibly) take ownership of\n// already allocated slice offered in me.\n//\n// If me is large we will adopt it, and we will potentially then\n// write to the me buffer.\n// If we already have a bigger buffer, copy me into the existing\n// buffer instead.\nfunc (b *Float64RingBuf) Adopt(me []float64) {\n\tn := len(me)\n\tif n > b.N {\n\t\tb.A = me\n\t\tb.N = n\n\t\tb.Beg = 0\n\t\tb.Readable = n\n\t} else {\n\t\t// we already have a larger buffer, reuse it.\n\t\tcopy(b.A, me)\n\t\tb.Beg = 0\n\t\tb.Readable = n\n\t}\n}\n"
  },
  {
    "path": "fbuf_test.go",
    "content": "package rbuf\n\nimport (\n\t\"io\"\n\t\"testing\"\n\n\tcv \"github.com/glycerine/goconvey/convey\"\n)\n\nfunc TestFloatBufReadWrite(t *testing.T) {\n\tb := NewFloat64RingBuf(5)\n\n\tdata := []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n\n\tcv.Convey(\"Given a Float64RingBuf of size 5\", t, func() {\n\t\tcv.Convey(\"Write() and ReadFloat64() should put and get floats\", func() {\n\t\t\tb.Reset()\n\n\t\t\tn, err := b.Write(data[:5])\n\t\t\tcv.So(n, cv.ShouldEqual, 5)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(b.Readable, cv.ShouldEqual, 5)\n\t\t\tcv.So(b.Values(), cv.ShouldResemble, data[:5])\n\n\t\t\tsink := make([]float64, 3)\n\t\t\tn, err = b.ReadFloat64(sink)\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(b.Values(), cv.ShouldResemble, data[3:5])\n\t\t\tcv.So(sink, cv.ShouldResemble, data[:3])\n\t\t})\n\n\t\tcv.Convey(\"Write() more than 5 items should give back ErrShortWrite\", func() {\n\t\t\tb.Reset()\n\n\t\t\tcv.So(b.Readable, cv.ShouldEqual, 0)\n\t\t\tn, err := b.Write(data[:10])\n\t\t\tcv.So(n, cv.ShouldEqual, 5)\n\t\t\tcv.So(err, cv.ShouldEqual, io.ErrShortWrite)\n\t\t\tcv.So(b.Readable, cv.ShouldEqual, 5)\n\t\t\tcv.So(b.Values(), cv.ShouldResemble, data[:5])\n\n\t\t\tsink := make([]float64, 3)\n\t\t\tn, err = b.ReadFloat64(sink)\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(b.Values(), cv.ShouldResemble, data[3:5])\n\t\t\tcv.So(sink, cv.ShouldResemble, data[:3])\n\t\t})\n\n\t\tcv.Convey(\"WriteAndMaybeOverwriteOldestData() should auto advance\", func() {\n\t\t\tb.Reset()\n\n\t\t\tn, err := b.WriteAndMaybeOverwriteOldestData(data[:5])\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(n, cv.ShouldEqual, 5)\n\t\t\tcv.So(b.Values(), cv.ShouldResemble, data[:5])\n\n\t\t\tn, err = b.WriteAndMaybeOverwriteOldestData(data[5:7])\n\t\t\tcv.So(n, cv.ShouldEqual, 2)\n\t\t\tcv.So(b.Values(), cv.ShouldResemble, data[2:7])\n\n\t\t\tn, err = b.WriteAndMaybeOverwriteOldestData(data[0:9])\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(n, cv.ShouldEqual, 9)\n\t\t\tcv.So(b.Values(), cv.ShouldResemble, data[4:9])\n\t\t})\n\t})\n}\n"
  },
  {
    "path": "pbuf.go",
    "content": "package rbuf\n\n// copyright (c) 2016, Jason E. Aten\n// license: MIT\n\nimport \"io\"\n\n// PointerRingBuf:\n//\n//  a fixed-size circular ring buffer of interface{}\n//\ntype PointerRingBuf struct {\n\tA        []interface{}\n\tN        int // MaxView, the total size of A, whether or not in use.\n\tBeg      int // start of in-use data in A\n\tReadable int // number of pointers available in A (in use)\n}\n\n// constructor. NewPointerRingBuf will allocate internally\n// a slice of size sliceN\nfunc NewPointerRingBuf(sliceN int) *PointerRingBuf {\n\tn := sliceN\n\tr := &PointerRingBuf{\n\t\tN:        n,\n\t\tBeg:      0,\n\t\tReadable: 0,\n\t}\n\tr.A = make([]interface{}, n, n)\n\n\treturn r\n}\n\n// TwoContig returns all readable pointers, but in two separate slices,\n// to avoid copying. The two slices are from the same buffer, but\n// are not contiguous. Either or both may be empty slices.\nfunc (b *PointerRingBuf) TwoContig() (first []interface{}, second []interface{}) {\n\n\textent := b.Beg + b.Readable\n\tif extent <= b.N {\n\t\t// we fit contiguously in this buffer without wrapping to the other.\n\t\t// Let second stay an empty slice.\n\t\treturn b.A[b.Beg:(b.Beg + b.Readable)], second\n\t}\n\n\treturn b.A[b.Beg:b.N], b.A[0:(extent % b.N)]\n}\n\n// ReadPtrs():\n//\n// from bytes.Buffer.Read(): Read reads the next len(p) interface{}\n// pointers from the buffer or until the buffer is drained. The return\n// value n is the number of bytes read. If the buffer has no data\n// to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.\nfunc (b *PointerRingBuf) ReadPtrs(p []interface{}) (n int, err error) {\n\treturn b.readAndMaybeAdvance(p, true)\n}\n\n// ReadWithoutAdvance(): if you want to Read the data and leave\n// it in the buffer, so as to peek ahead for example.\nfunc (b *PointerRingBuf) ReadWithoutAdvance(p []interface{}) (n int, err error) {\n\treturn b.readAndMaybeAdvance(p, false)\n}\n\nfunc (b *PointerRingBuf) readAndMaybeAdvance(p []interface{}, doAdvance bool) (n int, err error) {\n\tif len(p) == 0 {\n\t\treturn 0, nil\n\t}\n\tif b.Readable == 0 {\n\t\treturn 0, io.EOF\n\t}\n\textent := b.Beg + b.Readable\n\tif extent <= b.N {\n\t\tn += copy(p, b.A[b.Beg:extent])\n\t} else {\n\t\tn += copy(p, b.A[b.Beg:b.N])\n\t\tif n < len(p) {\n\t\t\tn += copy(p[n:], b.A[0:(extent%b.N)])\n\t\t}\n\t}\n\tif doAdvance {\n\t\tb.Advance(n)\n\t}\n\treturn\n}\n\n//\n// WritePtrs writes len(p) interface{} values from p to\n// the underlying data stream.\n// It returns the number of bytes written from p (0 <= n <= len(p))\n// and any error encountered that caused the write to stop early.\n// Write must return a non-nil error if it returns n < len(p).\n//\nfunc (b *PointerRingBuf) WritePtrs(p []interface{}) (n int, err error) {\n\tfor {\n\t\tif len(p) == 0 {\n\t\t\t// nothing (left) to copy in; notice we shorten our\n\t\t\t// local copy p (below) as we read from it.\n\t\t\treturn\n\t\t}\n\n\t\twriteCapacity := b.N - b.Readable\n\t\tif writeCapacity <= 0 {\n\t\t\t// we are all full up already.\n\t\t\treturn n, io.ErrShortWrite\n\t\t}\n\t\tif len(p) > writeCapacity {\n\t\t\terr = io.ErrShortWrite\n\t\t\t// leave err set and\n\t\t\t// keep going, write what we can.\n\t\t}\n\n\t\twriteStart := (b.Beg + b.Readable) % b.N\n\n\t\tupperLim := intMin(writeStart+writeCapacity, b.N)\n\n\t\tk := copy(b.A[writeStart:upperLim], p)\n\n\t\tn += k\n\t\tb.Readable += k\n\t\tp = p[k:]\n\n\t\t// we can fill from b.A[0:something] from\n\t\t// p's remainder, so loop\n\t}\n}\n\n// Reset quickly forgets any data stored in the ring buffer. The\n// data is still there, but the ring buffer will ignore it and\n// overwrite those buffers as new data comes in.\nfunc (b *PointerRingBuf) Reset() {\n\tb.Beg = 0\n\tb.Readable = 0\n}\n\n// Advance(): non-standard, but better than Next(),\n// because we don't have to unwrap our buffer and pay the cpu time\n// for the copy that unwrapping may need.\n// Useful in conjuction/after ReadWithoutAdvance() above.\nfunc (b *PointerRingBuf) Advance(n int) {\n\tif n <= 0 {\n\t\treturn\n\t}\n\tif n > b.Readable {\n\t\tn = b.Readable\n\t}\n\tb.Readable -= n\n\tb.Beg = (b.Beg + n) % b.N\n}\n\n// Adopt(): non-standard.\n//\n// For efficiency's sake, (possibly) take ownership of\n// already allocated slice offered in me.\n//\n// If me is large we will adopt it, and we will potentially then\n// write to the me buffer.\n// If we already have a bigger buffer, copy me into the existing\n// buffer instead.\nfunc (b *PointerRingBuf) Adopt(me []interface{}) {\n\tn := len(me)\n\tif n > b.N {\n\t\tb.A = me\n\t\tb.N = n\n\t\tb.Beg = 0\n\t\tb.Readable = n\n\t} else {\n\t\t// we already have a larger buffer, reuse it.\n\t\tcopy(b.A, me)\n\t\tb.Beg = 0\n\t\tb.Readable = n\n\t}\n}\n\n// Push writes len(p) pointers from p to the ring.\n// It returns the number of elements written from p (0 <= n <= len(p))\n// and any error encountered that caused the write to stop early.\n// Push must return a non-nil error if it returns n < len(p).\n//\nfunc (b *PointerRingBuf) Push(p []interface{}) (n int, err error) {\n\tfor {\n\t\tif len(p) == 0 {\n\t\t\t// nothing (left) to copy in; notice we shorten our\n\t\t\t// local copy p (below) as we read from it.\n\t\t\treturn\n\t\t}\n\n\t\twriteCapacity := b.N - b.Readable\n\t\tif writeCapacity <= 0 {\n\t\t\t// we are all full up already.\n\t\t\treturn n, io.ErrShortWrite\n\t\t}\n\t\tif len(p) > writeCapacity {\n\t\t\terr = io.ErrShortWrite\n\t\t\t// leave err set and\n\t\t\t// keep going, write what we can.\n\t\t}\n\n\t\twriteStart := (b.Beg + b.Readable) % b.N\n\n\t\tupperLim := intMin(writeStart+writeCapacity, b.N)\n\n\t\tk := copy(b.A[writeStart:upperLim], p)\n\n\t\tn += k\n\t\tb.Readable += k\n\t\tp = p[k:]\n\n\t\t// we can fill from b.A[0:something] from\n\t\t// p's remainder, so loop\n\t}\n}\n\n// PushAndMaybeOverwriteOldestData always consumes the full\n// slice p, even if that means blowing away the oldest\n// unread pointers in the ring to make room. In reality, only the last\n// min(len(p),b.N) bytes of p will end up being written to the ring.\n//\n// This allows the ring to act as a record of the most recent\n// b.N bytes of data -- a kind of temporal LRU cache, so the\n// speak. The linux kernel's dmesg ring buffer is similar.\n//\nfunc (b *PointerRingBuf) PushAndMaybeOverwriteOldestData(p []interface{}) (n int, err error) {\n\twriteCapacity := b.N - b.Readable\n\tif len(p) > writeCapacity {\n\t\tb.Advance(len(p) - writeCapacity)\n\t}\n\tstartPos := 0\n\tif len(p) > b.N {\n\t\tstartPos = len(p) - b.N\n\t}\n\tn, err = b.Push(p[startPos:])\n\tif err != nil {\n\t\treturn n, err\n\t}\n\treturn len(p), nil\n}\n"
  },
  {
    "path": "pbuf_test.go",
    "content": "package rbuf\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\tcv \"github.com/glycerine/goconvey/convey\"\n)\n\nfunc TestPointerReadWrite(t *testing.T) {\n\tb := NewPointerRingBuf(5)\n\n\tdata := []interface{}{}\n\tfor i := 0; i < 10; i++ {\n\t\tdata = append(data, interface{}(i))\n\t}\n\n\tcv.Convey(\"PointerRingBuf::PushAndMaybeOverwriteOldestData() should auto advance\", t, func() {\n\t\tb.Reset()\n\t\tn, err := b.PushAndMaybeOverwriteOldestData(data[:3])\n\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\tcv.So(b.Readable, cv.ShouldEqual, 3)\n\n\t\tn, err = b.PushAndMaybeOverwriteOldestData(data[3:5])\n\t\tcv.So(n, cv.ShouldEqual, 2)\n\t\tcv.So(b.Readable, cv.ShouldEqual, 5)\n\t\tcheck := make([]interface{}, 5)\n\t\tn, err = b.ReadPtrs(check)\n\t\tcv.So(n, cv.ShouldEqual, 5)\n\t\tcv.So(check, cv.ShouldResemble, data[:5])\n\n\t\tn, err = b.PushAndMaybeOverwriteOldestData(data[5:10])\n\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\tcv.So(n, cv.ShouldEqual, 5)\n\n\t\tn, err = b.ReadWithoutAdvance(check)\n\t\tcv.So(n, cv.ShouldEqual, 5)\n\t\tcv.So(check, cv.ShouldResemble, data[5:10])\n\n\t\t// check TwoConfig\n\t\tq, r := b.TwoContig()\n\n\t\t//p(\"len q = %v\", len(q))\n\t\t//p(\"len r = %v\", len(r))\n\n\t\tfound := make([]bool, 10)\n\t\tfor _, iface := range q {\n\t\t\tq0 := iface.(int)\n\t\t\tfound[q0] = true\n\t\t}\n\n\t\tfor _, iface := range r {\n\t\t\tr0 := iface.(int)\n\t\t\tfound[r0] = true\n\t\t}\n\n\t\ttotTrue := 0\n\t\tfor i := range found {\n\t\t\tif found[i] {\n\t\t\t\ttotTrue++\n\t\t\t}\n\t\t}\n\t\tcv.So(totTrue, cv.ShouldEqual, 5)\n\n\t})\n\n}\n\nfunc p(format string, a ...interface{}) {\n\tfmt.Printf(\"\\n\"+format+\"\\n\", a...)\n}\n"
  },
  {
    "path": "rbuf.go",
    "content": "package rbuf\n\n// copyright (c) 2014, Jason E. Aten\n// license: MIT\n\n// Some text from the Golang standard library doc is adapted and\n// reproduced in fragments below to document the expected behaviors\n// of the interface functions Read()/Write()/ReadFrom()/WriteTo() that\n// are implemented here. Those descriptions (see\n// http://golang.org/pkg/io/#Reader for example) are\n// copyright 2010 The Go Authors.\n\nimport \"io\"\n\n// FixedSizeRingBuf:\n//\n//    a fixed-size circular ring buffer. Yes, just what is says.\n//\n//    We keep a pair of ping/pong buffers so that we can linearize\n//    the circular buffer into a contiguous slice if need be.\n//\n// For efficiency, a FixedSizeRingBuf may be vastly preferred to\n// a bytes.Buffer. The ReadWithoutAdvance(), Advance(), and Adopt()\n// methods are all non-standard methods written for speed.\n//\n// For an I/O heavy application, I have replaced bytes.Buffer with\n// FixedSizeRingBuf and seen memory consumption go from 8GB to 25MB.\n// Yes, that is a 300x reduction in memory footprint. Everything ran\n// faster too.\n//\n// Note that Bytes(), while inescapable at times, is expensive: avoid\n// it if possible. Instead it is better to use the FixedSizeRingBuf.Readable\n// member to get the number of bytes available. Bytes() is expensive because\n// it may copy the back and then the front of a wrapped buffer A[Use]\n// into A[1-Use] in order to get a contiguous slice. If possible use ContigLen()\n// first to get the size that can be read without copying, Read() that\n// amount, and then Read() a second time -- to avoid the copy. See\n// BytesTwo() for a method that does this for you.\n//\ntype FixedSizeRingBuf struct {\n\tA        [2][]byte // a pair of ping/pong buffers. Only one is active.\n\tUse      int       // which A buffer is in active use, 0 or 1\n\tN        int       // MaxViewInBytes, the size of A[0] and A[1] in bytes.\n\tBeg      int       // start of data in A[Use]\n\tReadable int       // number of bytes available to read in A[Use]\n}\n\n// ContigLen gets the length of the largest read that we can provide to a contiguous slice\n// without an extra linearizing copy of all bytes internally.\nfunc (b *FixedSizeRingBuf) ContigLen() int {\n\textent := b.Beg + b.Readable\n\tfirstContigLen := intMin(extent, b.N) - b.Beg\n\treturn firstContigLen\n}\n\n// constructor. NewFixedSizeRingBuf will allocate internally\n// two buffers of size maxViewInBytes.\nfunc NewFixedSizeRingBuf(maxViewInBytes int) *FixedSizeRingBuf {\n\tn := maxViewInBytes\n\tr := &FixedSizeRingBuf{\n\t\tUse: 0, // 0 or 1, whichever is actually in use at the moment.\n\t\t// If we are asked for Bytes() and we wrap, linearize into the other.\n\n\t\tN:        n,\n\t\tBeg:      0,\n\t\tReadable: 0,\n\t}\n\tr.A[0] = make([]byte, n, n)\n\tr.A[1] = make([]byte, n, n)\n\n\treturn r\n}\n\n// from the standard library description of Bytes():\n// Bytes() returns a slice of the contents of the unread portion of the buffer.\n// If the caller changes the contents of the\n// returned slice, the contents of the buffer will change provided there\n//  are no intervening method calls on the Buffer.\n//\n// The largest slice Bytes ever returns is bounded above by the maxViewInBytes\n// value used when calling NewFixedSizeRingBuf().\nfunc (b *FixedSizeRingBuf) Bytes() []byte {\n\n\textent := b.Beg + b.Readable\n\tif extent <= b.N {\n\t\t// we fit contiguously in this buffer without wrapping to the other\n\t\treturn b.A[b.Use][b.Beg:(b.Beg + b.Readable)]\n\t}\n\n\t// wrap into the other buffer\n\tsrc := b.Use\n\tdest := 1 - b.Use\n\n\tn := copy(b.A[dest], b.A[src][b.Beg:])\n\tn += copy(b.A[dest][n:], b.A[src][0:(extent%b.N)])\n\n\tb.Use = dest\n\tb.Beg = 0\n\n\treturn b.A[b.Use][:n]\n}\n\n// BytesTwo returns all readable bytes, but in two separate slices,\n// to avoid copying. The two slices are from the same buffer, but\n// are not contiguous. Either or both may be empty slices.\nfunc (b *FixedSizeRingBuf) BytesTwo(makeCopy bool) (first []byte, second []byte) {\n\n\textent := b.Beg + b.Readable\n\tif extent <= b.N {\n\t\t// we fit contiguously in this buffer without wrapping to the other.\n\t\t// Let second stay an empty slice.\n\t\treturn b.A[b.Use][b.Beg:(b.Beg + b.Readable)], second\n\t}\n\n\treturn b.A[b.Use][b.Beg:b.N], b.A[b.Use][0:(extent % b.N)]\n}\n\n// Read():\n//\n// from bytes.Buffer.Read(): Read reads the next len(p) bytes\n// from the buffer or until the buffer is drained. The return\n// value n is the number of bytes read. If the buffer has no data\n// to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.\n//\n//  from the description of the Reader interface,\n//     http://golang.org/pkg/io/#Reader\n//\n/*\nReader is the interface that wraps the basic Read method.\n\nRead reads up to len(p) bytes into p. It returns the number\nof bytes read (0 <= n <= len(p)) and any error encountered.\nEven if Read returns n < len(p), it may use all of p as scratch\nspace during the call. If some data is available but not\nlen(p) bytes, Read conventionally returns what is available\ninstead of waiting for more.\n\nWhen Read encounters an error or end-of-file condition after\nsuccessfully reading n > 0 bytes, it returns the number of bytes\nread. It may return the (non-nil) error from the same call or\nreturn the error (and n == 0) from a subsequent call. An instance\nof this general case is that a Reader returning a non-zero number\nof bytes at the end of the input stream may return\neither err == EOF or err == nil. The next Read should\nreturn 0, EOF regardless.\n\nCallers should always process the n > 0 bytes returned before\nconsidering the error err. Doing so correctly handles I/O errors\nthat happen after reading some bytes and also both of the\nallowed EOF behaviors.\n\nImplementations of Read are discouraged from returning a zero\nbyte count with a nil error, and callers should treat that\nsituation as a no-op.\n*/\n//\nfunc (b *FixedSizeRingBuf) Read(p []byte) (n int, err error) {\n\treturn b.ReadAndMaybeAdvance(p, true)\n}\n\n// ReadWithoutAdvance(): if you want to Read the data and leave\n// it in the buffer, so as to peek ahead for example.\nfunc (b *FixedSizeRingBuf) ReadWithoutAdvance(p []byte) (n int, err error) {\n\treturn b.ReadAndMaybeAdvance(p, false)\n}\n\nfunc (b *FixedSizeRingBuf) ReadAndMaybeAdvance(p []byte, doAdvance bool) (n int, err error) {\n\tif len(p) == 0 {\n\t\treturn 0, nil\n\t}\n\tif b.Readable == 0 {\n\t\treturn 0, io.EOF\n\t}\n\textent := b.Beg + b.Readable\n\tif extent <= b.N {\n\t\tn += copy(p, b.A[b.Use][b.Beg:extent])\n\t} else {\n\t\tn += copy(p, b.A[b.Use][b.Beg:b.N])\n\t\tif n < len(p) {\n\t\t\tn += copy(p[n:], b.A[b.Use][0:(extent%b.N)])\n\t\t}\n\t}\n\tif doAdvance {\n\t\tb.Advance(n)\n\t}\n\treturn\n}\n\n//\n// Write writes len(p) bytes from p to the underlying data stream.\n// It returns the number of bytes written from p (0 <= n <= len(p))\n// and any error encountered that caused the write to stop early.\n// Write must return a non-nil error if it returns n < len(p).\n//\nfunc (b *FixedSizeRingBuf) Write(p []byte) (n int, err error) {\n\tfor {\n\t\tif len(p) == 0 {\n\t\t\t// nothing (left) to copy in; notice we shorten our\n\t\t\t// local copy p (below) as we read from it.\n\t\t\treturn\n\t\t}\n\n\t\twriteCapacity := b.N - b.Readable\n\t\tif writeCapacity <= 0 {\n\t\t\t// we are all full up already.\n\t\t\treturn n, io.ErrShortWrite\n\t\t}\n\t\tif len(p) > writeCapacity {\n\t\t\terr = io.ErrShortWrite\n\t\t\t// leave err set and\n\t\t\t// keep going, write what we can.\n\t\t}\n\n\t\twriteStart := (b.Beg + b.Readable) % b.N\n\n\t\tupperLim := intMin(writeStart+writeCapacity, b.N)\n\n\t\tk := copy(b.A[b.Use][writeStart:upperLim], p)\n\n\t\tn += k\n\t\tb.Readable += k\n\t\tp = p[k:]\n\n\t\t// we can fill from b.A[b.Use][0:something] from\n\t\t// p's remainder, so loop\n\t}\n}\n\n//\n// WriteAndMaybeOverwriteOldestData always consumes the full\n// buffer p, even if that means blowing away the oldest\n// unread bytes in the ring to make room. In reality, only the last\n// min(len(p),b.N) bytes of p will end up being written to the ring.\n//\n// This allows the ring to act as a record of the most recent\n// b.N bytes of data -- a kind of temporal LRU cache, so the\n// speak. The linux kernel's dmesg ring buffer is similar.\n//\nfunc (b *FixedSizeRingBuf) WriteAndMaybeOverwriteOldestData(p []byte) (n int, err error) {\n\twriteCapacity := b.N - b.Readable\n\tif len(p) > writeCapacity {\n\t\tb.Advance(len(p) - writeCapacity)\n\t}\n\tstartPos := 0\n\tif len(p) > b.N {\n\t\tstartPos = len(p) - b.N\n\t}\n\tn, err = b.Write(p[startPos:])\n\tif err != nil {\n\t\treturn n, err\n\t}\n\treturn len(p), nil\n}\n\n// WriteTo and ReadFrom avoid intermediate allocation and copies.\n\n// WriteTo avoids intermediate allocation and copies.\n// WriteTo writes data to w until there's no more data to write\n// or when an error occurs. The return value n is the number of\n// bytes written. Any error encountered during the write is also returned.\nfunc (b *FixedSizeRingBuf) WriteTo(w io.Writer) (n int64, err error) {\n\n\tif b.Readable == 0 {\n\t\treturn 0, io.EOF\n\t}\n\n\textent := b.Beg + b.Readable\n\tfirstWriteLen := intMin(extent, b.N) - b.Beg\n\tsecondWriteLen := b.Readable - firstWriteLen\n\tif firstWriteLen > 0 {\n\t\tm, e := w.Write(b.A[b.Use][b.Beg:(b.Beg + firstWriteLen)])\n\t\tn += int64(m)\n\t\tb.Advance(m)\n\n\t\tif e != nil {\n\t\t\treturn n, e\n\t\t}\n\t\t// all bytes should have been written, by definition of\n\t\t// Write method in io.Writer\n\t\tif m != firstWriteLen {\n\t\t\treturn n, io.ErrShortWrite\n\t\t}\n\t}\n\tif secondWriteLen > 0 {\n\t\tm, e := w.Write(b.A[b.Use][0:secondWriteLen])\n\t\tn += int64(m)\n\t\tb.Advance(m)\n\n\t\tif e != nil {\n\t\t\treturn n, e\n\t\t}\n\t\t// all bytes should have been written, by definition of\n\t\t// Write method in io.Writer\n\t\tif m != secondWriteLen {\n\t\t\treturn n, io.ErrShortWrite\n\t\t}\n\t}\n\n\treturn n, nil\n}\n\n// ReadFrom avoids intermediate allocation and copies.\n// ReadFrom() reads data from r until EOF or error. The return value n\n// is the number of bytes read. Any error except io.EOF encountered\n// during the read is also returned.\nfunc (b *FixedSizeRingBuf) ReadFrom(r io.Reader) (n int64, err error) {\n\tfor {\n\t\twriteCapacity := b.N - b.Readable\n\t\tif writeCapacity <= 0 {\n\t\t\t// we are all full\n\t\t\treturn n, nil\n\t\t}\n\t\twriteStart := (b.Beg + b.Readable) % b.N\n\t\tupperLim := intMin(writeStart+writeCapacity, b.N)\n\n\t\tm, e := r.Read(b.A[b.Use][writeStart:upperLim])\n\t\tn += int64(m)\n\t\tb.Readable += m\n\t\tif e == io.EOF {\n\t\t\treturn n, nil\n\t\t}\n\t\tif e != nil {\n\t\t\treturn n, e\n\t\t}\n\t}\n}\n\n// Reset quickly forgets any data stored in the ring buffer. The\n// data is still there, but the ring buffer will ignore it and\n// overwrite those buffers as new data comes in.\nfunc (b *FixedSizeRingBuf) Reset() {\n\tb.Beg = 0\n\tb.Readable = 0\n\tb.Use = 0\n}\n\n// Advance(): non-standard, but better than Next(),\n// because we don't have to unwrap our buffer and pay the cpu time\n// for the copy that unwrapping may need.\n// Useful in conjuction/after ReadWithoutAdvance() above.\nfunc (b *FixedSizeRingBuf) Advance(n int) {\n\tif n <= 0 {\n\t\treturn\n\t}\n\tif n > b.Readable {\n\t\tn = b.Readable\n\t}\n\tb.Readable -= n\n\tb.Beg = (b.Beg + n) % b.N\n}\n\n// Adopt(): non-standard.\n//\n// For efficiency's sake, (possibly) take ownership of\n// already allocated slice offered in me.\n//\n// If me is large we will adopt it, and we will potentially then\n// write to the me buffer.\n// If we already have a bigger buffer, copy me into the existing\n// buffer instead.\nfunc (b *FixedSizeRingBuf) Adopt(me []byte) {\n\tn := len(me)\n\tif n > b.N {\n\t\tb.A[0] = me\n\t\tb.A[1] = make([]byte, n, n)\n\t\tb.N = n\n\t\tb.Use = 0\n\t\tb.Beg = 0\n\t\tb.Readable = n\n\t} else {\n\t\t// we already have a larger buffer, reuse it.\n\t\tcopy(b.A[0], me)\n\t\tb.Use = 0\n\t\tb.Beg = 0\n\t\tb.Readable = n\n\t}\n}\n\nfunc intMax(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}\n\nfunc intMin(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t} else {\n\t\treturn b\n\t}\n}\n\nfunc (f *FixedSizeRingBuf) Avail() int {\n\treturn f.Readable\n}\n\n// First returns the earliest index, or -1 if\n// the ring is empty\nfunc (f *FixedSizeRingBuf) First() int {\n\tif f.Readable == 0 {\n\t\treturn -1\n\t}\n\treturn f.Beg\n}\n\n// Next returns the index of the element after\n// from, or -1 if no more. returns -2 if erroneous\n// input (bad from).\nfunc (f *FixedSizeRingBuf) Nextpos(from int) int {\n\tif from >= f.N || from < 0 {\n\t\treturn -2\n\t}\n\tif f.Readable == 0 {\n\t\treturn -1\n\t}\n\n\tlast := f.Last()\n\tif from == last {\n\t\treturn -1\n\t}\n\ta0, a1, b0, b1 := f.LegalPos()\n\tswitch {\n\tcase from >= a0 && from < a1:\n\t\treturn from + 1\n\tcase from == a1:\n\t\treturn b0 // can be -1\n\tcase from >= b0 && from < b1:\n\t\treturn from + 1\n\tcase from == b1:\n\t\treturn -1\n\t}\n\treturn -1\n}\n\n// LegalPos returns the legal index positions,\n// [a0,aLast] and [b0,bLast] inclusive, where the\n// [a0,aLast] holds the first FIFO ordered segment,\n// and the [b0,bLast] holds the second ordered segment,\n// if any.\n// A position of -1 means the segment is not used,\n// perhaps because b.Readable is zero, or because\n// the second segment [b0,bLast] is not in use (when\n// everything fits in the first [a0,aLast] segment).\n//\nfunc (b *FixedSizeRingBuf) LegalPos() (a0, aLast, b0, bLast int) {\n\ta0 = -1\n\taLast = -1\n\tb0 = -1\n\tbLast = -1\n\tif b.Readable == 0 {\n\t\treturn\n\t}\n\ta0 = b.Beg\n\tlast := b.Beg + b.Readable - 1\n\tif last < b.N {\n\t\taLast = last\n\t\treturn\n\t}\n\taLast = b.N - 1\n\tb0 = 0\n\tbLast = last % b.N\n\treturn\n}\n\n// Prevpos returns the index of the element before\n// from, or -1 if no more and from is the\n// first in the ring. Returns -2 on bad\n// from position.\nfunc (f *FixedSizeRingBuf) Prevpos(from int) int {\n\tif from >= f.N || from < 0 {\n\t\treturn -2\n\t}\n\tif f.Readable == 0 {\n\t\treturn -1\n\t}\n\tif from == f.Beg {\n\t\treturn -1\n\t}\n\ta0, a1, b0, b1 := f.LegalPos()\n\tswitch {\n\tcase from == a0:\n\t\treturn -1\n\tcase from > a0 && from <= a1:\n\t\treturn from - 1\n\tcase from == b0:\n\t\treturn a1\n\tcase from > b0 && from <= b1:\n\t\treturn from - 1\n\t}\n\treturn -1\n}\n\n// Last returns the index of the last element,\n// or -1 if the ring is empty.\nfunc (f *FixedSizeRingBuf) Last() int {\n\tif f.Readable == 0 {\n\t\treturn -1\n\t}\n\n\tlast := f.Beg + f.Readable - 1\n\tif last < f.N {\n\t\t// we fit without wrapping\n\t\treturn last\n\t}\n\n\treturn last % f.N\n}\n\n// Kth presents the contents of the\n// ring as a strictly linear sequence,\n// so the user doesn't need to think\n// about modular arithmetic. Here k indexes from\n// [0, f.Readable-1], assuming f.Avail()\n// is greater than 0. Kth() returns an\n// actual index where the logical k-th\n// element, starting from f.Beg, resides.\n// f.Beg itself lives at k = 0. If k is\n// out of bounds, or the ring is empty,\n// -1 is returned.\nfunc (f *FixedSizeRingBuf) Kth(k int) int {\n\tif f.Readable == 0 || k < 0 || k >= f.Readable {\n\t\treturn -1\n\t}\n\treturn (f.Beg + k) % f.N\n}\n\n// DeleteMostRecentBytes trims back the last n bytes written.\nfunc (f *FixedSizeRingBuf) DeleteMostRecentBytes(n int) {\n\tif n <= 0 {\n\t\treturn\n\t}\n\tif n >= f.Readable {\n\t\tf.Readable = 0\n\t\treturn\n\t}\n\tf.Readable -= n\n}\n"
  },
  {
    "path": "rbuf_test.go",
    "content": "package rbuf\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"testing\"\n\n\tcv \"github.com/glycerine/goconvey/convey\"\n)\n\nfunc TestRingBufReadWrite(t *testing.T) {\n\tb := NewFixedSizeRingBuf(5)\n\n\tdata := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n\n\tcv.Convey(\"Given a FixedSizeRingBuf of size 5\", t, func() {\n\t\tcv.Convey(\"Write(), Bytes(), and Read() should put and get bytes\", func() {\n\t\t\tn, err := b.Write(data[0:5])\n\t\t\tcv.So(n, cv.ShouldEqual, 5)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(b.Readable, cv.ShouldEqual, 5)\n\t\t\tif n != 5 {\n\t\t\t\tfmt.Printf(\"should have been able to write 5 bytes.\\n\")\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tcv.So(b.Bytes(), cv.ShouldResemble, data[0:5])\n\n\t\t\tsink := make([]byte, 3)\n\t\t\tn, err = b.Read(sink)\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(b.Bytes(), cv.ShouldResemble, data[3:5])\n\t\t\tcv.So(sink, cv.ShouldResemble, data[0:3])\n\t\t})\n\n\t\tcv.Convey(\"Write() more than 5 should give back ErrShortWrite\", func() {\n\t\t\tb.Reset()\n\t\t\tcv.So(b.Readable, cv.ShouldEqual, 0)\n\t\t\tn, err := b.Write(data[0:10])\n\t\t\tcv.So(n, cv.ShouldEqual, 5)\n\t\t\tcv.So(err, cv.ShouldEqual, io.ErrShortWrite)\n\t\t\tcv.So(b.Readable, cv.ShouldEqual, 5)\n\t\t\tif n != 5 {\n\t\t\t\tfmt.Printf(\"should have been able to write 5 bytes.\\n\")\n\t\t\t}\n\t\t\tcv.So(b.Bytes(), cv.ShouldResemble, data[0:5])\n\n\t\t\tsink := make([]byte, 3)\n\t\t\tn, err = b.Read(sink)\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(b.Bytes(), cv.ShouldResemble, data[3:5])\n\t\t\tcv.So(sink, cv.ShouldResemble, data[0:3])\n\t\t})\n\n\t\tcv.Convey(\"we should be able to wrap data and then get it back in Bytes()\", func() {\n\t\t\tb.Reset()\n\n\t\t\tn, err := b.Write(data[0:3])\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\n\t\t\tsink := make([]byte, 3)\n\t\t\tn, err = b.Read(sink) // put b.beg at 3\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(b.Readable, cv.ShouldEqual, 0)\n\n\t\t\tn, err = b.Write(data[3:8]) // wrap 3 bytes around to the front\n\t\t\tcv.So(n, cv.ShouldEqual, 5)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\n\t\t\tby := b.Bytes()\n\t\t\tcv.So(by, cv.ShouldResemble, data[3:8]) // but still get them back from the ping-pong buffering\n\n\t\t})\n\n\t\tcv.Convey(\"FixedSizeRingBuf::WriteTo() should work with wrapped data\", func() {\n\t\t\tb.Reset()\n\n\t\t\tn, err := b.Write(data[0:3])\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\n\t\t\tsink := make([]byte, 3)\n\t\t\tn, err = b.Read(sink) // put b.beg at 3\n\t\t\tcv.So(n, cv.ShouldEqual, 3)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(b.Readable, cv.ShouldEqual, 0)\n\n\t\t\tn, err = b.Write(data[3:8]) // wrap 3 bytes around to the front\n\n\t\t\tvar bb bytes.Buffer\n\t\t\tm, err := b.WriteTo(&bb)\n\n\t\t\tcv.So(m, cv.ShouldEqual, 5)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\n\t\t\tby := bb.Bytes()\n\t\t\tcv.So(by, cv.ShouldResemble, data[3:8]) // but still get them back from the ping-pong buffering\n\n\t\t})\n\n\t\tcv.Convey(\"FixedSizeRingBuf::ReadFrom() should work with wrapped data\", func() {\n\t\t\tb.Reset()\n\t\t\tvar bb bytes.Buffer\n\t\t\tn, err := b.ReadFrom(&bb)\n\t\t\tcv.So(n, cv.ShouldEqual, 0)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\n\t\t\t// write 4, then read 4 bytes\n\t\t\tm, err := b.Write(data[0:4])\n\t\t\tcv.So(m, cv.ShouldEqual, 4)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\n\t\t\tsink := make([]byte, 4)\n\t\t\tk, err := b.Read(sink) // put b.beg at 4\n\t\t\tcv.So(k, cv.ShouldEqual, 4)\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(b.Readable, cv.ShouldEqual, 0)\n\t\t\tcv.So(b.Beg, cv.ShouldEqual, 4)\n\n\t\t\tbbread := bytes.NewBuffer(data[4:9])\n\t\t\tn, err = b.ReadFrom(bbread) // wrap 4 bytes around to the front, 5 bytes total.\n\n\t\t\tby := b.Bytes()\n\t\t\tcv.So(by, cv.ShouldResemble, data[4:9]) // but still get them back continguous from the ping-pong buffering\n\t\t})\n\n\t\tcv.Convey(\"FixedSizeRingBuf::WriteAndMaybeOverwriteOldestData() should auto advance\", func() {\n\t\t\tb.Reset()\n\t\t\tn, err := b.WriteAndMaybeOverwriteOldestData(data[:5])\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(n, cv.ShouldEqual, 5)\n\n\t\t\tn, err = b.WriteAndMaybeOverwriteOldestData(data[5:7])\n\t\t\tcv.So(n, cv.ShouldEqual, 2)\n\t\t\tcv.So(b.Bytes(), cv.ShouldResemble, data[2:7])\n\n\t\t\tn, err = b.WriteAndMaybeOverwriteOldestData(data[0:9])\n\t\t\tcv.So(err, cv.ShouldEqual, nil)\n\t\t\tcv.So(n, cv.ShouldEqual, 9)\n\t\t\tcv.So(b.Bytes(), cv.ShouldResemble, data[4:9])\n\t\t})\n\n\t})\n\n}\n\nfunc TestNextPrev(t *testing.T) {\n\tb := NewFixedSizeRingBuf(6)\n\tdata := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n\n\tcv.Convey(\"Given a FixedSizeRingBuf of size 6, filled with 4 elements at various begin points, then Nextpos() and Prev() should return the correct positions or <0 if done\", t, func() {\n\t\tk := b.N\n\t\tfor i := 0; i < b.N; i++ {\n\t\t\tb.Reset()\n\t\t\tb.Beg = i\n\t\t\t_, err := b.Write(data[0:k])\n\t\t\tpanicOn(err)\n\t\t\t// cannot go prev to first\n\t\t\tcv.So(b.Prevpos(i), cv.ShouldEqual, -1)\n\t\t\t// cannot go after last\n\t\t\tcv.So(b.Nextpos((i+k-1)%b.N), cv.ShouldEqual, -1)\n\t\t\t// in the middle we should be okay\n\t\t\tfor j := 1; j < k-1; j++ {\n\t\t\t\tr := (i + j) % b.N\n\t\t\t\tprev := b.Prevpos(r)\n\t\t\t\tnext := b.Nextpos(r)\n\t\t\t\tcv.So(prev >= 0, cv.ShouldBeTrue)\n\t\t\t\tcv.So(next >= 0, cv.ShouldBeTrue)\n\t\t\t\tif next > r {\n\t\t\t\t\tcv.So(next, cv.ShouldEqual, r+1)\n\t\t\t\t} else {\n\t\t\t\t\tcv.So(next, cv.ShouldEqual, 0)\n\t\t\t\t}\n\t\t\t\tif prev < r {\n\t\t\t\t\tcv.So(prev, cv.ShouldEqual, r-1)\n\t\t\t\t} else {\n\t\t\t\t\tcv.So(prev, cv.ShouldEqual, b.N-1)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc panicOn(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n"
  }
]