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
use chrono::{self, NaiveDate, NaiveDateTime, NaiveTime, Utc};
use chrono::format::{DelayedFormat, Item};
use std::ops::Deref;
use std::marker::PhantomData;
use std::borrow::Borrow;
use std::error::Error;
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::vec::IntoIter;
use super::ChronoDateTime;

/** 
A date value produced and consumed by date formats.

`DateValue` is a very thin wrapper over `DateTime<Utc>` that doesn't carry any formatting semantics.
Like `FormattableDateValue`, this type is used for binding generics in methods that accept date values but it ignores any format on the input type.
You probably won't need to use it directly except to clobber the format on a `Date<M>` or `DateTime<Utc>` value.
*/
#[derive(Debug, Clone, PartialEq)]
pub struct DateValue(ChronoDateTime);

impl DateValue {
    /** Equivalent to `DateTime<Utc>::now()` */
    pub fn now() -> Self {
        DateValue(Utc::now())
    }

    /** Construct a `DateValue` from individual parts. */
    pub fn build(year: i32, month: u32, day: u32, hour: u32, minute: u32, second: u32, milli: u32) -> Self {
        let ndate = NaiveDate::from_ymd(year, month, day);
        let ntime = NaiveTime::from_hms_milli(hour, minute, second, milli);

        let date = ChronoDateTime::from_utc(NaiveDateTime::new(ndate, ntime), Utc);

        DateValue(date)
    }
}

impl<TFormat> From<FormattableDateValue<TFormat>> for DateValue {
    fn from(date: FormattableDateValue<TFormat>) -> Self {
        date.0
    }
}

impl From<ChronoDateTime> for DateValue {
    fn from(date: ChronoDateTime) -> Self {
        DateValue(date)
    }
}

impl PartialEq<ChronoDateTime> for DateValue {
    fn eq(&self, other: &ChronoDateTime) -> bool {
        PartialEq::eq(&self.0, other)
    }

    fn ne(&self, other: &ChronoDateTime) -> bool {
        PartialEq::ne(&self.0, other)
    }
}

impl PartialEq<DateValue> for ChronoDateTime {
    fn eq(&self, other: &DateValue) -> bool {
        PartialEq::eq(self, &other.0)
    }

    fn ne(&self, other: &DateValue) -> bool {
        PartialEq::ne(self, &other.0)
    }
}

impl Borrow<ChronoDateTime> for DateValue {
    fn borrow(&self) -> &ChronoDateTime {
        &self.0
    }
}

impl Deref for DateValue {
    type Target = ChronoDateTime;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/** 
A date value paired with a format.

`FormattableDateValue<F>` bundles a `DateValue` with a specific format and is used to ensure the formats of mappable date types aren't accidentally changed.
Like `DateValue`, this type is used for binding generics in methods that accept date values but it requires the input type uses a specific format.
You probably don't need to use it directly except to ensure date formats aren't silently changed.
*/
#[derive(Debug, Clone, PartialEq)]
pub struct FormattableDateValue<TFormat>(DateValue, PhantomData<TFormat>);

impl<TFormat> FormattableDateValue<TFormat>
where
    TFormat: DateFormat,
{
    /** Format the wrapped date value using the generic format. */
    pub fn format<'a>(&'a self) -> FormattedDate<'a> {
        TFormat::format(&self.0)
    }

    /** Parse a date value using the generic format. */
    pub fn parse(date: &str) -> Result<Self, ParseError> {
        let date = TFormat::parse(date)?;

        Ok(FormattableDateValue::from(date))
    }
}

impl<TFormat> From<DateValue> for FormattableDateValue<TFormat> {
    fn from(date: DateValue) -> Self {
        FormattableDateValue(date.into(), PhantomData)
    }
}

impl<TFormat> Borrow<ChronoDateTime> for FormattableDateValue<TFormat> {
    fn borrow(&self) -> &ChronoDateTime {
        self.0.borrow()
    }
}

impl<TFormat> PartialEq<ChronoDateTime> for FormattableDateValue<TFormat> {
    fn eq(&self, other: &ChronoDateTime) -> bool {
        PartialEq::eq(&self.0, other)
    }

    fn ne(&self, other: &ChronoDateTime) -> bool {
        PartialEq::ne(&self.0, other)
    }
}

impl<TFormat> PartialEq<FormattableDateValue<TFormat>> for ChronoDateTime {
    fn eq(&self, other: &FormattableDateValue<TFormat>) -> bool {
        PartialEq::eq(self, &other.0)
    }

    fn ne(&self, other: &FormattableDateValue<TFormat>) -> bool {
        PartialEq::ne(self, &other.0)
    }
}

/**
A format used for parsing and formatting dates.

The format is specified as two functions: `parse` and `format`.
A general `DateValue` is used as an intermediate value passed as input and produced as output for formatting.

# Examples

The easiest way to implement `DateFormat` is to derive `ElasticDateFormat`
on a unit struct:

```
# #[macro_use]
# extern crate elastic_types;
# #[macro_use]
# extern crate elastic_types_derive;
# extern crate chrono;
# use elastic_types::prelude::*;
# fn main() {
#[derive(Default, ElasticDateFormat)]
#[elastic(date_format="yyyy-MM-dd'T'HH:mm:ss")]
struct MyFormat;
# }
```

The `#[elastic(date_format)]` attribute is required,
and must contain a valid [format string](http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html).

> NOTE: Only a small subset of the Joda time format is supported.

You can customise the indexed format name by adding an `#[elastic(date_format_name)]` attribute:

```
# #[macro_use]
# extern crate elastic_types;
# #[macro_use]
# extern crate elastic_types_derive;
# extern crate chrono;
# use elastic_types::prelude::*;
# fn main() {
#[derive(Default, ElasticDateFormat)]
#[elastic(date_format="yyyyMMdd'T'HHmmssZ", date_format_name="basic_date_time_no_millis")]
struct MyFormat;
# }
```
*/
pub trait DateFormat
where
    Self: Default,
{
    /** Parses a date string to a `chrono::DateTime<Utc>` result. */
    fn parse(date: &str) -> Result<DateValue, ParseError>;

    /** Formats a given `chrono::DateTime<Utc>` as a string. */
    fn format<'a>(date: &'a DateValue) -> FormattedDate<'a>;

    /**
    The name of the format.
    
    This is the string used when defining the format in the field mapping.
    */
    fn name() -> &'static str;
}

/**
A formatted date.

This type can avoid allocating strings for date formats.
*/
pub struct FormattedDate<'a> {
    inner: FormattedDateInner<'a>,
}

enum FormattedDateInner<'a> {
    Delayed(DelayedFormat<IntoIter<Item<'a>>>),
    Buffered(String),
    Number(i64),
}

impl<'a> Display for FormattedDateInner<'a> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        fn fmt_inner<T>(inner: &T, f: &mut Formatter) -> FmtResult
        where
            T: Display,
        {
            inner.fmt(f)
        }

        match *self {
            FormattedDateInner::Delayed(ref inner) => fmt_inner(inner, f),
            FormattedDateInner::Buffered(ref inner) => fmt_inner(inner, f),
            FormattedDateInner::Number(ref inner) => fmt_inner(inner, f),
        }
    }
}

impl<'a> Display for FormattedDate<'a> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        self.inner.fmt(f)
    }
}

impl<'a> From<DelayedFormat<IntoIter<Item<'a>>>> for FormattedDate<'a> {
    fn from(formatted: DelayedFormat<IntoIter<Item<'a>>>) -> Self {
        FormattedDate {
            inner: FormattedDateInner::Delayed(formatted),
        }
    }
}

impl<'a> From<String> for FormattedDate<'a> {
    fn from(formatted: String) -> Self {
        FormattedDate {
            inner: FormattedDateInner::Buffered(formatted),
        }
    }
}

impl<'a> From<i64> for FormattedDate<'a> {
    fn from(formatted: i64) -> Self {
        FormattedDate {
            inner: FormattedDateInner::Number(formatted),
        }
    }
}

/** Represents an error encountered during parsing. */
#[derive(Debug)]
pub struct ParseError {
    kind: ParseErrorKind,
}

#[derive(Debug)]
enum ParseErrorKind {
    Chrono(chrono::ParseError),
    Other(String),
}

impl Display for ParseError {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        match self.kind {
            ParseErrorKind::Chrono(ref err) => write!(f, "Chrono error: {}", err),
            ParseErrorKind::Other(ref err) => write!(f, "Error: {}", err),
        }
    }
}

impl Error for ParseError {
    fn description(&self) -> &str {
        match self.kind {
            ParseErrorKind::Chrono(ref err) => err.description(),
            ParseErrorKind::Other(ref err) => &err[..],
        }
    }

    fn cause(&self) -> Option<&Error> {
        match self.kind {
            ParseErrorKind::Chrono(ref err) => Some(err),
            ParseErrorKind::Other(_) => None,
        }
    }
}

impl From<chrono::ParseError> for ParseError {
    fn from(err: chrono::ParseError) -> ParseError {
        ParseError {
            kind: ParseErrorKind::Chrono(err),
        }
    }
}

impl From<String> for ParseError {
    fn from(err: String) -> ParseError {
        ParseError {
            kind: ParseErrorKind::Other(err),
        }
    }
}