by enitihas · 6y ago · 0 comments
The only place where I couldn't find a zero cost abstraction was enum encoding, where enums are of different sizes.
For example
pub enum OpCode { OpReturn, OpConstant(u8), OpNegate, OpAdd, ... }
It would be great if the compiler could use only 1 byte for the rest of the enums other than OpConstant, and more bytes for OpConstant, and use maybe the first 2 bits to store the number of bytes used, kind of like sds library by antirez. This is the only place where I felt my rust implementation was less efficient than the book's c implementation.
Off course, I could go the same route as the c code, and not use type safe enums by just keeping an array of bytes and doing the decoding myself, but I wanted to have full compile time type safety.
Unfortunately, variable-sized types interact poorly with arrays -- you can no longer access any element in constant time. UTF-8 has essentially the same issue.
Did you end up abstracting over the byte array at all? I would imagine that some kind of `BytecodeBuffer` could give pretty reasonable ergonomics over a raw buffer without sacrificing efficiency or correctness.
Unsized types interact badly with everything, really. That's why you usually shove them behind a pointer.