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
extern crate chrono;
extern crate thiserror;

use chrono::Datelike;
use std::convert::{TryFrom, TryInto};

/// A struct with the parsed data of a Persona ID.
///
/// Persona data can be parsed from a string using their [`std::str::FromStr`] implementation, like so:
///
/// ```rust,ignore
/// let v = "A-223-0-QZ-029";
/// assert_eq!(
///     v.parse::<PersonaData>().unwrap(),
///     PersonaData {
///         model: MT::Alpha,
///         date: chrono::NaiveDate::from_ymd(2223, 1, 1),
///         personality: "QZ".into(),
///         manufacture_no: 29,
///     }
/// );
/// ```
///
/// They can also be re-stringified using [`std::fmt::Display`].
///
/// ```rust,ignore
/// assert_eq!(
///     format!(
///         "{}",
///         PersonaData {
///             model: MT::Alpha,
///             date: chrono::NaiveDate::from_ymd(2223, 1, 1),
///             personality: "QZ".into(),
///             manufacture_no: 29,
///         }
///     ),
///     "A-223-0-QZ-029"
/// );
/// ```
#[derive(Debug, Eq, PartialEq)]
pub struct PersonaData {
    pub model: ModelType,
    pub date: chrono::NaiveDate,
    pub personality: [char; 2],
    pub manufacture_no: u16,
}

#[derive(Debug, thiserror::Error)]
pub enum ParseFailure {
    #[error("String of invalid length or format passed")]
    InvalidString,
    #[error("Invalid model for value '{0}'")]
    InvalidModel(char),
    #[error("Invalid year '{0}'")]
    InvalidYear(String),
    #[error("Invalid month '{0}'")]
    InvalidMonth(String),
    #[error("Invalid manufacture number '{0}'")]
    InvalidManufactureNo(String),
}

/// The various models that Persona offers.
#[non_exhaustive]
#[derive(Debug, Eq, PartialEq, Clone, Copy)]
pub enum ModelType {
    /// Signature Series - Prototypes made during the first Persona test.
    Alpha,
    /// Enterprise units - Secretaries, executive assistants, and office workers.
    Buisness,
    /// Close companions of most natures - from Best Friends to Family, and confidants to your 'girl next door'-style unit.
    Companion,
    /// Male units.
    David,
    /// Entertainers - For night clubs and adult venues.
    Entertainment,
    /// Anthropomorphic units - All robofoxes welcome.
    Fursona,
    /// Security, bodyguards, and stand-ins.
    Guardian,
    /// Nursing, in-home support, and lifeguards.
    Healthcare,
    /// Replacement / Uploaded personalities. Formerly human.
    Inherited,
    // J,
    /// Sorority/School models.
    KappaIotaTau,
    /// Lawyers and Attourneys.
    Legal,
    /// Homemakers, child rearers, and some limited financial computational functions.
    Matron,
    /// Null units. Includes non-Synthflesh robots.
    Null,
    /// Alien & monster girls.
    Outsiders,
    /// Personalized / Prototypes. For one-offs, experiments, or truly custom orders.
    PersonaPlus,
    /// Repair and reprogramming specialists.
    QualityControl,
    /// Sales units, waitresses, and hotel staff (such as receptionists and maids).
    Retail,
    /// Sexual gratification.
    Sensual, // Model S, suggested name
    /// Training, testing, and tuning.
    Testing,
    /// Utility, heavy-duty, sanitation, and janitorial bots.
    Utility,
    /// Persona Spike Project (in development)
    Variable,
    // W,
    /// Experimental one-off designs. Includes pre-transfer 'units'.
    Experimental, // Model X,
    // Y,
    #[cfg_attr(not(feature = "unstable"), doc(hidden))]
    ZSeries,
}

impl std::fmt::Display for ModelType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use ModelType as MT;

        write!(
            f,
            "{}",
            match self {
                MT::Alpha => "Alpha",
                MT::Buisness => "Buisness",
                MT::Companion => "Companion",
                MT::David => "David",
                MT::Entertainment => "Entertainment",
                MT::Fursona => "Fursona",
                MT::Guardian => "Guardian",
                MT::Healthcare => "Healthcare",
                MT::Inherited => "Inherited",
                MT::KappaIotaTau => "Kappa Iota Tau",
                MT::Legal => "Legal",
                MT::Matron => "Matron",
                MT::Null => "Null",
                MT::Outsiders => "Outsiders",
                MT::PersonaPlus => "Persona+",
                MT::QualityControl => "Quality Control",
                MT::Retail => "Retail",
                MT::Sensual => "Sensual", // Model S, suggested name
                MT::Testing => "Testing",
                MT::Utility => "Utility",
                MT::Variable => "Variable",
                MT::Experimental => "Experimental", // Model X,
                MT::ZSeries => {
                    if cfg!(feature = "unstable") {
                        "Z Series"
                    } else {
                        ""
                    }
                }
            }
        )
    }
}

impl TryFrom<char> for ModelType {
    type Error = ParseFailure;

    fn try_from(value: char) -> Result<Self, Self::Error> {
        use ModelType as MT;
        if !value.is_ascii_uppercase() {
            return Err(ParseFailure::InvalidModel(value));
        }

        match value {
            'A' => Ok(MT::Alpha),
            'B' => Ok(MT::Buisness),
            'C' => Ok(MT::Companion),
            'D' => Ok(MT::David),
            'E' => Ok(MT::Entertainment),
            'F' => Ok(MT::Fursona),
            'G' => Ok(MT::Guardian),
            'H' => Ok(MT::Healthcare),
            'I' => Ok(MT::Inherited),
            'J' => Err(ParseFailure::InvalidModel(value)),
            'K' => Ok(MT::KappaIotaTau),
            'L' => Ok(MT::Legal),
            'M' => Ok(MT::Matron),
            'N' => Ok(MT::Null),
            'O' => Ok(MT::Outsiders),
            'P' => Ok(MT::PersonaPlus),
            'Q' => Ok(MT::QualityControl),
            'R' => Ok(MT::Retail),
            'S' => Ok(MT::Sensual),
            'T' => Ok(MT::Testing),
            'U' => Ok(MT::Utility),
            'V' => Ok(MT::Variable),
            'W' => Err(ParseFailure::InvalidModel(value)),
            'X' => Ok(MT::Experimental),
            'Y' => Err(ParseFailure::InvalidModel(value)),
            'Z' => {
                if cfg!(feature = "unstable") {
                    Ok(MT::ZSeries)
                } else {
                    Err(ParseFailure::InvalidModel(value))
                }
            }
            _ => unreachable!(),
        }
    }
}

impl From<ModelType> for char {
    fn from(v: ModelType) -> Self {
        use ModelType as MT;
        match v {
            MT::Alpha => 'A',
            MT::Buisness => 'B',
            MT::Companion => 'C',
            MT::David => 'D',
            MT::Entertainment => 'E',
            MT::Fursona => 'F',
            MT::Guardian => 'G',
            MT::Healthcare => 'H',
            MT::Inherited => 'I',
            // MT::J => 'J',
            MT::KappaIotaTau => 'K',
            MT::Legal => 'L',
            MT::Matron => 'M',
            MT::Null => 'N',
            MT::Outsiders => 'O',
            MT::PersonaPlus => 'P',
            MT::QualityControl => 'Q',
            MT::Retail => 'R',
            MT::Sensual => 'S',
            MT::Testing => 'T',
            MT::Utility => 'U',
            MT::Variable => 'V',
            // MT::W => 'W',
            MT::Experimental => 'X', // Model X,
            // MT::Y => '',
            MT::ZSeries => {
                if cfg!(feature = "unstable") {
                    'Z'
                } else {
                    panic!()
                }
            }
        }
    }
}

impl std::str::FromStr for PersonaData {
    // ID format:
    //
    // L-NNN-N-LL-NNN (L = letter, N = number)
    // ^ ^   ^ ^  ^
    // | |   | |  |
    // Model Type |
    //   |   | |  |
    //   Manufacture Year
    //       | |  |
    //       Manufacture Month (hexidecimal)
    //         |  |
    //         Personality Identifier
    //            |
    //            Manufacture Number

    type Err = ParseFailure;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.len() != 14 || !s.is_ascii() {
            return Err(ParseFailure::InvalidString);
        }

        let mut iditer = s.split('-').map(|x| x.chars());

        let model = if let Some(x) = iditer.next().map(|mut x| x.next()).flatten() {
            x
        } else {
            return Err(ParseFailure::InvalidString);
        };

        let model: ModelType = model.try_into()?;

        let year = if let Some(x) = iditer.next().map(|x| x.collect::<String>()) {
            if let Ok(v) = x.parse::<u16>() {
                if v > 999 {
                    return Err(ParseFailure::InvalidYear(v.to_string()));
                } else {
                    v + 2000
                }
            } else {
                return Err(ParseFailure::InvalidYear(x.into()));
            }
        } else {
            return Err(ParseFailure::InvalidString);
        };

        let month = if let Some(x) = iditer.next().map(|x| x.collect::<String>()) {
            if let Ok(v) = u16::from_str_radix(&x, 16) {
                if v > 11 {
                    return Err(ParseFailure::InvalidMonth(v.to_string()));
                } else {
                    v + 1
                }
            } else {
                return Err(ParseFailure::InvalidMonth(x.into()));
            }
        } else {
            return Err(ParseFailure::InvalidString);
        };

        let personality = if let Some(x) = iditer.next().map(|x| x.take(2)) {
            if x.clone().count() == 2 {
                let x = x.collect::<Vec<_>>();
                [x[0], x[1]]
            } else {
                return Err(ParseFailure::InvalidString);
            }
        } else {
            return Err(ParseFailure::InvalidString);
        };

        let manufacture_no = if let Some(x) = iditer.next().map(|x| x.collect::<String>()) {
            if let Ok(v) = x.parse::<u16>() {
                if v > 999 {
                    return Err(ParseFailure::InvalidManufactureNo(v.to_string()));
                } else {
                    v
                }
            } else {
                return Err(ParseFailure::InvalidManufactureNo(x.into()));
            }
        } else {
            return Err(ParseFailure::InvalidString);
        };

        let date = chrono::NaiveDate::from_ymd(year as i32, month as u32, 1);

        Ok(PersonaData {
            model,
            date,
            personality,
            manufacture_no,
        })
    }
}

impl std::fmt::Display for PersonaData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let model: char = self.model.into();
        write!(
            f,
            "{}-{:03}-{:X}-{}{}-{:03}",
            model,
            self.date.year() - 2000,
            self.date.month() - 1,
            self.personality[0],
            self.personality[1],
            self.manufacture_no
        )
    }
}

#[cfg(test)]
mod tests {
    use super::ModelType as MT;
    use super::PersonaData;
    #[test]
    fn valid_parse_and_reassemble() {
        let v = "A-223-0-QZ-029";
        assert_eq!(
            v.parse::<PersonaData>().unwrap(),
            PersonaData {
                model: MT::Alpha,
                date: chrono::NaiveDate::from_ymd(2223, 1, 1),
                personality: ['Q', 'Z'],
                manufacture_no: 29,
            }
        );
        assert_eq!(
            format!(
                "{}",
                PersonaData {
                    model: MT::Alpha,
                    date: chrono::NaiveDate::from_ymd(2223, 1, 1),
                    personality: ['Q', 'Z'],
                    manufacture_no: 29,
                }
            ),
            v.to_string()
        );
    }
}