-
Notifications
You must be signed in to change notification settings - Fork 0
/
disksim.c
75 lines (58 loc) · 1.65 KB
/
disksim.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <stdlib.h>
#include <memory.h>
#include "ext2.h"
#include "disk.h"
#include "disksim.h"
typedef struct
{
char* address;
} DISK_MEMORY;
int disksim_read(DISK_OPERATIONS* this, SECTOR sector, void* data);
int disksim_write(DISK_OPERATIONS* this, SECTOR sector, const void* data);
int disksim_init(SECTOR numberOfSectors, unsigned int bytesPerSector, DISK_OPERATIONS* disk)
{
if (disk == NULL)
return -1;
disk->pdata = malloc(sizeof(DISK_MEMORY));
if (disk->pdata == NULL)
{
disksim_uninit(disk);
return -1;
}
((DISK_MEMORY*)disk->pdata)->address = (char*)malloc(bytesPerSector * numberOfSectors);
if (disk->pdata == NULL)
{
disksim_uninit(disk);
return -1;
}
memset(((DISK_MEMORY*)disk->pdata)->address, 0, bytesPerSector * numberOfSectors);
disk->read_sector = disksim_read;
disk->write_sector = disksim_write;
disk->numberOfSectors = numberOfSectors;
disk->bytesPerSector = bytesPerSector;
return 0;
}
void disksim_uninit(DISK_OPERATIONS* this)
{
if (this)
{
if (this->pdata)
free(this->pdata);
}
}
int disksim_read(DISK_OPERATIONS* this, SECTOR sector, void* data)
{
char* disk = ((DISK_MEMORY*)this->pdata)->address;
if (sector < 0 || sector >= this->numberOfSectors)
return -1;
memcpy(data, &disk[sector * this->bytesPerSector], this->bytesPerSector);
return 0;
}
int disksim_write(DISK_OPERATIONS* this, SECTOR sector, const void* data)
{
char* disk = ((DISK_MEMORY*)this->pdata)->address;
if (sector < 0 || sector >= this->numberOfSectors)
return -1;
memcpy(&disk[sector * this->bytesPerSector], data, this->bytesPerSector);
return 0;
}