[docs]def__init__(self,size,filename):""" Class constructor. Initialize the vdisk object. Args: size (int): Size in bytes of the vdisk. filename (str): Real filename of the vdisk in the filesystem. """self._filename=os.path.join(os.path.expanduser("~"),"."+filename)self._size=sizeself._disk=[0b00000000]*self._sizeself._terminal=Terminal()
[docs]defget_size(self)->int:"""Get the size of the virtual disk. Returns: int: Size in bytes of the virtual disk. """returnself._size;
[docs]def__str__(self)->str:"""Overload of the str() function. Returns: str: A string with the filename and size of the disk. """returnf"Filename: {self._filename} // Size: {self._size} bytes."
[docs]defsize(self)->int:"""Size of the virtual disk. Returns: int: Size in bytes of the virtual disk. """returnself._size
[docs]deffilename(self,name:str)->None:"""Set the filename of the virtual disk. Args: name (str): Name of the file. """self._filename=name
[docs]defwrite(self,sector:int,value:int)->bool:"""Write bytes to the virtual disk. Args: sector: Sector where the byte is written. value: The byte to be written. Returns: bool: True if successful, False if not. """ifsector<0orsector>self._size-1:self._terminal.error_message("Invalid sector.")returnFalseelifvalue<0orvalue>255:self._terminal.error_message("Disk.write(): Invalid value.")returnFalseelse:self._disk[int(sector)]=valuereturnTrue
[docs]defread(self,sector:int)->int:"""Read a virtual disk sector. Parameters: sector (int): Sector to be read. Returns: int: the read byte or -1 if there were any problem. """ifsector<0orsector>self._size-1:self._terminal.error_message("Disk.read(): Invalid sector.")return-1else:returnself._disk[int(sector)]
[docs]defload(self)->bool:"""Load the virtual disk from a real file. Returns: bool: True if was successful, False if not, """try:withopen(self._filename,'rb')asf:content=f.read()exceptIOError:self._terminal.error_message(f"Disk.load(): Problem accessing {self._filename}")returnFalsefori,valueinenumerate(content):self._disk[i]=valuereturnTrue
[docs]defsave(self)->bool:"""Save the virtual disk to a real file. Returns: bool: True if was successful, False if not. """try:withopen(self._filename,'w+b')asf:binary_format=bytearray(self._disk)bytes_written=f.write(binary_format)ifbytes_written==self._size:self._terminal.info_message(f"Active page saved to: {AnsiColors.BRIGHT_YELLOW.value}{self._filename}.{AnsiColors.RESET.value}")self._terminal.info_message(f"Size: {AnsiColors.BRIGHT_YELLOW.value}{len(binary_format)} bytes.{AnsiColors.RESET.value}")returnTrueelse:self._terminal.error_message(f"Expected to write {self._size} bytes, but only wrote {bytes_written} bytes.")returnFalseexceptIOError:self._terminal.error_message(f"Disk.save(): Problem accessing {self._filename}")returnFalse