D中的自动数据持久性

Nor*_*löw 3 reflection persistence d object

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

@persistent int x = 1;
Run Code Online (Sandbox Code Playgroud)

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

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

Ada*_*ppe 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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