Giter Site home page Giter Site logo

circularbuffer-csharp's Introduction

Circular Buffer

Build Status nuget

Simple implementation of a circular buffer in C#. This is a single file implementation, which means that you only need to copy the CircularBuffer.cs file to your project and use it.

What is a circular buffer?

A circular buffer, cyclic buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end.

This means that you have predefined memory usage. Push and Pop operations are always O(1). Index access is also O(1).

More info @ wikipedia: http://en.wikipedia.org/wiki/Circular_buffer

circularbuffer-csharp's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar joaoportela avatar levibotelho avatar silvenga avatar tinohager avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

circularbuffer-csharp's Issues

Naming conventions

  1. The Size property should be renamed Count to follow the naming convention used in all built-in C# collections

  2. The Front / Back naming is a bit confusing. If we're using the Circular Buffer like a stack (LIFO), we might think of the "front" as the end of the collection (since it contains the newest element) and "back" as the start of the collection (since it contains the oldest element). Possible alternatives are First/Last (a convention used by LINQ), Start/End,

Enumerating the circular buffer does not produce anything

This code does not produce output from the circular buffer
It only prints the content of the array.
`
int[] values = new int[20];
Random rnd = new Random();

for (int i = 0; i < values.Length; i++)
values[i] = rnd.Next(1, 99);

CircularBuffer buffer = new CircularBuffer(values.Length / 2);

Console.WriteLine(string.Join(", ", values));

foreach (int value in values)
buffer.Add(value);

Console.WriteLine(string.Join(", ", buffer));

Console.ReadKey();
`

I think there might be an issue with this method

`private void innerInsert(T value)
{
_circularBuffer[_tail] = value;
_tail = (_tail + 1) % _circularBuffer.Length;
if (_tail == _head) // <- here
{
_head = (_head + 1) % _circularBuffer.Length;
}

        // Count should not be greater than the length of the buffer when overriding 
        _count = _count < Length ? ++_count : _count;
    }`

[Question] Safe for multi-thread usage ?

Hi, this CircularBuffer-CSharp library is NOT safe for multi-thread usage, is it ?

There is no locking mechanism

    public void PopFront()
    {
        ThrowIfEmpty("Cannot take elements from an empty buffer.");
        _buffer[_start] = default(T);
        Increment(ref _start);
        --_size;
    }


    private void Increment(ref int index)
    {
        if (++index == Capacity)
        {
            index = 0;
        }
    }

Back() is wrong when _end is 0 and buffer is not full

When _end is 0, yet the buffer is not full (_size is not Capacity), Back() returns the wrong value.

For example, consider a buffer of capacity 8 where indices 4-7 are occupied. _start would be 4, and _end would be 0. But the current implementation of Back() loops around by subtracting one from _size when _end is 0. This would put us at index 3, which is bad!

Here is the proper implementation:

public T Back()
{
	ThrowIfEmpty();
	// Was '_size', now 'Capacity'
	return _buffer[(_end != 0 ? _end : Capacity) - 1];
}

Thanks a lot for this useful data structure!

Not an iss-ue, a thank-you!

Apologies in advance if this is the wrong place to put this kind of feedback.

Thank you so much for making this! I was searching all morning for a solid, modern .NET implementation of this classic data structure and stumbled upon yours right when I was about to give up and implement it myself. I'm hoping to integrate the code I plan to use it in with my first proprietary software-based business endeavor, so the Unlicense is also much appreciated.

My hat is off to you. Cheers!

Can not convert from circularbuffer<byte> to byte[]

Thanks for the Circular buffer.I am trying to use it in my serial port communication project in c#. The read method of the port or write takes byte[] as an parameter so I am not able to make use of Circular buffer.

socket use case suggestions

  • Hi, thanks for the CircularBuffer code.
  • When I use CircularBuffer in my socket code,I have some new functionality needed from it.

Use case: socket send byte buffer and receive byte buffer

Description:

  • I have a separate socket thread whose job is:
    • To send my application serialized bytes to socket from CircularBuffer_PendingSend
    • To receive bytes from socket to CircularBuffer_PendingRecv
  • The socket is in unblock mode
    • Every loop I get bytes from CircularBuffer_PendingSend

      • ask socket to send
      • the send function returned immediately with bytes sent
      • remove sent bytes count from CircularBuffer_PendingSend
      • I could use ToArray function, but I want to eliminate unnecessary memory copy
      • My expectation code is as this:
      if(circularBuffer_pendingSend.IsEmpty)
      {
           // pending send buffer is empty, waiting for next loop cycle
           Thread.Sleep(5);
           return;
      }
      ArraySegment<bytes>[] segments = circularBuffer_pendingSend.ToArraySegments();
      int totalBytesSent = 0;
      foreach(var seg in segments)
      {
           if(seg.Count == 0)
           {
               break;
           }
           int bytesSent = socket.Send(seg.Array, seg.Offset, seg.Count);
           totalBytesSent += bytesSent;
           // socket kernel buffer is full, so stop sending
           if(bytesSent < seg.Count)
           {
                break;
           }
       }
       circularBuffer_pendingSend.PopFrontN(totalBytesSent);
    • Every loop cycle I receive bytes from socket and add them to CircularBuffer_PendingRecv back

      • My expectation code is as this:
      // buf is bytes[], temporary recv buffer
      int bytesReceived = socket.Receive(buf);
      circularBuffer_pendingRecv.PushBackBuffer(buf, 0, bytesReceived);

Nullable warnings

The code fails to build in projects where nullable warnings are enabled and warnings are treated as errors.

CircularBuffer.cs(237,29,237,39): error CS8601: Possible null reference assignment.
CircularBuffer.cs(248,31,248,41): error CS8601: Possible null reference assignment.
CircularBuffer.cs(279,28,279,41): error CS8604: Possible null reference argument for parameter 'sourceArray' in 'void Array.Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)'.
CircularBuffer.cs(314,34,314,47): error CS8602: Dereference of a possibly null reference.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.