diff options
author | Genny <gen@nyble.dev> | 2021-09-23 20:33:50 -0500 |
---|---|---|
committer | Genny <gen@nyble.dev> | 2021-09-23 20:33:50 -0500 |
commit | 637441239434fabedfe83f5abc1af4232c802f7a (patch) | |
tree | dbc84cd1a31686077fc046fd42d223f1ca08f890 /src/block/colortable.rs | |
parent | 7b8081a79fb3db4a76f9e4cca8f8a88e6e7f873c (diff) | |
download | gifed-637441239434fabedfe83f5abc1af4232c802f7a.tar.gz gifed-637441239434fabedfe83f5abc1af4232c802f7a.zip |
Improve API, monocommit, sorry
Diffstat (limited to 'src/block/colortable.rs')
-rw-r--r-- | src/block/colortable.rs | 47 |
1 files changed, 41 insertions, 6 deletions
diff --git a/src/block/colortable.rs b/src/block/colortable.rs index da9458c..d8241f7 100644 --- a/src/block/colortable.rs +++ b/src/block/colortable.rs @@ -1,9 +1,11 @@ pub use crate::Color; +use crate::EncodingError; use std::{ convert::{TryFrom, TryInto}, ops::Deref, }; +#[derive(Clone, Debug)] pub struct ColorTable { table: Vec<Color>, } @@ -29,6 +31,19 @@ impl ColorTable { pub fn push(&mut self, color: Color) { self.table.push(color); } + + pub fn get(&self, index: u8) -> Option<Color> { + self.table.get(index as usize).map(|v| v.clone()) + } + + pub fn from_color(&self, color: Color) -> Option<u8> { + for (i, &c) in self.table.iter().enumerate() { + if c == color { + return Some(i as u8); + } + } + None + } } impl Deref for ColorTable { @@ -39,12 +54,6 @@ impl Deref for ColorTable { } } -impl From<Vec<Color>> for ColorTable { - fn from(table: Vec<Color>) -> Self { - ColorTable { table } - } -} - impl From<&ColorTable> for Box<[u8]> { fn from(table: &ColorTable) -> Self { let mut vec = vec![]; @@ -80,3 +89,29 @@ impl TryFrom<&[u8]> for ColorTable { } } } + +impl TryFrom<Vec<Color>> for ColorTable { + type Error = EncodingError; + + fn try_from(value: Vec<Color>) -> Result<Self, Self::Error> { + if value.len() > 256 { + Err(EncodingError::TooManyColors) + } else { + Ok(Self { table: value }) + } + } +} + +impl TryFrom<Vec<(u8, u8, u8)>> for ColorTable { + type Error = EncodingError; + + fn try_from(value: Vec<(u8, u8, u8)>) -> Result<Self, Self::Error> { + if value.len() > 256 { + Err(EncodingError::TooManyColors) + } else { + Ok(Self { + table: value.into_iter().map(|c| c.into()).collect(), + }) + } + } +} |