BSON.jl
BSON.jl copied to clipboard
Reconstruct Types
Hello, one of the features for using BSON you mention is the backwards compatibility. But I have a very general question about this.
Suppose I save a type (struct) which is designed in a certain way and comes from a package, like this:
struct Foo
foo::String
bar::Int
end
After some time the design of this structure changes due to some improvements of the package or whatever...
struct Foo
foo::String
bar::Int
added_feature::Float64
end
Now I will not be able to load my old saved BSON file anymore because I cannot reproduce the right struct in my environment and I cannot recreate it from the saved data because BSON does not load anything.
I do not expect that a reconstructed struct will work properly but at least it would be great if it still would be possible to load it and, e.g., define a conversion method or just extract some data.
You could define a conversion method by creating BSON.newstruct!(x::Foo, fs...)
In this example, it would be
function BSON.newstruct!(x::Foo, fs...)
for (i, f) = enumerate(fs)
f = convert(fieldtype(typeof(x),i), f)
ccall(:jl_set_nth_field, Nothing, (Any, Csize_t, Any), x, i-1, f)
end
# initialise added_feature
val = 100.0
index = 3
ccall(:jl_set_nth_field, Nothing, (Any, Csize_t, Any), x, index-1, val)
return x
end