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
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;

use std::borrow::Cow;

use crate::parse::token::{
    Comment as ParsedComment, Field as ParsedField, InlineComment as ParsedInlineComment,
    Value as ParsedValue,
};

#[derive(Clone, PartialEq, Debug)]
/// The output struct for g-code emission implementing [std::fmt::Display]
///
/// Any strings here are expected to have escaped characters, see <https://www.reprap.org/wiki/G-code#Quoted_strings>
pub enum Token<'a> {
    Field(Field<'a>),
    Comment {
        is_inline: bool,
        inner: Cow<'a, str>,
    },
}

impl<'input> From<&ParsedField<'input>> for Token<'input> {
    fn from(field: &ParsedField<'input>) -> Self {
        Self::Field(field.into())
    }
}

impl<'a, 'input: 'a> From<&'a ParsedInlineComment<'input>> for Token<'input> {
    fn from(comment: &'a ParsedInlineComment<'input>) -> Self {
        Self::Comment {
            is_inline: true,
            inner: Cow::Borrowed(
                comment
                    .inner
                    .strip_prefix("(")
                    .unwrap()
                    .strip_suffix(")")
                    .unwrap(),
            ),
        }
    }
}

impl<'input> From<&ParsedComment<'input>> for Token<'input> {
    fn from(comment: &ParsedComment<'input>) -> Self {
        Self::Comment {
            is_inline: false,
            inner: Cow::Borrowed(comment.inner.strip_prefix(";").unwrap()),
        }
    }
}

/// Fundamental unit of g-code: a descriptive letter followed by a value.
///
/// Field type supports owned and partially-borrowed representations using [Cow].
#[derive(Clone, PartialEq, Debug)]
pub struct Field<'a> {
    pub letters: Cow<'a, str>,
    pub value: Value<'a>,
}

impl<'input> From<&ParsedField<'input>> for Field<'input> {
    fn from(field: &ParsedField<'input>) -> Self {
        Self {
            letters: field.letters.into(),
            value: Value::from(&field.value),
        }
    }
}

impl<'a> From<Field<'a>> for Token<'a> {
    fn from(field: Field<'a>) -> Token<'a> {
        Self::Field(field)
    }
}

impl<'a> Field<'a> {
    /// Returns an owned representation of the Field valid for the `'static` lifetime.
    ///
    /// This will allocate any string types.
    pub fn into_owned(self) -> Field<'static> {
        Field {
            letters: self.letters.into_owned().into(),
            value: self.value.into_owned(),
        }
    }
}

/// All the possible variations of a field's value.
/// Some flavors of g-code also allow for strings.
///
/// Any strings here are expected to have escaped characters, see <https://www.reprap.org/wiki/G-code#Quoted_strings>
#[derive(Clone, PartialEq, Debug)]
pub enum Value<'a> {
    Rational(Decimal),
    Float(f64),
    Integer(usize),
    String(Cow<'a, str>),
}

impl Value<'_> {
    /// Interpret the value as an [f64]
    ///
    /// Returns [Option::None] for [Value::String] or a [Value::Rational] that can't be converted.
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Self::Rational(r) => r.to_f64(),
            Self::Integer(i) => Some(*i as f64),
            Self::Float(f) => Some(*f),
            Self::String(_) => None,
        }
    }

    /// Returns an owned representation of the Value valid for the `'static` lifetime.
    ///
    /// This will allocate a string for a [Value::String].
    pub fn into_owned(self) -> Value<'static> {
        match self {
            Self::String(s) => Value::String(s.into_owned().into()),
            Self::Rational(r) => Value::Rational(r),
            Self::Integer(i) => Value::Integer(i),
            Self::Float(f) => Value::Float(f),
        }
    }
}

impl<'input> From<&ParsedValue<'input>> for Value<'input> {
    fn from(val: &ParsedValue<'input>) -> Self {
        use ParsedValue::*;
        match val {
            Rational(r) => Self::Rational(*r),
            Integer(i) => Self::Integer(*i),
            String(s) => {
                // Remove enclosing quotes
                Self::String(Cow::Borrowed(
                    s.strip_prefix('"').unwrap().strip_suffix('"').unwrap(),
                ))
            }
        }
    }
}