Golang Implementation Ringbuf

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Ring Buffer Algorithm benefits: High memory usage, in buffered buffer memory model, It is not easy to have memory out of bounds, dangling pointers and other bugs, the problem is also easy to analyze debugging at the memory level. The system is easy to keep strong.

package mainimport  ("bytes" "FMT") type ringbuf struct {buf          []bytestart, size int}func new (Size int)  *Ringbuf  {Return &ringbuf{make ([]byte, size), 0, 0}}func  (r *ringbuf)  Write (b  []byte)  {for len (b)  > 0 {start :=  (r.start + r.size)  % len (R.BUF) n := copy (r.buf[start:], b) B = b[n:] //golang is to make good use of the slice if  r.size >= len (R.BUF)  {if n <= len (R.BUF)  {r.start +=  Nif r.start >= len (R.BUF)  {r.start = 0}} else {r.start =  0}}r.size += n// size can ' t exceed the capacityif r.size >  cap (R.BUF)  {r.size = cap (r.buf)}}}func  (r *ringbuf)  Read (b []byte)  int {read :=&Nbsp;0size := r.sizestart := r.startfor len (b)  > 0 &&  Size > 0 {end := start + sizeif end > len (R.BUF)   {End = len (R.BUF)}n := copy (B, r.buf[start:end]) size -= nread +=  nb = b[n:]start =  (start + n)  % len (R.BUF)}return read}func  (R&NBSP;*RINGBUF)  size ()  int {return r.size}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.