I'm trying to implement a parser for a database file format. Conceptually, I'm trying to define a struct like the following:
struct Database {
schema: Vec<FieldDescriptors>,
records: Vec<Record>,
}
Record
is basically just a Vec<u8>
. In order to extract a column from a record, it needs to refer to a schema (to know which bytes to read). I've tried to implement several designs unsuccessfully:
1) Have the Record
struct store a reference to either the Database
or the schema (stumbled on this answer: Why can't I store a value and a reference to that value in the same struct?, and I understand why it doesn't work).
2) Create different types for the record data (stored in the database struct), and a record that can actually return the appropriate columns(created on demand when needed). A record contains a reference to the data, and a reference to the schema. This worked fine, except that I want to be able to implement the Index
trait to access a record. Unfortunately, index
must return a reference, so I can't return a new proxy object on demand. (also apparently impossible to do currently Implementing Index trait to return a value that is not a reference)
Other options I've considered: storing a copy of the schema with each record which would be wasteful, or storing the schema in a box and storing a reference to it in each record(seems the least onerous, but still unsatisfying).
Am I missing a good solution to this problem?