You are given a text definition of a message schema and a table of primitive types with their byte sizes. Implement a parser and expose two query functions:
-
get_size(name)
: returns the size in bytes of either:
-
a primitive type (e.g.,
"int"
), or
-
a field name defined in the message, or
-
the message type/name itself (total size = sum of its fields’ sizes).
-
get_type(field_name)
: returns the declared type of the given field.
Schema format
The schema is provided as a multi-line string. Example:
Message:
field_name field_type
field_name2 field_type2
-
The first non-empty line is the message header (
Message:
). Treat the message type/name as
"Message"
.
-
Each subsequent non-empty line contains exactly two tokens:
<field_name> <field_type>
.
-
<field_type>
is a primitive type listed in the primitives table.
Primitives table
You are given a map/dictionary like:
-
float -> 8
-
int -> 4
-
char -> 4
Requirements
-
Parse the schema and store enough information to answer queries efficiently.
-
get_size("Message")
returns the total size of the message (sum of sizes of each field’s type).
-
get_size(field_name)
returns the size of that field’s type.
-
get_type(field_name)
returns the type string for that field.
-
get_size(primitive_type)
returns the size from the primitives table.
Assumptions / edge behavior (make explicit in your implementation)
-
If a queried field/type does not exist, you may either raise an error/exception or return a sentinel value (e.g.,
-1
/
null
), but be consistent.
-
Field names are unique within the message.
-
Whitespace and blank lines may appear and should be ignored.
Example
Given schema:
Message:
price float
qty int
and primitives {float: 8, int: 4}:
-
get_type("price") -> "float"
-
get_size("price") -> 8
-
get_size("Message") -> 12
-
get_size("int") -> 4
Implement the parser and these two query functions.