blob: 0931e6855d7171502681abafb77838de0e11d30b [file] [log] [blame]
Janis Danisevskisc51dff82021-10-20 09:51:16 -07001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Implements utility functions and types for diced and the dice HAL.
16
Janis Danisevskisc51dff82021-10-20 09:51:16 -070017/// This submodule implements a limited set of CBOR generation functionality. Essentially,
18/// a cbor header generator and some convenience functions for number and BSTR encoding.
19pub mod cbor {
20 use anyhow::{anyhow, Context, Result};
21 use std::convert::TryInto;
22 use std::io::Write;
23
24 /// CBOR encodes a positive number.
25 pub fn encode_number(n: u64, buffer: &mut dyn Write) -> Result<()> {
26 encode_header(0, n, buffer)
27 }
28
29 /// CBOR encodes a binary string.
30 pub fn encode_bstr(bstr: &[u8], buffer: &mut dyn Write) -> Result<()> {
31 encode_header(
32 2,
33 bstr.len().try_into().context("In encode_bstr: Failed to convert usize to u64.")?,
34 buffer,
35 )
36 .context("In encode_bstr: While writing header.")?;
37 let written = buffer.write(bstr).context("In encode_bstr: While writing payload.")?;
38 if written != bstr.len() {
39 return Err(anyhow!("In encode_bstr: Buffer too small. ({}, {})", written, bstr.len()));
40 }
41 Ok(())
42 }
43
44 /// Formats a CBOR header. `t` is the type, and n is the header argument.
45 pub fn encode_header(t: u8, n: u64, buffer: &mut dyn Write) -> Result<()> {
46 match n {
47 n if n < 24 => {
Charisee03e00842023-01-25 01:41:23 +000048 let written =
49 buffer.write(&u8::to_be_bytes((t << 5) | (n as u8 & 0x1F))).with_context(
50 || format!("In encode_header: Failed to write header ({}, {})", t, n),
51 )?;
Janis Danisevskisc51dff82021-10-20 09:51:16 -070052 if written != 1 {
53 return Err(anyhow!("In encode_header: Buffer to small. ({}, {})", t, n));
54 }
55 }
56 n if n <= 0xFF => {
57 let written =
Charisee03e00842023-01-25 01:41:23 +000058 buffer.write(&u8::to_be_bytes((t << 5) | (24u8 & 0x1F))).with_context(
Janis Danisevskisc51dff82021-10-20 09:51:16 -070059 || format!("In encode_header: Failed to write header ({}, {})", t, n),
60 )?;
61 if written != 1 {
62 return Err(anyhow!("In encode_header: Buffer to small. ({}, {})", t, n));
63 }
64 let written = buffer.write(&u8::to_be_bytes(n as u8)).with_context(|| {
65 format!("In encode_header: Failed to write size ({}, {})", t, n)
66 })?;
67 if written != 1 {
68 return Err(anyhow!(
69 "In encode_header while writing size: Buffer to small. ({}, {})",
70 t,
71 n
72 ));
73 }
74 }
75 n if n <= 0xFFFF => {
76 let written =
Charisee03e00842023-01-25 01:41:23 +000077 buffer.write(&u8::to_be_bytes((t << 5) | (25u8 & 0x1F))).with_context(
Janis Danisevskisc51dff82021-10-20 09:51:16 -070078 || format!("In encode_header: Failed to write header ({}, {})", t, n),
79 )?;
80 if written != 1 {
81 return Err(anyhow!("In encode_header: Buffer to small. ({}, {})", t, n));
82 }
83 let written = buffer.write(&u16::to_be_bytes(n as u16)).with_context(|| {
84 format!("In encode_header: Failed to write size ({}, {})", t, n)
85 })?;
86 if written != 2 {
87 return Err(anyhow!(
88 "In encode_header while writing size: Buffer to small. ({}, {})",
89 t,
90 n
91 ));
92 }
93 }
94 n if n <= 0xFFFFFFFF => {
95 let written =
Charisee03e00842023-01-25 01:41:23 +000096 buffer.write(&u8::to_be_bytes((t << 5) | (26u8 & 0x1F))).with_context(
Janis Danisevskisc51dff82021-10-20 09:51:16 -070097 || format!("In encode_header: Failed to write header ({}, {})", t, n),
98 )?;
99 if written != 1 {
100 return Err(anyhow!("In encode_header: Buffer to small. ({}, {})", t, n));
101 }
102 let written = buffer.write(&u32::to_be_bytes(n as u32)).with_context(|| {
103 format!("In encode_header: Failed to write size ({}, {})", t, n)
104 })?;
105 if written != 4 {
106 return Err(anyhow!(
107 "In encode_header while writing size: Buffer to small. ({}, {})",
108 t,
109 n
110 ));
111 }
112 }
113 n => {
114 let written =
Charisee03e00842023-01-25 01:41:23 +0000115 buffer.write(&u8::to_be_bytes((t << 5) | (27u8 & 0x1F))).with_context(
Janis Danisevskisc51dff82021-10-20 09:51:16 -0700116 || format!("In encode_header: Failed to write header ({}, {})", t, n),
117 )?;
118 if written != 1 {
119 return Err(anyhow!("In encode_header: Buffer to small. ({}, {})", t, n));
120 }
Charisee03e00842023-01-25 01:41:23 +0000121 let written = buffer.write(&u64::to_be_bytes(n)).with_context(|| {
Janis Danisevskisc51dff82021-10-20 09:51:16 -0700122 format!("In encode_header: Failed to write size ({}, {})", t, n)
123 })?;
124 if written != 8 {
125 return Err(anyhow!(
126 "In encode_header while writing size: Buffer to small. ({}, {})",
127 t,
128 n
129 ));
130 }
131 }
132 }
133 Ok(())
134 }
135
136 #[cfg(test)]
137 mod test {
138 use super::*;
139
140 fn encode_header_helper(t: u8, n: u64) -> Vec<u8> {
141 let mut b: Vec<u8> = vec![];
142 encode_header(t, n, &mut b).unwrap();
143 b
144 }
145
146 #[test]
147 fn encode_header_test() {
148 assert_eq!(&encode_header_helper(0, 0), &[0b000_00000]);
149 assert_eq!(&encode_header_helper(0, 23), &[0b000_10111]);
150 assert_eq!(&encode_header_helper(0, 24), &[0b000_11000, 24]);
151 assert_eq!(&encode_header_helper(0, 0xff), &[0b000_11000, 0xff]);
152 assert_eq!(&encode_header_helper(0, 0x100), &[0b000_11001, 0x01, 0x00]);
153 assert_eq!(&encode_header_helper(0, 0xffff), &[0b000_11001, 0xff, 0xff]);
154 assert_eq!(&encode_header_helper(0, 0x10000), &[0b000_11010, 0x00, 0x01, 0x00, 0x00]);
155 assert_eq!(
156 &encode_header_helper(0, 0xffffffff),
157 &[0b000_11010, 0xff, 0xff, 0xff, 0xff]
158 );
159 assert_eq!(
160 &encode_header_helper(0, 0x100000000),
161 &[0b000_11011, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00]
162 );
163 assert_eq!(
164 &encode_header_helper(0, 0xffffffffffffffff),
165 &[0b000_11011, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
166 );
167 }
168 }
169}