| 11 | ################################################################################ |
| 12 | |
| 13 | class DAL1: |
| 14 | |
| 15 | # DEFAULTS (16 MB) |
| 16 | BLOCKS = (2 ** 12) |
| 17 | SIZE = (2 ** 12) |
| 18 | |
| 19 | # Disk Abstraction Layer |
| 20 | def __init__(self): |
| 21 | self.__disk = DiskDriver(self.BLOCKS, self.SIZE) |
| 22 | self.__blocks, self.__size = self.__disk.info() |
| 23 | self.__end = self.__blocks * self.__size |
| 24 | |
| 25 | # Read Some Data |
| 26 | def read(self, index, size): |
| 27 | assert type(index) is int and 0 <= index < self.__end |
| 28 | assert type(size) is int and index < index + size <= self.__end |
| 29 | first_index = index |
| 30 | last_index = index + size - 1 |
| 31 | first_block = first_index / self.__size + 1 |
| 32 | last_block = last_index / self.__size + 2 |
| 33 | stream = ''.join([self.__read(block) for block in \ |
| 34 | range(first_block, last_block)]) |
| 35 | first_index = index % self.__size |
| 36 | last_index = first_index + size |
| 37 | return stream[first_index:last_index] |
| 38 | |
| 39 | # Write Some Data |
| 40 | def write(self, index, data): |
| 41 | size = len(data) |
| 42 | assert type(index) is int and 0 <= index < self.__end |
| 43 | assert type(data) is str and index < index + size <= self.__end |
| 44 | first_index = index |
| 45 | last_index = index + size - 1 |
| 46 | first_block = first_index / self.__size + 1 |
| 47 | last_block = last_index / self.__size + 2 |
| 48 | blocks = last_block - first_block |
| 49 | if blocks == 1: |
| 50 | if size == self.__size: |
| 51 | self.__write(first_block, data) |
| 52 | else: |
| 53 | stream = self.__read(first_block) |
| 54 | first_index = index % self.__size |
| 55 | last_index = first_index + size |
| 56 | stream = stream[:first_index] + data + stream[last_index:] |
| 57 | self.__write(first_block, stream) |
| 58 | else: |
| 59 | if index % self.__size: |
| 60 | stream = self.__read(first_block) |
| 61 | first_index = index % self.__size |
| 62 | last_index = self.__size - first_index |
| 63 | stream = stream[:first_index] + data[:last_index] |
| 64 | data = data[last_index:] |
| 65 | self.__write(first_block, stream) |
| 66 | else: |
| 67 | last_index = self.__size |
| 68 | stream = data[:last_index] |
| 69 | data = data[last_index:] |
| 70 | self.__write(first_block, stream) |