string_art/
line_config.rs1use std::ops::{Deref, DerefMut};
2
3use serde::{Deserialize, Serialize};
4
5use crate::{
6 line_selector::{self, LineItemSelector, LineSelector}, verboser::Verboser, AsLab, Image
7};
8
9#[derive(Clone, Copy, Serialize, Deserialize)]
10pub struct LineItemConfig {
11 pub color_idx: usize,
12 pub cap: usize,
13}
14
15impl LineItemConfig {
16 pub fn new(color_idx: usize, cap: usize) -> Self {
17 LineItemConfig { color_idx, cap }
18 }
19}
20
21#[derive(Copy, Clone, Serialize, Deserialize)]
22pub struct LineGroupConfig<C = Vec<LineItemConfig>>(C);
23
24impl<C> LineGroupConfig<C> {
25 pub fn new(items: C) -> Self {
26 LineGroupConfig(items)
27 }
28}
29impl<C> Deref for LineGroupConfig<C>{
30 type Target = C;
31
32 fn deref(&self) -> &Self::Target {
33 &self.0
34 }
35}
36
37impl<C> DerefMut for LineGroupConfig<C>{
38 fn deref_mut(&mut self) -> &mut Self::Target {
39 &mut self.0
40 }
41}
42
43#[derive(Copy, Clone, Serialize, Deserialize)]
44pub struct LineConfig<G = Vec<LineGroupConfig>, C = Vec<LineItemConfig>> {
45 groups: G,
46 _panthom: std::marker::PhantomData<C>,
47}
48
49impl<G, C> LineConfig<G, C>{
50 pub fn new(groups: G) -> Self{
51 Self{
52 groups,
53 _panthom: std::marker::PhantomData,
54 }
55 }
56}
57
58impl<G, C> Deref for LineConfig<G, C>{
59 type Target = G;
60
61 fn deref(&self) -> &Self::Target {
62 &self.groups
63 }
64}
65
66impl<G, C> DerefMut for LineConfig<G, C>{
67 fn deref_mut(&mut self) -> &mut Self::Target {
68 &mut self.groups
69 }
70}
71
72impl From<&LineSelector> for LineConfig{
73 fn from(value: &LineSelector) -> Self {
74 LineConfig::new(value.iter().map(|group| {
75 LineGroupConfig::new(group.iter().map(|item| {
76 LineItemConfig::new(item.color_idx(), item.cap())
77 }).collect())
78 }).collect())
79 }
80}
81
82unsafe impl<S, G, C> line_selector::Builder<S> for LineConfig<G, C>
83where
84 G: AsRef<[LineGroupConfig<C>]>,
85 C: AsRef<[LineItemConfig]>,
86{
87 fn build_line_selector(
88 &self,
89 _: &Image<S>,
90 palette: &[impl AsLab<S>],
91 _: &mut impl Verboser,
92 ) -> Result<LineSelector, line_selector::Error> {
93 self.groups
94 .as_ref()
95 .iter()
96 .map(|group| {
97 group
98 .0
99 .as_ref()
100 .iter()
101 .map(|item| {
102 if item.color_idx >= palette.len() {
103 Err(line_selector::Error)
104 } else {
105 Ok(LineItemSelector::new(item.color_idx, 0, item.cap))
106 }
107 })
108 .collect()
109 })
110 .collect()
111 }
112}
113
114impl From<LineItemConfig> for LineItemSelector {
115 fn from(value: LineItemConfig) -> Self {
116 LineItemSelector::new(value.color_idx, 0, value.cap)
117 }
118}