c代写-A1-Assignment 2
时间:2022-03-26
Assignment 2
前言:Asm2 要求还是比较容易理解的,编程难度可能会比 A1 稍微高一些,因为涉及
到 dynamic memory 等内容,需要大家对内存的理解和操控有一定的熟练程度才行,
不过也不至于难到写不出来
概括
我们需要写一个可以储存 entry 的 database
这个 database 通过 stdin 和用户进行互动,获取数据和指令
我们的 database 需要判断输入的数据和指令是否符合贵族或者是否可以执行
然后执行对应的操作之后要把相应的 output 输出到 stdout
Element Struct
Element 就是 assignment 里所说的 value,我们用 element 这个 struct 来储存 values。
Element 分为两个类型:
• 一种是 integer
element example1 = {0, 1};
element example2 = {0, 2};
element example3 = {0, 3};
• 另一种是 entry
entry* a;
element example4 = {1, a};
Entry Struct
Entry 是一整个 key + value pair, 分为 simple 和 general 两个类型。我们用 entry 这个
struct 来储存 entries。
例如:
set a 1 2 3
a 1 2 3 是一个 entry,a 是 key,1 2 3 是对应的 value,由三个 integer element 组成。
Entry 分为两个类型:
• Simple Entry
o Values 只包含 integer
• General Entry
o Values 包含其他 entry
a 就是一个 simple entry。用 is_simple 这个变量来衡量这个 entry 是什么类型。
Length:储存 value 的数量
Next:下一个 entry pointer,
Prev: 上一个 entry pointer,
forward_size:有几个 forward entry
forward_max:max forward value
forward: array of forward entries
backward_size
backward_max:max backward value
backward:array of backward entries
Snapshot Struct
Snapshot 是用来存 database 里某一个时间段的所有 entry 的值的,
我们需要做到随时可以 access 某个 snapshot 以及对里面的 entry 进行更改的操作。
entry* entries; // 存这个 snapshot里的 entry array
snapshot* next; // 下一个 snapshot
snapshot* prev; // 上一个 snapshot
推荐步骤
1. 先确保代码能够读取 stdin
fgets(line, MAX_LINE, stdin);
2. 用 strncasecmp() 来比较 case insensitive 输入
E.g.
if (strncasecmp(line, "HELP", 4) == 0){
command_help();
}
3. 根据 command 在 ymirdb.h 文件建立 function declaration
void command_bye();
void command_help();
void command_list_keys();
void command_list_entries();
void command_list_snapshots();
void command_get();
void command_del();
void command_purge();
void command_set();
void command_push();
void command_append();
void command_pick();
void command_pluck();
void command_pop();
void command_drop();
void command_rollback();
void command_checkout();
void command_snapshot();
void command_min();
void command_max();
void command_sum();
void command_len();
void command_rev();
void command_uniq();
void command_sort();
void command_forward();
void command_backward();
void command_type();
a. 注意后续需要根据需求改动函数的参数和返回类型
4. 建立用来储存 snapshot 和 entry 的 array
snapshot ** snapshots = NULL;
int sp_num = 0;
entry ** entries = NULL;
int en_num = 0;
a. 这里因为我们不知道一共会有多少的 snapshot 和 entry,所以这些都需要
用到 malloc/realloc 等函数来调取空间
b. 由于 c 不会知道一个由 pointer 代表的 array 的长度是多少,所以我们需
要再额外用一个变量来储存长度信息
5. 给大家四个函数的代码例子演示一下。