将库存移植到 C
Coddy 面向 C 开发者的 Lua 课程的第 47 课,共 48 课。
挑战
中等C 版本使用一个动态数组来存储条目,并为每个条目分配一个名称。输出结果后,它会释放这些内存分配。Lua 表取代了这种存储管理方式;请保留聚合和排序行为。
将参考 C 程序移植为 Lua 模块。每一行输入都由一个小写 ASCII 名称、一个冒号和一个带符号的整数增量组成。按名称聚合,只保留最终总数为正数的项,按名称升序排序,并返回用逗号连接的 name=total 条目。如果没有剩余项,则返回 empty。在 inventory.lua 中实现 inventory.aggregate(lines);由 app 格式化结果。所有输入行的格式都正确。
C 参考程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <errno.h>
struct Entry { char *name; long total; };
/* The caller owns each returned line, including a final line without newline. */
static int read_line(char **out) {
size_t length = 0, capacity = 32;
char *line = malloc(capacity);
int ch;
if (line == NULL) return -1;
while ((ch = getchar()) != EOF && ch != '\n') {
if (length == capacity - 1) {
if (capacity > SIZE_MAX / 2) { free(line); return -1; }
capacity *= 2;
char *grown = realloc(line, capacity);
if (grown == NULL) { free(line); return -1; }
line = grown;
}
line[length++] = (char)ch;
}
if (ferror(stdin)) { free(line); return -1; }
if (ch == EOF && length == 0) { free(line); return 0; }
line[length] = '\0';
*out = line;
return 1;
}
static int by_name(const void *left, const void *right) {
const struct Entry *a = left, *b = right;
return strcmp(a->name, b->name);
}
int main(void) {
struct Entry *entries = NULL;
size_t count = 0;
int status = 0, result;
char *line = NULL;
while ((result = read_line(&line)) == 1) {
char *separator = strchr(line, ':');
if (separator == NULL || separator == line) { status = 1; break; }
*separator = '\0';
for (const char *p = line; *p != '\0'; ++p)
if (*p < 'a' || *p > 'z') status = 1;
const char *digits = separator + 1;
if (*digits == '-') ++digits;
if (*digits == '\0') status = 1;
for (const char *p = digits; *p != '\0'; ++p)
if (*p < '0' || *p > '9') status = 1;
errno = 0;
char *end;
long delta = strtol(separator + 1, &end, 10);
if (status || errno == ERANGE || *end != '\0') { status = 1; break; }
size_t index = 0;
while (index < count && strcmp(entries[index].name, line) != 0) ++index;
if (index == count) {
if (count == SIZE_MAX / sizeof *entries) { status = 1; break; }
struct Entry *grown = realloc(entries, (count + 1) * sizeof *entries);
if (grown == NULL) { status = 1; break; }
entries = grown;
entries[count++] = (struct Entry){line, 0};
line = NULL; /* Transfer ownership to the new entry. */
}
long old = entries[index].total;
if ((delta > 0 && old > LONG_MAX - delta) ||
(delta < 0 && old < LONG_MIN - delta)) { status = 1; break; }
entries[index].total += delta;
free(line);
line = NULL;
}
if (result < 0) status = 1;
free(line);
if (!status) {
if (count > 1) qsort(entries, count, sizeof *entries, by_name);
int printed = 0;
for (size_t i = 0; i < count; ++i) {
if (entries[i].total > 0) {
printf("%s%s=%ld", printed ? "," : "", entries[i].name, entries[i].total);
printed = 1;
}
}
if (!printed) fputs("empty", stdout);
putchar('\n');
}
for (size_t i = 0; i < count; ++i) free(entries[i].name);
free(entries);
return status || ferror(stdout);
}
编辑 app.lua、inventory.lua。可见的锁定文件 main.lua 会从标准输入读取内容并整理成行序列,调用 app.run(lines),然后输出其返回值,并在末尾添加一个换行符。不要输出诊断信息,也不要更改模块名称。空输入会得到一个空序列。所有数值输入都足够小,不会溢出。
公共 API 检查:inventory.aggregate(lines) 会返回一个新表,其中包含带符号增量的求和结果,并保留总数为零的项。空输入会得到一个空表。格式化和筛选由 app 完成。锁定的驱动程序会在调用 app.run 之前检查此行为。检查成功时不会输出任何内容。
亲手试试
-- 公共 API 检查
do
local inventory=require("inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
end
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
面向 C 开发者的 Lua中的所有课
自己练习: Lua 在线编译器