wavedrom 0.1.0

A Pure Rust Digital Timing Diagram Generator based on WaveDrom-JS
Documentation
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
//! Edges or Arrows define a set of markers and edge lines that can be put over a diagram to
//! indicate properties.
//!
//! An edge line is between 2 nodes which are identified by a character. If the character is and
//! uppercase ASCII character then is is not displayed on the diagram otherwise it is also shown on
//! the diagram.
//!
//! There are several types of edges, a full overview can be seen in the wavedrom-rs book. Here
//! they are represented with the [`EdgeVariant`] structure.
//!
//! In [WaveJson][crate::wavejson] an edge is given by a string that defined under the `edge`
//! property array at the root JSON level. The edge there given in the following order: `<start
//! node><edge identifier><end node> [label]`. The label is text that is put on the middle of the
//! edge.

use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::str::FromStr;

use crate::{CycleOffset, Signal};

/// A set of edge markers. Both the edge lines and the text_nodes.
#[derive(Debug, Clone)]
pub struct LineEdgeMarkers<'a> {
    lines: Vec<LineEdge<'a>>,
    text_nodes: Vec<LineEdgeText>,
}

/// A edge from a start node to an end node
#[derive(Debug, Clone)]
pub struct LineEdge<'a> {
    from: InSignalPosition,
    from_marker: Option<char>,
    to: InSignalPosition,
    to_marker: Option<char>,
    text: Option<Cow<'a, str>>,
    variant: EdgeVariant,
}

/// The text belowing to a node
#[derive(Debug, Clone)]
pub struct LineEdgeText {
    at: InSignalPosition,
    text: char,
}

/// A position in the signal schema. Containing both a `x` (cycle offset) value and a `y` (signal
/// index) value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InSignalPosition {
    x: CycleOffset,
    y: u32,
}

/// The definition for an edge
#[derive(Debug, Clone)]
#[cfg_attr(test, derive(PartialEq, Eq))]
pub struct EdgeDefinition {
    variant: EdgeVariant,
    from: char,
    to: char,
    label: Option<String>,
}

/// A variant of an edge
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EdgeVariant {
    /// A smooth / curved edge variant
    Spline(SplineEdgeVariant),
    /// A sharp edge variant
    Sharp(SharpEdgeVariant),
}

/// A variant of a smooth / curved edge
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplineEdgeVariant {
    /// Spline edge that is points to the start and end node horizontally. Edge identifier is `~`.
    BothHorizontal(EdgeArrowType),
    /// Spline edge that is points to the start horizontally. The end node is pointed to slightly
    /// vertical. Edge identifier is `-~`.
    StartHorizontal(EdgeArrowType),
    /// Spline edge that is points to the end horizontally. The start node is pointed to slightly
    /// vertical. Edge identifier is `~-`.
    EndHorizontal(EdgeArrowType),
}

/// A variant of a sharp edge
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SharpEdgeVariant {
    /// Sharp edge that always takes the shortest path from the start to the end node. Edge
    /// identifier is `-`.
    Straight(EdgeArrowType),
    /// Sharp edge that points to the start and the end node horizontally. Edge identifier is
    /// `-|-`.
    BothHorizontal(EdgeArrowType),
    /// Sharp edge that points to the start node horizontally and the end node mostly vertically.
    /// Edge identifier is `-|`.
    StartHorizontal(EdgeArrowType),
    /// Sharp edge that points to the end node horizontally and the start node mostly vertically.
    /// Edge identifier is `|-`.
    EndHorizontal(EdgeArrowType),
    /// Sharp edge that takes the shortest path from the start node to the end node and contains
    /// small bars at the start and end. Edge identifier is `+`.
    Cross,
}

/// Structure that defines at which sides of an [`EdgeVariant`] there are arrows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EdgeArrowType {
    /// No arrows at either start or end.
    None,
    /// Arrows at start.
    Start,
    /// Arrow at end.
    End,
    /// Both arrows at start or end.
    Both,
}

pub(crate) struct LineEdgeMarkersBuilder {
    line_number: u32,
    node_positions: HashMap<char, InSignalPosition>,
    text_nodes: Vec<LineEdgeText>,
}

impl EdgeArrowType {
    /// Create a new [`EdgeArrowType`].
    #[inline]
    fn new(has_arrow_left: bool, has_arrow_right: bool) -> Self {
        match (has_arrow_left, has_arrow_right) {
            (false, false) => Self::None,
            (true, false) => Self::Start,
            (false, true) => Self::End,
            (true, true) => Self::Both,
        }
    }
}

#[inline]
fn take_char(s: &str, c: char) -> (&str, bool) {
    if s.starts_with(c) {
        (&s[1..], true)
    } else {
        (s, false)
    }
}

#[inline]
fn take(s: &str) -> Option<(&str, char)> {
    let mut chars = s.chars();
    let c = chars.next()?;
    Some((chars.as_str(), c))
}

impl EdgeArrowType {
    /// Does the variant have an arrow at the start
    #[inline]
    pub fn has_start_arrow(self) -> bool {
        matches!(self, Self::Both | Self::Start)
    }

    /// Does the variant have an arrow at the end
    #[inline]
    pub fn has_end_arrow(self) -> bool {
        matches!(self, Self::Both | Self::End)
    }
}

impl SplineEdgeVariant {
    /// Fetch the arrow type that the [`SplineEdgeVariant`] has.
    #[inline]
    pub fn arrow_type(self) -> EdgeArrowType {
        match self {
            SplineEdgeVariant::BothHorizontal(a)
            | SplineEdgeVariant::StartHorizontal(a)
            | SplineEdgeVariant::EndHorizontal(a) => a,
        }
    }
}

impl SharpEdgeVariant {
    /// Fetch the arrow type that the [`SharpEdgeVariant`] has. The [`SharpEdgeVariant::Cross`]
    /// always has [`EdgeArrowType::None`].
    #[inline]
    pub fn arrow_type(self) -> EdgeArrowType {
        match self {
            SharpEdgeVariant::Straight(a)
            | SharpEdgeVariant::BothHorizontal(a)
            | SharpEdgeVariant::StartHorizontal(a)
            | SharpEdgeVariant::EndHorizontal(a) => a,
            SharpEdgeVariant::Cross => EdgeArrowType::None,
        }
    }
}

impl EdgeVariant {
    /// Fetch the arrow type that the [`EdgeVariant`] has. The [`SharpEdgeVariant::Cross`]
    /// always has [`EdgeArrowType::None`].
    #[inline]
    pub fn arrow_type(self) -> EdgeArrowType {
        match self {
            EdgeVariant::Spline(v) => v.arrow_type(),
            EdgeVariant::Sharp(v) => v.arrow_type(),
        }
    }

    fn consume(s: &str) -> Option<(&str, Self)> {
        let (s, has_arrow_left) = take_char(s, '<');

        match s.as_bytes() {
            [b'-', b'|', b'-', ..] => {
                let s = &s[3..];
                let (s, has_arrow_right) = take_char(s, '>');
                let arrow_type = EdgeArrowType::new(has_arrow_left, has_arrow_right);
                Some((s, Self::Sharp(SharpEdgeVariant::BothHorizontal(arrow_type))))
            }
            [b'-', b'|', ..] => {
                let s = &s[2..];
                let (s, has_arrow_right) = take_char(s, '>');
                let arrow_type = EdgeArrowType::new(has_arrow_left, has_arrow_right);
                Some((
                    s,
                    Self::Sharp(SharpEdgeVariant::StartHorizontal(arrow_type)),
                ))
            }
            [b'|', b'-', ..] => {
                let s = &s[2..];
                let (s, has_arrow_right) = take_char(s, '>');
                let arrow_type = EdgeArrowType::new(has_arrow_left, has_arrow_right);
                Some((s, Self::Sharp(SharpEdgeVariant::EndHorizontal(arrow_type))))
            }
            [b'-', b'~', ..] => {
                let s = &s[2..];
                let (s, has_arrow_right) = take_char(s, '>');
                let arrow_type = EdgeArrowType::new(has_arrow_left, has_arrow_right);
                Some((
                    s,
                    Self::Spline(SplineEdgeVariant::StartHorizontal(arrow_type)),
                ))
            }
            [b'~', b'-', ..] => {
                let s = &s[2..];
                let (s, has_arrow_right) = take_char(s, '>');
                let arrow_type = EdgeArrowType::new(has_arrow_left, has_arrow_right);
                Some((
                    s,
                    Self::Spline(SplineEdgeVariant::EndHorizontal(arrow_type)),
                ))
            }
            [b'-', ..] => {
                let s = &s[1..];
                let (s, has_arrow_right) = take_char(s, '>');
                let arrow_type = EdgeArrowType::new(has_arrow_left, has_arrow_right);
                Some((s, Self::Sharp(SharpEdgeVariant::Straight(arrow_type))))
            }
            [b'+', ..] => {
                let s = &s[1..];
                if has_arrow_left {
                    return None;
                }
                Some((s, Self::Sharp(SharpEdgeVariant::Cross)))
            }
            [b'~', ..] => {
                let s = &s[1..];
                let (s, has_arrow_right) = take_char(s, '>');
                let arrow_type = EdgeArrowType::new(has_arrow_left, has_arrow_right);
                Some((
                    s,
                    Self::Spline(SplineEdgeVariant::BothHorizontal(arrow_type)),
                ))
            }
            _ => None,
        }
    }
}

impl LineEdgeMarkersBuilder {
    pub fn new() -> Self {
        Self {
            line_number: 0,
            node_positions: HashMap::new(),
            text_nodes: Vec::new(),
        }
    }

    pub fn add_signal(&mut self, signal: &Signal) {
        let line_number = self.line_number;

        for (i, c) in signal.get_nodes().chars().enumerate() {
            if c == '.' {
                continue;
            }

            let at = InSignalPosition {
                x: signal.get_phase() + CycleOffset::new_rounded(i as u32),
                y: line_number,
            };

            self.node_positions.insert(c, at.clone());
            self.text_nodes.push(LineEdgeText { at, text: c });
        }

        self.line_number += 1;
    }

    pub fn build(mut self, edges: &[EdgeDefinition]) -> LineEdgeMarkers {
        let mut lines = Vec::new();
        let mut used_text_nodes = HashSet::new();

        for edge in edges {
            if edge.from == edge.to {
                continue;
            }

            let Some(from) = self.node_positions.get(&edge.from) else {
                continue;
            };
            let Some(to) = self.node_positions.get(&edge.to) else {
                continue;
            };

            used_text_nodes.insert(edge.from);
            used_text_nodes.insert(edge.to);

            let from = from.clone();
            let to = to.clone();

            let text = edge.label.as_ref().map(|text| Cow::Borrowed(&text[..]));
            let variant = edge.variant;

            let from_marker = (!edge.from.is_ascii_uppercase()).then_some(edge.from);
            let to_marker = (!edge.to.is_ascii_uppercase()).then_some(edge.to);

            lines.push(LineEdge {
                from,
                from_marker,
                to,
                to_marker,
                text,
                variant,
            });
        }

        self.text_nodes
            .retain(|n| !used_text_nodes.contains(&n.text()) && !n.text().is_ascii_uppercase());

        LineEdgeMarkers {
            lines,
            text_nodes: self.text_nodes,
        }
    }
}

impl LineEdgeMarkers<'_> {
    /// The edge lines for a [`LineEdgeMarkers`]
    pub fn lines(&self) -> &[LineEdge] {
        &self.lines
    }

    /// The lone standing text nodes for a [`LineEdgeMarkers`]
    pub fn text_nodes(&self) -> &[LineEdgeText] {
        &self.text_nodes
    }
}

impl LineEdge<'_> {
    /// The starting position
    #[inline]
    pub fn from(&self) -> &InSignalPosition {
        &self.from
    }

    /// The ending position
    #[inline]
    pub fn to(&self) -> &InSignalPosition {
        &self.to
    }

    /// The marker at the start of the edge line
    #[inline]
    pub fn from_marker(&self) -> Option<char> {
        self.from_marker
    }

    /// The marker at the end of the edge line
    #[inline]
    pub fn to_marker(&self) -> Option<char> {
        self.to_marker
    }

    /// The variant of the edge line
    #[inline]
    pub fn variant(&self) -> &EdgeVariant {
        &self.variant
    }

    /// The label text of the edge line
    #[inline]
    pub fn label(&self) -> Option<&str> {
        self.text.as_ref().map(|s| &s[..])
    }
}

impl LineEdgeText {
    /// The location of the node
    #[inline]
    pub fn at(&self) -> &InSignalPosition {
        &self.at
    }

    /// The text content of the node
    #[inline]
    pub fn text(&self) -> char {
        self.text
    }
}

impl InSignalPosition {
    /// The `x` value of the position
    pub fn x(&self) -> CycleOffset {
        self.x
    }

    /// The `y` value of the position
    pub fn y(&self) -> u32 {
        self.y
    }
}

impl EdgeDefinition {
    /// Create a new [`EdgeDefinition`] from a set of parameters
    pub fn new(variant: EdgeVariant, from: char, to: char, label: Option<String>) -> Self {
        Self { variant, from, to, label }
    }
}

impl FromStr for EdgeDefinition {
    type Err = usize;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let start_len = s.len();
        let s = s.trim_start();
        let start_idx = start_len - s.len();

        let (s, from) = take(s).ok_or(start_idx)?;

        let start_len = s.len();
        let s = s.trim_start();
        let start_idx = start_idx + start_len - s.len();

        let (s, variant) = EdgeVariant::consume(s).ok_or(start_idx)?;

        let start_len = s.len();
        let s = s.trim_start();
        let start_idx = start_idx + start_len - s.len();

        let (s, to) = take(s).ok_or(start_idx)?;

        let text = (!s.is_empty()).then_some(s.trim_start().to_string());

        Ok(Self {
            variant,
            from,
            to,
            label: text,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn edge_variant_parse() {
        macro_rules! assert_edge_variant {
            ($input:literal, $output:expr) => {
                #[allow(unused)]
                use EdgeArrowType::*;
                #[allow(unused)]
                use EdgeVariant::*;

                let out = EdgeVariant::consume($input);

                assert!(out.is_some());

                let (out_str, out) = out.unwrap();

                assert!(out_str.is_empty());
                assert_eq!(out, $output);
            };
            ($input:literal) => {
                assert!(EdgeVariant::consume($input).is_none());
            };
        }

        assert_edge_variant!("-|-", Sharp(SharpEdgeVariant::BothHorizontal(None)));
        assert_edge_variant!("<-|-", Sharp(SharpEdgeVariant::BothHorizontal(Start)));
        assert_edge_variant!("<-|->", Sharp(SharpEdgeVariant::BothHorizontal(Both)));
        assert_edge_variant!("-|->", Sharp(SharpEdgeVariant::BothHorizontal(End)));
        assert_edge_variant!("->", Sharp(SharpEdgeVariant::Straight(End)));
        assert_edge_variant!("+", Sharp(SharpEdgeVariant::Cross));
        assert_edge_variant!("<+");
        assert_edge_variant!("<+>");
    }

    #[test]
    fn edge_definition() {
        macro_rules! assert_edge_def {
            ($input:literal => $from:literal, $to:literal, $edge_variant:expr, $text:expr) => {
                #[allow(unused)]
                use EdgeVariant::*;

                let out = EdgeDefinition::from_str($input);

                assert!(out.is_ok());

                let out = out.unwrap();

                assert_eq!(out.from, $from);
                assert_eq!(out.to, $to);
                assert_eq!(out.variant, $edge_variant);
                assert_eq!(out.label, Some($text).map(Into::into));
            };
            ($input:literal => $from:literal, $to:literal, $edge_variant:expr) => {
                #[allow(unused)]
                use EdgeVariant::*;

                let out = EdgeDefinition::from_str($input);

                assert!(out.is_ok());

                let out = out.unwrap();

                assert_eq!(out.from, $from);
                assert_eq!(out.to, $to);
                assert_eq!(out.variant, $edge_variant);
                assert!(out.label.is_none());
            };
            ($input:literal) => {
                assert!(EdgeDefinition::from_str($input).is_err());
            };
        }

        assert_edge_def!("I+J abc" => 'I', 'J', Sharp(SharpEdgeVariant::Cross), "abc");
        assert_edge_def!("I<+J abc");
        assert_edge_def!("<+J" => '<', 'J', Sharp(SharpEdgeVariant::Cross));
    }
}