본문 바로가기

C# 프로그래밍/예제 코드

[C#] 링버퍼(원형큐) - Ring Buffer(Circular Queue)

반응형

일반적인 큐는 선입선출(FIFO, First-In-First-Out) 특징을 활용하여 데이터를 관리 할 수 있도록 해준다.

 

반면 데이터를 순환하며 저장할 수 있게 해주는 구조로 링버퍼를 활용할 수 있다.

 

 

소스코드는 아래와 같다.

 

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RingBuffer<T> {
	public readonly int Size;

	public Action<T> OnOverflow;

	public int Count {
		get;
		private set;
	}

	public int TotalCount {
		get;
		private set;
	}

	private T[] buffer;
	private int position;

	public RingBuffer(int size) {
		this.Size = size;
		this.buffer = new T[size];
		this.Count = 0;
		this.position = 0;
	}

	public void Push(T item) {
		this.position = (this.position + 1) % this.Size;
		if (this.buffer[this.position] != null && this.OnOverflow != null) {
			this.OnOverflow(this.buffer[this.position]);
		}
		this.buffer[this.position] = item;
		this.Count++;
		if (this.Count > this.Size) {
			this.Count = this.Size;
		}
		this.TotalCount++;
	}

	public T Peek() {
		if (this.Count == 0) {
			throw new System.InvalidOperationException();
		}
		return this.buffer[this.position];
	}

	public T Pop() {
		if (this.Count == 0) {
			throw new System.InvalidOperationException();
		}
		T result = this.buffer[this.position];
		this.buffer[this.position] = default(T);

		this.position = (this.position + this.Size - 1) % this.Size;
		this.Count--;
		this.TotalCount--;

		return result;
	}

	public bool Any() {
		return this.Count != 0;
	}
}
반응형