Sharing a schema with structure children

I am trying to implement a parser for a database file format. Ok, I am trying to define a structure like this:

struct Database {
    schema: Vec<FieldDescriptors>,
    records: Vec<Record>,
}

      

Record

basically just a Vec<u8>

. To retrieve a column from a record, you need to refer to the schema (to find out which bytes to read). I have tried several projects with no success:

1) Store the Record

struct store a reference to Database

either a schema or a schema (came across 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 record data (stored in the database structure) and a record that can actually return the corresponding columns (created on demand when needed). The record contains a link to the data and a link to the schema. This worked well, except that I want to be able to use a trait Index

to access the record. Unfortunately, Index

must return a reference, so I cannot return a new proxy object on demand. (also apparently not possible to do currently Implementing Index Pointer to return a value that is not a reference )

Other options I considered: keeping a copy of the schema with each entry, which would be wasteful, or saving the schema in a box and storing a reference to it in each entry (seems least cumbersome but still unsatisfactory).

Is there a good solution to this problem?

+3


source to share


1 answer


You haven't posted very much code, but I'm guessing you wanted to get the column information from a record using something like:

impl Record {
   fn get_column(&self, index: usize) -> Column {
       // use self.schema to get the column...
   }
}

      



A completely different design would have to associate this code with the schema instead and pass &Record

it when you need the schema to do something on it. You can protect any user from having to access the schema directly by using a facade, which can be Database

itself:

struct Schema {
   field_descriptors: Vec<FieldDescriptors>
}

struct Database {
    schema: Schema,
    records: Vec<Record>,
}

impl Schema {
    fn get_column(&self, record: &Record, index: usize) -> Column {
        // use self.field_descriptors to get the column...
    }
}

impl Database {
    fn get_column(&self, row: usize, col_index: usize) -> Column {
        schema.get_column(&self.records[row], col_index)
    }
}

      

0


source







All Articles