1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
 * Copyright 2018 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use crate::endian_scalar::read_scalar_at;
use crate::follow::Follow;
use crate::primitives::*;

/// VTable encapsulates read-only usage of a vtable. It is only to be used
/// by generated code.
#[derive(Debug)]
pub struct VTable<'a> {
    buf: &'a [u8],
    loc: usize,
}

impl<'a> PartialEq for VTable<'a> {
    fn eq(&self, other: &VTable) -> bool {
        self.as_bytes().eq(other.as_bytes())
    }
}

impl<'a> VTable<'a> {
    /// SAFETY
    /// `buf` must contain a valid vtable at `loc`
    ///
    /// This consists of a number of `VOffsetT`
    /// - size of vtable in bytes including size element
    /// - size of object in bytes including the vtable offset
    /// - n fields where n is the number of fields in the table's schema when the code was compiled
    pub unsafe fn init(buf: &'a [u8], loc: usize) -> Self {
        VTable { buf, loc }
    }

    pub fn num_fields(&self) -> usize {
        (self.num_bytes() / SIZE_VOFFSET) - 2
    }

    pub fn num_bytes(&self) -> usize {
        // Safety:
        // Valid VTable at time of construction
        unsafe { read_scalar_at::<VOffsetT>(self.buf, self.loc) as usize }
    }

    pub fn object_inline_num_bytes(&self) -> usize {
        // Safety:
        // Valid VTable at time of construction
        let n = unsafe { read_scalar_at::<VOffsetT>(self.buf, self.loc + SIZE_VOFFSET) };
        n as usize
    }

    pub fn get_field(&self, idx: usize) -> VOffsetT {
        // TODO(rw): distinguish between None and 0?
        if idx > self.num_fields() {
            return 0;
        }

        // Safety:
        // Valid VTable at time of construction
        unsafe {
            read_scalar_at::<VOffsetT>(
                self.buf,
                self.loc + SIZE_VOFFSET + SIZE_VOFFSET + SIZE_VOFFSET * idx,
            )
        }
    }

    pub fn get(&self, byte_loc: VOffsetT) -> VOffsetT {
        // TODO(rw): distinguish between None and 0?
        if byte_loc as usize + 2 > self.num_bytes() {
            return 0;
        }
        // Safety:
        // byte_loc is within bounds of vtable, which was valid at time of construction
        unsafe { read_scalar_at::<VOffsetT>(self.buf, self.loc + byte_loc as usize) }
    }

    pub fn as_bytes(&self) -> &[u8] {
        let len = self.num_bytes();
        &self.buf[self.loc..self.loc + len]
    }
}

#[allow(dead_code)]
pub fn field_index_to_field_offset(field_id: VOffsetT) -> VOffsetT {
    // Should correspond to what end_table() below builds up.
    let fixed_fields = 2; // Vtable size and Object Size.
    ((field_id + fixed_fields) * (SIZE_VOFFSET as VOffsetT)) as VOffsetT
}

#[allow(dead_code)]
pub fn field_offset_to_field_index(field_o: VOffsetT) -> VOffsetT {
    debug_assert!(field_o >= 2);
    let fixed_fields = 2; // VTable size and Object Size.
    (field_o / (SIZE_VOFFSET as VOffsetT)) - fixed_fields
}

impl<'a> Follow<'a> for VTable<'a> {
    type Inner = VTable<'a>;
    unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
        VTable::init(buf, loc)
    }
}