base.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # This file provides a wrapper on memory access, similarly to working with
  2. # pointers in low level languages
  3. # The memory is organized in blocks of a single byte
  4. # use C compatible data types for maximum memory efficiency
  5. import ctypes
  6. class MemoryRequest:
  7. def __init__(self, agent_id: int, round_id: int, operation_type: str, content: str = None):
  8. self.agent_id = agent_id
  9. self.round_id = round_id
  10. self.content = content
  11. self.operation_type = operation_type
  12. class Memory:
  13. def __init__(self, size=1024):
  14. self.size = size
  15. """ makes an array of bytes, typically how memory is organized """
  16. self.memory = (ctypes.c_ubyte * size)()
  17. self.free_blocks = [(0, size - 1)]
  18. # malloc(3) implementation
  19. def mem_alloc(self, size):
  20. for i, (start, end) in enumerate(self.free_blocks):
  21. block_size = end - start + 1
  22. if block_size >= size:
  23. allocated_start = start
  24. allocated_end = start + size - 1
  25. if allocated_end == end:
  26. self.free_blocks.pop(i)
  27. else:
  28. self.free_blocks[i] = (allocated_end + 1, end)
  29. return allocated_start
  30. raise MemoryError("No sufficient memory available.")
  31. def mem_clear(self, start, size):
  32. allocated_end = start + size - 1
  33. self.free_blocks.append((start, allocated_end))
  34. self.free_blocks.sort()
  35. # memcpy(3) implementation
  36. def mem_write(self, address, data):
  37. size = len(data)
  38. if address + size > self.size:
  39. raise MemoryError("Not enough space to write data.")
  40. for i in range(size):
  41. self.memory[address + i] = data[i]
  42. # similar to dereferencing pointers
  43. def mem_read(self, address, size):
  44. data = self.memory[address:address + size]
  45. return data
  46. # abstract implementation of memory utilities for thread safe access
  47. class BaseMemoryManager:
  48. def __init__(self, max_memory_block_size, memory_block_num):
  49. pass
  50. def run(self):
  51. pass
  52. def start(self):
  53. """start the scheduler"""
  54. self.active = True
  55. self.thread.start()
  56. def stop(self):
  57. """stop the scheduler"""
  58. self.active = False
  59. self.thread.join()
  60. def mem_write(self, content: str):
  61. pass
  62. def mem_read(self, agent_id):
  63. pass
  64. def mem_alloc(self, agent_id):
  65. pass
  66. def mem_clear(self):
  67. pass