Skip to main content

ironwork_rt/
edit.rs

1//! Editing: a numeric value laid into a numeric-edited PICTURE, alphanumeric data into an
2//! alphanumeric-edited one, and de-editing back to a number.
3
4use crate::picture::Sym;
5
6/// The characters a numeric-edited item holds for a value. `magnitude` is already aligned to the
7/// PICTURE's decimal places and within its digit positions. `point` is what a decimal point
8/// position shows: a period, or a comma under DECIMAL-POINT IS COMMA. `currency` is the currency
9/// sign value, which the first currency position holds in full.
10pub fn numeric(syms: &[Sym], digits: u32, negative: bool, magnitude: u128, blank_when_zero: bool, point: char, currency: &str) -> String {
11    let width = |s: &Sym| width(s, currency);
12    let size: usize = syms.iter().map(width).sum();
13    let digit_syms: Vec<&Sym> = syms.iter().filter(|s| s.is_digit()).collect();
14    if magnitude == 0 && (blank_when_zero || digit_syms.iter().all(|s| matches!(s, Sym::Z | Sym::Float(_)))) {
15        return " ".repeat(size);
16    }
17    if magnitude == 0 && digit_syms.iter().all(|s| matches!(s, Sym::Star)) {
18        return syms.iter().flat_map(|s| std::iter::repeat_n(if *s == Sym::Point { point } else { '*' }, width(s))).collect();
19    }
20    let text = format!("{magnitude:0width$}", width = digits as usize);
21    let mut digit_chars = text.chars().skip(text.len() - digits as usize);
22    let mut out: Vec<char> = Vec::with_capacity(size);
23    let (mut significant, mut fill) = (false, None);
24    let (mut float_char, mut float_slot) = (None, None);
25    for s in syms {
26        match *s {
27            Sym::Nine => {
28                significant = true;
29                out.push(digit_chars.next().unwrap_or('0'));
30            }
31            Sym::Z | Sym::Star => {
32                let blank = if *s == Sym::Star { '*' } else { ' ' };
33                fill = Some(blank);
34                let d = digit_chars.next().unwrap_or('0');
35                significant |= d != '0';
36                out.push(if significant { d } else { blank });
37            }
38            Sym::FloatLead(c) => {
39                float_char = Some(c);
40                out.extend(std::iter::repeat_n(' ', width(s)));
41                float_slot = Some(out.len() - 1);
42            }
43            Sym::Float(_) => {
44                let d = digit_chars.next().unwrap_or('0');
45                significant |= d != '0';
46                if significant {
47                    out.push(d);
48                } else {
49                    float_slot = Some(out.len());
50                    out.push(' ');
51                }
52            }
53            Sym::Point | Sym::Implied => {
54                significant = true;
55                if *s == Sym::Point {
56                    out.push(point);
57                }
58            }
59            Sym::Insert(c) => {
60                if significant {
61                    out.push(c);
62                } else if float_char.is_some() {
63                    float_slot = Some(out.len());
64                    out.push(' ');
65                } else {
66                    out.push(fill.unwrap_or(c));
67                }
68            }
69            Sym::Sign(c) => out.push(match (c, negative) {
70                ('+', false) => '+',
71                (_, true) => '-',
72                _ => ' ',
73            }),
74            Sym::Currency => out.extend(currency.chars()),
75            Sym::Cr => out.extend(if negative { ['C', 'R'] } else { [' ', ' '] }),
76            Sym::Db => out.extend(if negative { ['D', 'B'] } else { [' ', ' '] }),
77            Sym::Char => out.push(' '),
78        }
79    }
80    match (float_char, float_slot) {
81        (Some('$'), Some(slot)) => {
82            let value: Vec<char> = currency.chars().collect();
83            out[slot + 1 - value.len()..=slot].copy_from_slice(&value);
84        }
85        (Some(c), Some(slot)) => {
86            out[slot] = match (c, negative) {
87                ('+', false) => '+',
88                (_, true) => '-',
89                _ => ' ',
90            }
91        }
92        _ => {}
93    }
94    out.into_iter().collect()
95}
96
97/// Alphanumeric data laid into an alphanumeric-edited PICTURE: characters fill the X, A and 9
98/// positions in order; insertion characters stand where they are written.
99pub fn alphanumeric(syms: &[Sym], data: &[u8], space: u8, encode: impl Fn(char) -> u8) -> Vec<u8> {
100    let mut source = data.iter();
101    syms.iter()
102        .map(|s| match s {
103            Sym::Insert(c) => encode(*c),
104            _ => source.next().copied().unwrap_or(space),
105        })
106        .collect()
107}
108
109/// A numeric-edited item's value: the digits in its digit positions, negative when it shows a
110/// minus sign, CR or DB. `currency` is the currency sign value, as for [`numeric`].
111pub fn de_edit(syms: &[Sym], text: &str, currency: &str) -> (bool, u128) {
112    let chars: Vec<char> = text.chars().collect();
113    let (mut at, mut magnitude, mut negative) = (0usize, 0u128, false);
114    for s in syms {
115        let c = chars.get(at).copied().unwrap_or(' ');
116        match s {
117            Sym::Implied => continue,
118            Sym::Cr | Sym::Db => {
119                negative |= c != ' ';
120                at += 2;
121                continue;
122            }
123            _ if s.is_digit() => magnitude = magnitude * 10 + c.to_digit(10).unwrap_or(0) as u128,
124            Sym::Sign(_) | Sym::FloatLead(_) | Sym::Float(_) => negative |= c == '-',
125            _ => {}
126        }
127        if matches!(s, Sym::Float(_)) {
128            negative |= c == '-';
129        }
130        at += width(s, currency);
131    }
132    (negative, magnitude)
133}
134
135/// Character positions `s` takes: the first currency position holds the whole currency sign value.
136fn width(s: &Sym, currency: &str) -> usize {
137    match s {
138        Sym::Currency | Sym::FloatLead('$') => currency.chars().count().max(1),
139        _ => s.width(),
140    }
141}