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
#![forbid(unsafe_code)]

//! # morseclock - Yet another not-so-intuitive clock
//! 
//! morseclock allows you to generate a clock visualization inspired by [this hackaday post](https://hackaday.com/2016/07/29/a-one-led-clock/)
//! 
//! # Usage example
//! 
//! ```
//! use morseclock::{Clock, Format, MorseExt};
//! 
//! // Hour must be in the range [0, 23)
//! let hour = 16.try_into().unwrap();
//! // Minute must be in the range [0, 59)
//! let minute = 47.try_into().unwrap();
//! 
//! let clock = Clock::new(hour, minute, Format::Hour12);
//! 
//! let time: String = clock
//!     .into_iter()
//!     .morse()
//!     .collect();
//! 
//! assert_eq!(time, "--.=----")
//! ```
//! 
//! # How to read the "morsecode"
//! 
//! The mapping generated by the [`MorseExt`] iterator extension trait can be interpreted as follows
//! 
//! The string `"--.=----"` represents the time 4:47.  
//! The character `'='` separates the hour-hand from the minute-hand.
//! 
//! On the hour-hand a single `'-'` stands for a increment of of 3 hours (a quarter rotation of the hand), starting at the 0 o'clock position.  
//! A single `'.'` stands for an increment of 1 hour.  
//! 
//! On the minute-hand, a single `'-'` stands for a increment of 15 minutes (a quarter rotation of the hand), starting at the 0 o'clock position.
//! A single `'.'` stands for an increment of 5 minutes.
//! 
//! 
//! ## Some time examples on the 12 hour clock
//! 
//! 00:00 is `-=-`  
//! 03:00 is `--=-`  
//! 06:00 is `---=-`  
//! 21:40 is 09:40 is `----=---..`
//! 
//! All minutes are rounded to 5 minutes, therefore the str representations of the following times are equal
//! 
//! 00:00 is 00:01 is .. is 00:04

use std::error;
use std::fmt;
use std::iter;
use std::marker::PhantomData;

/// A collection of errors which can happen
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Error {
    /// The given value is invalid for a hand
    InvalidHandValue,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidHandValue => f.write_str("Invalid hand value"),
        }
    }
}

impl error::Error for Error {}

/// A trait describing the properties of a clock hand
pub trait ClockHand {
    /// The granularity of the given hand
    const GRANULARITY: u8;
    /// The maximum value of the given hand
    const MAX: u8;

    /// Converts a hand value into a number of long and short symbols
    fn to_long_short(value: u8) -> (u8, u8);
}

/// Hour marker struct for [`Hand`]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Hour;

impl ClockHand for Hour {
    const GRANULARITY: u8 = 1;
    const MAX: u8 = 24;

    fn to_long_short(value: u8) -> (u8, u8) {
        (value / 3 + 1, value % 3)
    }
}

/// Minute marker struct for [`Hand`]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Minute;

impl ClockHand for Minute {
    const GRANULARITY: u8 = 5;
    const MAX: u8 = 60;

    fn to_long_short(value: u8) -> (u8, u8) {
        (value / 15 + 1, value % 15 / Self::GRANULARITY)
    }
}

/// A clock hand
/// 
/// The only way to construct a hand is via the [`TryFrom`]/[`TryInto`] implementations
/// for [`Hand<Hour>`] and [`Hand<Minute>`]
/// 
/// # Example
/// ```
/// # use morseclock::{Hand, Minute, Hour};
/// # 
/// let hour = Hand::<Hour>::try_from(23);
/// let minute = Hand::<Minute>::try_from(59);
/// ```
#[derive(Clone, Copy, Debug, Hash)]
pub struct Hand<T> {
    value: u8,
    _marker: PhantomData<T>,
}

impl<H: ClockHand> PartialEq for Hand<H> {
    fn eq(&self, other: &Self) -> bool {
        self.value / H::GRANULARITY == other.value / H::GRANULARITY
    }
}

impl<H: ClockHand> Eq for Hand<H> {}

impl<H: ClockHand> TryFrom<u32> for Hand<H> {
    type Error = Error;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        if value >= H::MAX as u32 {
            return Err(Error::InvalidHandValue);
        }

        Ok(Hand {
            value: value as u8,
            _marker: PhantomData,
        })
    }
}

impl<H: ClockHand> IntoIterator for Hand<H> {
    type Item = Symbol;
    type IntoIter = HandIter<H>;

    fn into_iter(self) -> Self::IntoIter {
        let (long, short) = H::to_long_short(self.value);

        HandIter {
            long,
            short,
            _marker: PhantomData,
        }
    }
}

/// An iterator over a [`Hand`] which produces a series of [`Symbol`]s
pub struct HandIter<T> {
    long: u8,
    short: u8,
    _marker: PhantomData<T>,
}

impl<T> Iterator for HandIter<T> {
    type Item = Symbol;

    fn next(&mut self) -> Option<Self::Item> {
        if self.long > 0 {
            self.long -= 1;
            Some(Symbol::Long)
        } else if self.short > 0 {
            self.short -= 1;
            Some(Symbol::Short)
        } else {
            None
        }
    }
}

/// The symbols used to describe a time
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Symbol {
    /// The break symbol (used to distinguish between hour and minute)
    Break,
    /// The short symbol
    Short,
    /// Thoe long symbol
    Long,
}

/// The output format of the clock, either 12 or 24 hours
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Format {
    Hour12,
    Hour24,
}

/// A Clock which can produce a morse-like sequence of dits and dashes
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Clock {
    pub hour: Hand<Hour>,
    pub minute: Hand<Minute>,
    pub format: Format,
}

impl Clock {
    pub fn new(hour: Hand<Hour>, minute: Hand<Minute>, format: Format) -> Self {
        Self {
            hour,
            minute,
            format,
        }
    }
}

impl IntoIterator for Clock {
    type Item = Symbol;
    type IntoIter = ClockIter;

    fn into_iter(mut self) -> Self::IntoIter {
        if self.format == Format::Hour12 {
            self.hour.value %= 12;
        }

        ClockIter(
            self.hour
                .into_iter()
                .chain(iter::once(Symbol::Break))
                .chain(self.minute.into_iter()),
        )
    }
}

/// An iterator over a [`Clock`] which produces a series of [`Symbol`]s
pub struct ClockIter(
    iter::Chain<iter::Chain<HandIter<Hour>, iter::Once<Symbol>>, HandIter<Minute>>,
);

impl Iterator for ClockIter {
    type Item = Symbol;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

/// An extension trait for iterators which yield [`Symbol`]s
pub trait MorseExt {
    type Output;
    fn morse(self) -> Self::Output;
}

/// An iterator adapter which produces a series of morsecode-like symbols
///
/// See [`MorseExt`]
pub struct Morse<I>(I);

impl<I> MorseExt for I
where
    I: Iterator<Item = Symbol>,
{
    type Output = Morse<I>;

    fn morse(self) -> Self::Output {
        Morse(self)
    }
}

impl<I> Iterator for Morse<I>
where
    I: Iterator<Item = Symbol>,
{
    type Item = char;

    fn next(&mut self) -> Option<Self::Item> {
        match self.0.next() {
            Some(Symbol::Break) => Some('='),
            Some(Symbol::Short) => Some('.'),
            Some(Symbol::Long) => Some('-'),
            None => None,
        }
    }
}

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

    macro_rules! eq {
        (($hour:expr, $minute:expr), $result_h12:expr) => {
            let hour = $hour.try_into().unwrap();
            let minute = $minute.try_into().unwrap();

            let dashes: String = Clock::new(hour, minute, Format::Hour12)
                .into_iter()
                .morse()
                .collect();

            assert_eq!(dashes, $result_h12);

            if $hour >= 12 {
                let dashes: String = Clock::new(hour, minute, Format::Hour24)
                    .into_iter()
                    .morse()
                    .collect();

                assert_eq!(dashes, concat!("----", $result_h12));
            }
        };
    }

    #[test]
    fn samples() {
        eq!((00, 00), "-=-");
        eq!((23, 59), "----..=----..");
        eq!((12, 00), "-=-");
        eq!((12, 15), "-=--");
        eq!((12, 30), "-=---");
        eq!((12, 34), "-=---");
        eq!((12, 35), "-=---.");
        eq!((14, 45), "-..=----");
        eq!((17, 47), "--..=----");
        eq!((18, 32), "---=---");
    }

    #[test]
    fn hand_equality() {
        assert_eq!(Hand::<Minute>::try_from(0), Hand::<Minute>::try_from(4));
    }
}