D中的自动数据持久性

时间:2014-01-05 11:17:43

标签: object reflection persistence d

有人想过在D中实现某种自动数据(对象)持久性吗?我对这个问题的理想解决方案是:

@persistent int x = 1;

这对于静态变量大多数都是无效的,但动态变量也是可能的。

这些变量将存储在键值存储数据库中。键可以是基于范围变量名称和类型的指纹摘要加上当前加载的代码的一些摘要。

1 个答案:

答案 0 :(得分:11)

你可以做一些与模板类似的事情。看看这个:

import std.stdio;

// do not declare two of these on the same line or they'll get mixed up
struct persistent(Type, string file = __FILE__, size_t line = __LINE__) {
    Type info;
    alias info this;

    // require an initializer
    @disable this();

    // with the initializer
    this(Type t) {
        // if it is in the file, we should load it here
        // else...
        info = t;
    }
    ~this() {
        // you should actually save it to the file
        writeln("Saving ", info, " as key ",
            file,":",line);
    }
}

void main() {
    persistent!int x = 10;
}

如果你运行它,你会看到initalizer和write,如果你填写了文件支持(可能是json使用键和值,或者其他一些序列化程序来处理更多类型),它应该能够保存。您还可以将dtor保存到全局缓冲区,然后让模块析构函数实际将其保存到文件中(并且模块构造函数也加载文件),因此它不会尝试在每个函数调用上读/写文件。

所有变量都将表现为静态变量,因为您可以看到此处的键是声明的文件和行号,没有环境输入。但是,嘿,这很简单,应该可行。