jellyfin-smart-playlist/Jellyfin.Plugin.SmartPlaylist/Util/Stream.cs

62 lines
1.6 KiB
C#
Raw Normal View History

2024-06-27 01:47:44 +02:00
namespace Jellyfin.Plugin.SmartPlaylist.Util {
public interface IStream<T> {
int Available();
T Get();
int Commit();
int Rewind();
int Rewind(int n);
int Consumed();
IStream<T> Copy();
2024-06-27 01:47:44 +02:00
}
public class Stream<T> : IStream<T> {
private readonly IList<T> _items;
private int _cursor;
private int _ephemeralCursor;
2024-06-27 01:47:44 +02:00
protected Stream(IList<T> items) {
_items = items;
_cursor = 0;
_ephemeralCursor = 0;
2024-06-27 01:47:44 +02:00
}
private Stream(IList<T> items, int cursor, int ephemeralCursor) {
_items = items;
_cursor = cursor;
_ephemeralCursor = ephemeralCursor;
}
public int Available() {
return _items.Count - _ephemeralCursor;
2024-06-27 01:47:44 +02:00
}
public T Get() {
return _items[_ephemeralCursor++];
2024-06-27 01:47:44 +02:00
}
public int Commit() {
int diff = Consumed();
_cursor = _ephemeralCursor;
2024-06-27 01:47:44 +02:00
return diff;
}
public int Rewind() {
int diff = Consumed();
_ephemeralCursor = _cursor;
2024-06-27 01:47:44 +02:00
return diff;
}
public int Rewind(int n) {
int diff = Consumed();
2024-06-27 01:47:44 +02:00
if (diff < n) {
n = diff;
}
_ephemeralCursor -= n;
2024-06-27 01:47:44 +02:00
return n;
}
public int Consumed() {
return _ephemeralCursor - _cursor;
}
public IStream<T> Copy() {
return new Stream<T>(_items, _cursor, _ephemeralCursor);
}
2024-06-27 01:47:44 +02:00
}
}