-
Notifications
You must be signed in to change notification settings - Fork 1
/
pager.h
109 lines (93 loc) · 2.77 KB
/
pager.h
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <stdint.h>
#include <sys/fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include "types.h"
#ifndef PAGER_H
#define PAGER_H
pager_t *pager_open(const char *filename)
{
// S_IWUSR means User write permission
// S_IRUSR means User read permission
int fd = open(filename, O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
if (fd < 0)
{
printf("Unable to open file\n");
exit(EXIT_FAILURE);
}
off_t file_length = lseek(fd, 0, SEEK_END);
pager_t *pager = (pager_t *)malloc(sizeof(pager_t));
pager->file_descriptor = fd;
pager->file_length = file_length;
pager->num_pages = file_length / PAGE_SIZE;
if (file_length % PAGE_SIZE != 0)
{
printf("Db file is not a whole number of pages. Corrupt file.\n");
exit(EXIT_FAILURE);
}
for (uint32_t i = 0; i < TABLE_MAX_PAGES; i++)
{
pager->pages[i] = NULL;
}
return pager;
}
void *get_page(pager_t *pager, uint32_t page_num)
{
if (page_num > TABLE_MAX_PAGES)
{
printf("Tried to fetch page number out of bounds. %u > %u\n", page_num, TABLE_MAX_PAGES);
exit(EXIT_FAILURE);
}
// Cache miss. Allocate memory and load from file.
if (pager->pages[page_num] == NULL)
{
void *page = malloc(PAGE_SIZE);
uint32_t num_pages = pager->file_length / PAGE_SIZE;
// 引入 B tree 之后必然是整页读写的
// if (pager->file_length % PAGE_SIZE)
// {
// num_pages += 1;
// }
if (page_num <= num_pages)
{
lseek(pager->file_descriptor, page_num * PAGE_SIZE, SEEK_SET);
ssize_t bytes_read = read(pager->file_descriptor, page, PAGE_SIZE);
if (bytes_read == -1)
{
printf("Error reading file: %d\n", errno);
exit(EXIT_FAILURE);
}
}
pager->pages[page_num] = page;
// pager_open() 中 num_pages 初始化为 file_length / PAGE_SIZE
// 当插入数据时,需要新增 1 page 时执行
if (page_num >= pager->num_pages)
{
pager->num_pages = page_num + 1;
}
}
return pager->pages[page_num];
}
void pager_flush(pager_t *pager, uint32_t page_num)
{
if (pager->pages[page_num] == NULL)
{
printf("Tried to flush null page\n");
exit(EXIT_FAILURE);
}
off_t offset = lseek(pager->file_descriptor, page_num * PAGE_SIZE, SEEK_SET);
if (offset == -1)
{
printf("Error seeking: %d\n", errno);
exit(EXIT_FAILURE);
}
ssize_t bytes_written = write(pager->file_descriptor, pager->pages[page_num], PAGE_SIZE);
if (bytes_written == -1)
{
printf("Error writing: %d\n", errno);
exit(EXIT_FAILURE);
}
}
#endif