| 15 | 16 | |
| 16 | 17 | """ |
| 17 | 18 | def __init__(self, message: str): |
| 18 | | pass |
| 19 | self.message = message |
| 20 | super().__init__(message) |
| 19 | 21 | |
| 20 | 22 | |
| 21 | 23 | class CircularBuffer: |
| 22 | 24 | def __init__(self, capacity: int): |
| 23 | | pass |
| 24 | | |
| 25 | self.capacity = capacity |
| 26 | self.buffer = [None] * capacity # Fixed-size array |
| 27 | self.head = 0 # Points to oldest element (to read) |
| 28 | self.tail = 0 # Points to next write position |
| 29 | self.size = 0 # Current number of elements |
| 30 | |
| 25 | 31 | def read(self) -> str: |
| 26 | | pass |
| 27 | | |
| 32 | # Edge Case: Buffer is empty when trying to read |
| 33 | if self.size == 0: |
| 34 | raise BufferEmptyException("Circular buffer is empty") |
| 35 | |
| 36 | data = self.buffer[self.head] |
| 37 | self.buffer[self.head] = None # Clear the position |
| 38 | self.head = (self.head + 1) % self.capacity # Move head circularly |
| 39 | self.size -= 1 |
| 40 | return data |
| 41 | |
| 28 | 42 | def write(self, data: str) -> None: |
| 29 | | pass |
| 30 | | |
| 43 | # Edge Case: Buffer is full when trying to write |
| 44 | if self.size >= self.capacity: |
| 45 | raise BufferFullException("Circular buffer is full") |
| 46 | |
| 47 | self.buffer[self.tail] = data |
| 48 | self.tail = (self.tail + 1) % self.capacity # Move tail circularly |
| 49 | self.size += 1 |
| 50 | |
| 31 | 51 | def overwrite(self, data: str) -> None: |
| 32 | | pass |
| 33 | | |
| 52 | # If buffer is full, overwrite oldest element by moving head |
| 53 | if self.size >= self.capacity: |
| 54 | self.head = (self.head + 1) % self.capacity # Move head to skip oldest |
| 55 | self.size -= 1 |
| 56 | |
| 57 | self.buffer[self.tail] = data |
| 58 | self.tail = (self.tail + 1) % self.capacity # Move tail circularly |
| 59 | self.size += 1 |
| 60 | |
| 34 | 61 | def clear(self) -> None: |
| 35 | | pass |
| 62 | self.buffer = [None] * self.capacity |
| 63 | self.head = 0 |
| 64 | self.tail = 0 |
| 65 | self.size = 0 |
| 66 | |
| 67 | # Handled Edge Cases: Buffer is empty when trying to read; Buffer is full when trying to write; Buffer is full and overwrite removes oldest element before adding new one |