amebazii/types/enums.rs
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 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
use serde::{Deserialize, Serialize};
use crate::{
error::Error,
util::{hmac_md5, hmac_sha256, md5, sha256},
};
/// Enum representing different image types.
///
/// This enum defines various image types used within the system. The image types
/// are associated with different identifiers, and the enum also includes a fallback
/// type for unknown image types.
///
/// However, note that *image type* refers to the `SubImage` of the firmware image.
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
#[repr(u8)]
pub enum ImageType {
Parttab,
Boot,
FHWSS,
FHWSNS,
FWLS,
Isp,
Voe, // Video output encoder
Wln, // Wireless network ?
Xip, // Executable in place
Wowln, // Wake-on-Wireless-LAN ?
Cinit, // Custom initialization ?
Cpfw,
Unknown = 0x3F,
}
impl TryFrom<u8> for ImageType {
type Error = Error;
/// Attempts to convert a `u8` value to an `ImageType` variant.
///
/// This method tries to map a `u8` value to the corresponding `ImageType` enum variant.
/// If the value is not valid, it returns an error of type `Error::UnknownImageType`.
///
/// # Parameters
/// - `value`: The `u8` value representing the image type.
///
/// # Returns
/// - `ImageType`: A valid `ImageType` variant if the value matches.
/// - `Error::UnknownImageType`: An error if the value does not match any known image type.
///
/// # Example
/// ```
/// use amebazii::types::enums::ImageType;
/// let image_type = ImageType::try_from(1).unwrap();
/// assert_eq!(image_type, ImageType::Boot); // Valid conversion.
/// ```
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(ImageType::Parttab),
1 => Ok(ImageType::Boot),
2 => Ok(ImageType::FHWSS),
3 => Ok(ImageType::FHWSNS),
4 => Ok(ImageType::FWLS),
// REVISIT: mark unsupported images
5 => Ok(ImageType::Isp),
6 => Ok(ImageType::Voe),
7 => Ok(ImageType::Wln),
8 => Ok(ImageType::Xip),
9 => Ok(ImageType::Wowln),
10 => Ok(ImageType::Cinit),
11 => Ok(ImageType::Cpfw),
0x3F => Ok(ImageType::Unknown),
_ => Err(Error::UnknownImageType(value)),
}
}
}
/// Enum representing different section types in memory.
///
/// This enum defines the types of memory sections that can exist, each represented
/// by a specific identifier (u8 value). These sections correspond to various types of
/// memory regions, such as data cache memory (DTCM), instruction cache memory (ITCM),
/// and other specialized memory regions.
///
/// # Variants
/// - `DTCM`: Data tightly coupled memory (0x80).
/// - `ITCM`: Instruction tightly coupled memory (0x81).
/// - `SRAM`: Static RAM (0x82).
/// - `PSRAM`: Pseudo-static RAM (0x83).
/// - `LPDDR`: Low power DDR memory (0x84).
/// - `XIP`: Execute-In-Place memory (0x85), containing raw binary with compiled code.
///
/// The `XIP` variant refers to memory regions that can execute code directly from the memory,
/// without the need to copy the code into RAM.
///
/// # Example
/// ```
/// use amebazii::types::enums::SectionType;
///
/// let section = SectionType::try_from(0x80).unwrap();
/// assert_eq!(section, SectionType::DTCM); // Successfully converts to DTCM.
/// ```
///
/// # Error Handling
/// If the provided value doesn't correspond to a known section type, an error
/// (`Error::UnknownSectionType`) will be returned.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[repr(u8)]
pub enum SectionType {
DTCM = 0x80,
ITCM,
SRAM,
PSRAM,
LPDDR,
/// Execute-In-Place (XIP) contains the raw binary with all
/// compiled code.
XIP,
}
impl TryFrom<u8> for SectionType {
type Error = Error;
/// Tries to convert a `u8` value into a corresponding `SectionType` variant.
///
/// This function maps a `u8` value to its corresponding `SectionType` enum variant.
/// If the value does not match a valid section type, it returns an error with
/// the message indicating an invalid section type.
///
/// # Parameters
/// - `value`: The `u8` value representing the section type.
///
/// # Returns
/// - `SectionType`: A valid `SectionType` variant if the value matches.
/// - `Error::UnknownSectionType`: An error if the value doesn't match a known section type.
///
/// # Example
/// ```
/// use amebazii::types::enums::SectionType;
///
/// let section = SectionType::try_from(0x84).unwrap();
/// assert_eq!(section, SectionType::LPDDR); // Successfully converts to LPDDR.
/// ```
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0x80 => Ok(SectionType::DTCM),
0x81 => Ok(SectionType::ITCM),
0x82 => Ok(SectionType::SRAM),
0x83 => Ok(SectionType::PSRAM),
0x84 => Ok(SectionType::LPDDR),
0x85 => Ok(SectionType::XIP),
_ => Err(Error::UnknownSectionType(format!(
"Invalid section type: {}",
value
))),
}
}
}
/// Available sizes for XIP (Execute-In-Place) page remapping.
///
/// This enum defines different page sizes used in XIP remapping, with each variant
/// representing a specific page size in kilobytes.
///
/// # Variants
/// - `_16K`: Represents a 16 KB page size (0).
/// - `_32K`: Represents a 32 KB page size (1).
/// - `_64K`: Represents a 64 KB page size (2).
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
#[repr(u8)]
pub enum XipPageRemapSize {
#[default]
_16K = 0,
_32K,
_64K,
}
impl TryFrom<u8> for XipPageRemapSize {
type Error = Error;
/// Attempts to convert a `u8` value to an `XipPageRemapSize` variant.
///
/// This method maps a `u8` value to the corresponding `XipPageRemapSize` variant.
/// If the value is not valid, it returns an error with a message indicating the
/// invalid page remap size.
///
/// # Parameters
/// - `value`: The `u8` value representing the XIP page remap size.
///
/// # Returns
/// - `XipPageRemapSize`: The corresponding `XipPageRemapSize` variant if the value matches.
/// - `Error::InvalidEnumValue`: An error if the value doesn't match a valid remap size.
///
/// # Example
/// ```
/// use amebazii::types::enums::XipPageRemapSize;
///
/// let size = XipPageRemapSize::try_from(2).unwrap();
/// assert_eq!(size, XipPageRemapSize::_64K); // Successfully converts to 64 KB.
/// ```
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(XipPageRemapSize::_16K),
1 => Ok(XipPageRemapSize::_32K),
2 => Ok(XipPageRemapSize::_64K),
_ => Err(Error::InvalidEnumValue(format!(
"Invalid XIP page remap size: {}",
value
))),
}
}
}
impl XipPageRemapSize {
/// Returns the size of the page in bytes for the given `XipPageRemapSize` variant.
///
/// This function returns the page size corresponding to the variant in bytes.
/// The page sizes are predefined as 16 KB, 32 KB, and 64 KB.
///
/// # Returns
/// - `u32`: The page size in bytes.
pub fn page_size(&self) -> u32 {
match self {
XipPageRemapSize::_16K => 0x4000,
XipPageRemapSize::_32K => 0x8000,
XipPageRemapSize::_64K => 0x10000,
}
}
}
// Defined in parse_json_config
/// Supported encryption algorithms.
///
/// This enum defines the supported encryption algorithms, each represented by a specific
/// identifier (u16 value). The available algorithms include `Ecb` (Electronic Codebook),
/// `Cbc` (Cipher Block Chaining), and `Other` for any unspecified or custom algorithms.
///
/// # Variants
/// - `Ecb`: Electronic Codebook mode encryption (0).
/// - `Cbc`: Cipher Block Chaining mode encryption (1).
/// - `Other`: Represents other custom or unsupported encryption algorithms (0xFF).
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]
#[repr(u16)]
pub enum EncryptionAlgo {
Ecb,
Cbc,
#[default]
Other = 0xFF,
}
impl TryFrom<u16> for EncryptionAlgo {
type Error = Error;
/// Tries to convert a `u16` value to an `EncryptionAlgo` variant.
///
/// # Parameters
/// - `value`: The `u16` value representing the encryption algorithm.
///
/// # Returns
/// - `Ok(EncryptionAlgo)`: The corresponding `EncryptionAlgo` variant if the value matches.
/// - `Err(Error::InvalidEnumValue)`: An error if the value doesn't match a valid encryption algorithm.
///
/// # Example
/// ```
/// use amebazii::types::enums::EncryptionAlgo;
///
/// let algo = EncryptionAlgo::try_from(0).unwrap();
/// assert_eq!(algo, EncryptionAlgo::Ecb); // Successfully converts to Ecb.
/// ```
fn try_from(value: u16) -> Result<Self, Self::Error> {
match value {
0 => Ok(EncryptionAlgo::Ecb),
1 => Ok(EncryptionAlgo::Cbc),
0xFF => Ok(EncryptionAlgo::Other),
_ => Err(Error::InvalidEnumValue(format!(
"Invalid encryption algorithm: {}",
value
))),
}
}
}
// --- Hash Algorithms ---
// Defined in parse_json_config
/// Supported various hash algorithms.
///
/// This enum defines the supported hash algorithms, each represented by a specific
/// identifier (u16 value). The available algorithms include `Md5`, `Sha256`, and `Other`
/// for unspecified or custom algorithms.
///
/// # Variants
/// - `Md5`: MD5 hash algorithm (0x00).
/// - `Sha256`: SHA-256 hash algorithm (0x01).
/// - `Other`: Represents other custom or unsupported hash algorithms (0xFF).
///
/// # Example
/// ```
/// use amebazii::types::enums::HashAlgo;
///
/// let algo = HashAlgo::try_from(1).unwrap();
/// assert_eq!(algo, HashAlgo::Sha256); // Successfully converts to Sha256.
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]
#[repr(u16)]
pub enum HashAlgo {
Md5 = 0x00,
Sha256,
#[default]
Other = 0xFF,
}
impl TryFrom<u16> for HashAlgo {
type Error = Error;
/// Tries to convert a `u16` value to a corresponding `HashAlgo` variant.
///
/// # Parameters
/// - `value`: The `u16` value representing the hash algorithm.
///
/// # Returns
/// - `Ok(HashAlgo)`: The corresponding `HashAlgo` variant if the value matches.
/// - `Err(Error::InvalidEnumValue)`: An error if the value doesn't match a valid hash algorithm.
fn try_from(value: u16) -> Result<Self, Self::Error> {
match value {
0 => Ok(HashAlgo::Md5),
1 => Ok(HashAlgo::Sha256),
0xFF => Ok(HashAlgo::Other),
_ => Err(Error::InvalidEnumValue(format!(
"Invalid hash algorithm: {}",
value
))),
}
}
}
impl HashAlgo {
/// Computes the hash of the provided buffer using the specified algorithm.
///
/// If a key is provided, HMAC (Hash-based Message Authentication Code) is used.
///
/// # Parameters
/// - `buffer`: A byte slice containing the data to be hashed.
/// - `key`: An optional byte slice containing the key for HMAC. If `None`, the raw hash is computed.
///
/// # Returns
/// - `Ok(Vec<u8>)`: The computed hash as a vector of bytes.
/// - `Err(Error::UnsupportedHashAlgo)`: An error if an unsupported hash algorithm is chosen.
///
/// # Example
/// ```
/// use amebazii::types::enums::HashAlgo;
///
/// let data = b"some data to hash";
/// let algo = HashAlgo::Md5;
/// let result = algo.compute_hash(data, None).unwrap();
/// assert_eq!(result.len(), 16); // MD5 produces a 16-byte hash.
/// ```
pub fn compute_hash(&self, buffer: &[u8], key: Option<&[u8]>) -> Result<Vec<u8>, Error> {
match self {
HashAlgo::Sha256 => match key {
Some(key_data) => {
return Ok(hmac_sha256(&key_data, &buffer)?.to_vec());
}
None => {
return Ok(sha256(&buffer)?.to_vec());
}
},
HashAlgo::Md5 => match key {
Some(key_data) => {
return Ok(hmac_md5(&key_data, &buffer)?.to_vec());
}
None => {
return Ok(md5(&buffer)?.to_vec());
}
},
_ => {
return Err(Error::UnsupportedHashAlgo(*self as u8));
}
}
}
}
/// Enum representing all different types of partitions. (as per _convert_pt_type)
///
/// # Variants
/// - `PartTab`: Partition table (0).
/// - `Boot`: Boot partition (1).
/// - `Sys`: System partition (2).
///
/// - `Fw1`: Firmware partition 1.
/// - `Fw2`: Firmware partition 2.
/// - `Cal`: Calibration partition (5).
/// - `User`: User data partition (6).
/// - `Var`: Variable partition (7).
/// - `MP`: Main partition (8).
/// - `Rdp`: Reserved partition (9).
///
/// # Example
/// ```
/// use amebazii::types::enums::PartitionType;
///
/// let part = PartitionType::try_from(1).unwrap();
/// assert_eq!(part, PartitionType::Boot); // Successfully converts to Boot partition.
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[repr(u8)]
pub enum PartitionType {
/// Partition table (0).
PartTab = 0,
/// Boot partition (1).
Boot,
/// System partition (4).
Sys,
/// Calibration partition (5).
Cal,
/// User data partition (6).
User,
/// Firmware partition 1 (2).
Fw1,
/// Firmware partition 2 (3).
Fw2,
/// Variable partition (7).
Var,
/// Main partition (8).
MP,
/// Reserved partition (9).
Rdp,
Unknown = 10,
}
impl TryFrom<u8> for PartitionType {
type Error = Error;
/// Attempts to convert a `u8` value to the corresponding `PartitionType` variant.
///
/// This method maps a `u8` value to the appropriate `PartitionType` variant.
/// If the value is not valid, it returns an error indicating that the partition type
/// is invalid.
///
/// # Parameters
/// - `value`: The `u8` value representing the partition type.
///
/// # Returns
/// - `Ok(PartitionType)`: The corresponding `PartitionType` variant if the value matches.
/// - `Err(Error::InvalidEnumValue)`: An error if the value doesn't match a valid partition type.
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(PartitionType::PartTab),
1 => Ok(PartitionType::Boot),
2 => Ok(PartitionType::Sys),
3 => Ok(PartitionType::Cal),
4 => Ok(PartitionType::User),
5 => Ok(PartitionType::Fw1),
6 => Ok(PartitionType::Fw2),
7 => Ok(PartitionType::Var),
8 => Ok(PartitionType::MP),
9 => Ok(PartitionType::Rdp),
10 => Ok(PartitionType::Unknown),
_ => Err(Error::InvalidEnumValue(format!(
"Invalid partition type: {}",
value
))),
}
}
}
/// Enum representing different key export operations.
///
/// This enum defines the operations for key export, represented by a specific `u8` value.
/// The available operations include:
/// - `None`: No key export operation (0).
/// - `Latest`: Export the latest key (1).
/// - `Both`: Export both keys (2).
///
/// # Variants
/// - `None`: No key export operation (0).
/// - `Latest`: Only export the latest key (1).
/// - `Both`: Export both the latest and previous keys (2).
///
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default)]
#[repr(u8)]
pub enum KeyExportOp {
/// No key export operation (0).
#[default]
None = 0,
/// Export the latest key (1).
Latest,
/// Export both keys (2).
Both,
}
impl TryFrom<u8> for KeyExportOp {
type Error = Error;
/// Tries to convert a `u8` value to the corresponding `KeyExportOp` variant.
///
/// # Parameters
/// - `value`: The `u8` value representing the key export operation.
///
/// # Returns
/// - `Ok(KeyExportOp)`: The corresponding `KeyExportOp` variant if the value matches.
/// - `Err(Error::InvalidEnumValue)`: An error if the value doesn't match a valid key export operation.
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(KeyExportOp::None),
1 => Ok(KeyExportOp::Latest),
2 => Ok(KeyExportOp::Both),
_ => Err(Error::InvalidEnumValue(format!(
"Invalid key export type: {}",
value
))),
}
}
}
/// Represents different flash sizes based on the corresponding size codes.
///
/// This enum defines the possible flash sizes, each represented by a specific
/// 16-bit value. The sizes range from 2MB to 1MB, with different values for each
/// size. The default value corresponds to a 2MB flash size.
#[allow(non_camel_case_types)]
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Default)]
#[repr(u16)]
pub enum FlashSize {
#[default]
Size_2M = 0xFFFF,
Size_32M = 0x7FFF,
Size_16M = 0x3FFF,
Size_8M = 0x1FFF,
Size_4M = 0x0FFF,
Size_1M = 0x07FF,
}
impl From<u16> for FlashSize {
/// Converts a 16-bit value into a `FlashSize` enum.
///
/// # Arguments:
/// - `value`: A 16-bit unsigned integer representing a flash size.
///
/// # Returns:
/// - The corresponding `FlashSize` enum variant.
fn from(value: u16) -> Self {
match value {
0xFFFF => FlashSize::Size_2M,
0x7FFF => FlashSize::Size_32M,
0x3FFF => FlashSize::Size_16M,
0x1FFF => FlashSize::Size_8M,
0x0FFF => FlashSize::Size_4M,
0x07FF => FlashSize::Size_1M,
_ => FlashSize::Size_2M,
}
}
}
/// Represents different SPI I/O modes used for communication with flash memory.
///
/// This enum defines the supported SPI I/O modes for flash memory. These modes
/// control how data is transferred between the device and the memory. The default
/// value is `Quad_IO`, which uses four data lines for transfer.
#[allow(non_camel_case_types)]
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Default)]
#[repr(u16)]
pub enum SpiIOMode {
#[default]
Quad_IO = 0xFFFF,
Quad_Output = 0x7FFF,
Dual_IO = 0x3FFF,
Dual_Output = 0x1FFF,
One_IO = 0x0FFF,
}
impl From<u16> for SpiIOMode {
/// Converts a 16-bit value into a `SpiIOMode` enum.
///
/// # Arguments:
/// - `value`: A 16-bit unsigned integer representing an SPI I/O mode.
///
/// # Returns:
/// - The corresponding `SpiIOMode` enum variant.
fn from(value: u16) -> Self {
match value {
0xFFFF => SpiIOMode::Quad_IO,
0x7FFF => SpiIOMode::Quad_Output,
0x3FFF => SpiIOMode::Dual_IO,
0x1FFF => SpiIOMode::Dual_Output,
0x0FFF => SpiIOMode::One_IO,
_ => SpiIOMode::Quad_IO,
}
}
}
/// Represents different SPI clock speeds for communication with flash memory.
///
/// This enum defines the supported SPI speeds for flash memory communication.
/// The speeds range from 100MHz down to 25MHz, with 100MHz being the default.
///
/// C Structure:
/// - [hal_sys_ctrl.h#L94](https://github.com/Ameba-AIoT/ameba-rtos-z2/blob/302d27d3a393e7ef3739d94d0bb0cf2a4c9bc40d/component/soc/realtek/8710c/fwlib/include/hal_sys_ctrl.h#L94)
#[derive(Debug, Copy, Clone, Serialize, Deserialize, Default)]
#[repr(u16)]
pub enum SpiSpeed {
#[default]
_100MHz = 0xFFFF,
_50MHz = 0x7FFF,
_25MHz = 0x3FFF,
}
impl From<u16> for SpiSpeed {
/// Converts a 16-bit value into a `SpiSpeed` enum.
///
/// # Arguments:
/// - `value`: A 16-bit unsigned integer representing an SPI clock speed.
///
/// # Returns:
/// - The corresponding `SpiSpeed` enum variant.
fn from(value: u16) -> Self {
match value {
0xFFFF => SpiSpeed::_100MHz,
0x7FFF => SpiSpeed::_50MHz,
0x3FFF => SpiSpeed::_25MHz,
_ => SpiSpeed::_100MHz,
}
}
}