riscy_isa/encoding_stream.rs
1use crate::Instruction;
2
3/// Encodes a sequence of RISC-V [instructions](Instruction), turning them into bytes.
4///
5/// # Example
6/// To use this you'll want to create a stream using `EncodingStream::new()`,
7/// then push each instruction in sequence using `push()`. When you're done, you
8/// can get the encoded bytes using `bytes()`.
9///
10/// ```
11/// use riscy_isa::{Instruction, Opcode, OpImmFunction, EncodingStream, Register};
12/// let mut stream = EncodingStream::new();
13/// stream.push(&Instruction::I {
14/// opcode: Opcode::OpImm(OpImmFunction::ADDI),
15/// rd: Register::A0,
16/// rs1: Register::Zero,
17/// imm: 0,
18/// });
19/// assert_eq!(stream.bytes(), &[19, 5, 0, 0]);
20/// ```
21pub struct EncodingStream {
22 bytes: Vec<u8>,
23}
24
25impl EncodingStream {
26 pub fn new() -> Self {
27 Self { bytes: Vec::new() }
28 }
29
30 pub fn push(&mut self, instruction: &Instruction) {
31 self.bytes.append(&mut instruction.bytes());
32 }
33
34 pub fn bytes(&self) -> &[u8] {
35 &self.bytes
36 }
37}