Skip to content

Commit

Permalink
Fixed an unwanted infinite loop (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
suragch committed Jul 10, 2023
1 parent cb5e501 commit ee30e0c
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 8 deletions.
11 changes: 4 additions & 7 deletions 06-queues/projects/final/lib/ring_buffer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ class RingBuffer<E> {
_size++;
}

int _advance(int index) {
return (index == _list.length - 1) ? 0 : index + 1;
}
int _advance(int index) => (index + 1) % _list.length;

E? read() {
if (isEmpty) return null;
Expand All @@ -38,13 +36,12 @@ class RingBuffer<E> {
String toString() {
final text = StringBuffer();
text.write('[');
int index = _readIndex;
while (index != _writeIndex) {
for (int i = 0; i < _size; i++) {
final index = (_readIndex + i) % _list.length;
if (index != _readIndex) {
text.write(', ');
}
text.write(_list[index % _list.length]);
index++;
text.write(_list[index]);
}
text.write(']');
return text.toString();
Expand Down
51 changes: 50 additions & 1 deletion 06-queues/projects/final/test/ring_buffer_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,62 @@ void main() {
expect(buffer.read(), isNull);
});

// https://github.com/kodecocodes/dsad-materials/pull/8
test('toString contains no infinite loop', () {
final buffer = RingBuffer<int>(5);
final buffer = RingBuffer<int>(3);
buffer.write(1);
buffer.write(2);
buffer.write(3);
buffer.read();
expect(buffer.toString(), '[2, 3]');

final rb = RingBuffer<String>(3);
rb.write('Ray');
rb.write('Brian');
rb.write('Noah');
expect(rb.read(), 'Ray');
expect(rb.toString(), '[Brian, Noah]');
});

// https://github.com/kodecocodes/dsad-materials/pull/8
test('toString not empty when read and write index equal', () {
final rb = RingBuffer<String>(3);
rb.write('Ray');
rb.write('Brian');
rb.write('Noah');
expect(rb.toString(), '[Ray, Brian, Noah]');
});

test('toString variations', () {
var buffer = RingBuffer<int>(3);
expect(buffer.toString(), '[]');

buffer.write(1);
expect(buffer.toString(), '[1]');

buffer.write(2);
expect(buffer.toString(), '[1, 2]');

buffer.write(3);
expect(buffer.toString(), '[1, 2, 3]');

buffer.read();
expect(buffer.toString(), '[2, 3]');

buffer.write(4);
expect(buffer.toString(), '[2, 3, 4]');

buffer.read();
expect(buffer.toString(), '[3, 4]');

buffer.read();
expect(buffer.toString(), '[4]');

buffer.read();
expect(buffer.toString(), '[]');

buffer.read();
expect(buffer.toString(), '[]');
});
});
}

0 comments on commit ee30e0c

Please sign in to comment.