Improve VGA palette parser (#604)

* Improve VGA palette parser

* Refactor code with test

* Rewrite test
This commit is contained in:
Vincent Ollivier 2024-03-22 14:45:33 +01:00 committed by GitHub
parent 3895f4618c
commit 9143355cc4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 25 additions and 6 deletions

View File

@ -54,7 +54,7 @@ pub fn from_csv(s: &str) -> Result<Palette, ()> {
}
#[test_case]
fn parse_palette_csv() {
fn test_from_csv() {
assert!(from_csv("").is_err());
assert!(from_csv("0,0,0,0").is_err());

View File

@ -8,6 +8,7 @@ use bit_field::BitField;
use core::cmp;
use core::fmt;
use core::fmt::Write;
use core::num::ParseIntError;
use lazy_static::lazy_static;
use spin::Mutex;
use vte::{Params, Parser, Perform};
@ -271,6 +272,18 @@ fn vga_color(color: u8) -> u8 {
color >> 2
}
fn parse_palette(palette: &str) -> Result<(usize, u8, u8, u8), ParseIntError> {
debug_assert!(palette.len() == 8);
debug_assert!(palette.chars().next() == Some('P'));
let i = usize::from_str_radix(&palette[1..2], 16)?;
let r = u8::from_str_radix(&palette[2..4], 16)?;
let g = u8::from_str_radix(&palette[4..6], 16)?;
let b = u8::from_str_radix(&palette[6..8], 16)?;
Ok((i, r, g, b))
}
/// See https://vt100.net/emu/dec_ansi_parser
impl Perform for Writer {
fn print(&mut self, c: char) {
@ -420,11 +433,9 @@ impl Perform for Writer {
let s = String::from_utf8_lossy(params[0]);
match s.chars().next() {
Some('P') if s.len() == 8 => {
let i = usize::from_str_radix(&s[1..2], 16).unwrap_or(0);
let r = u8::from_str_radix(&s[2..4], 16).unwrap_or(0);
let g = u8::from_str_radix(&s[4..6], 16).unwrap_or(0);
let b = u8::from_str_radix(&s[6..8], 16).unwrap_or(0);
self.set_palette(i, r, g, b);
if let Ok((i, r, g, b)) = parse_palette(&s) {
self.set_palette(i, r, g, b);
}
}
Some('R') => {
let palette = Palette::default();
@ -569,3 +580,11 @@ pub fn init() {
WRITER.lock().clear_screen();
}
#[test_case]
fn test_parse_palette() {
assert_eq!(parse_palette("P0282828"), Ok((0, 0x28, 0x28, 0x28)));
assert_eq!(parse_palette("P4CC241D"), Ok((4, 0xCC, 0x24, 0x1D)));
assert!(parse_palette("BAAAAAAD").is_ok());
assert!(parse_palette("GOOOOOOD").is_err());
}