1 /*
2  * hunt-time: A time library for D programming language.
3  *
4  * Copyright (C) 2015-2018 HuntLabs
5  *
6  * Website: https://www.huntlabs.net/
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 
12 module hunt.time.Year;
13 
14 import hunt.time.temporal.ChronoField;
15 import hunt.time.temporal.ChronoUnit;
16 
17 import hunt.stream.DataInput;
18 import hunt.stream.DataOutput;
19 import hunt.Exceptions;
20 
21 //import hunt.io.ObjectInputStream;
22 import hunt.stream.Common;
23 import hunt.time.chrono.Chronology;
24 import hunt.time.chrono.IsoChronology;
25 // import hunt.time.format.DateTimeFormatter;
26 // import hunt.time.format.DateTimeFormatterBuilder;
27 import hunt.time.format.DateTimeParseException;
28 import hunt.time.format.SignStyle;
29 import hunt.time.temporal.ChronoField;
30 import hunt.time.temporal.ChronoUnit;
31 import hunt.time.temporal.Temporal;
32 import hunt.time.temporal.TemporalAccessor;
33 import hunt.time.temporal.TemporalAdjuster;
34 import hunt.time.temporal.TemporalAmount;
35 import hunt.time.temporal.TemporalField;
36 import hunt.time.temporal.TemporalQueries;
37 import hunt.time.temporal.TemporalQuery;
38 import hunt.time.temporal.TemporalUnit;
39 import hunt.time.Exceptions;
40 import hunt.time.temporal.ValueRange;
41 import hunt.Functions;
42 import hunt.time.ZoneId;
43 import hunt.time.Clock;
44 import hunt.time.Month;
45 import hunt.time.MonthDay;
46 import hunt.time.LocalDate;
47 import hunt.time.YearMonth;
48 import hunt.time.Exceptions;
49 import hunt.Long;
50 import hunt.math.Helper;
51 import hunt.util.Common;
52 import hunt.time.Ser;
53 import std.conv;
54 import hunt.time.util.Common;
55 /**
56  * A year _in the ISO-8601 calendar system, such as {@code 2007}.
57  * !(p)
58  * {@code Year} is an immutable date-time object that represents a year.
59  * Any field that can be derived from a year can be obtained.
60  * !(p)
61  * !(b)Note that years _in the ISO chronology only align with years _in the
62  * Gregorian-Julian system for modern years. Parts of Russia did not switch to the
63  * modern Gregorian/ISO rules until 1920.
64  * As such, historical years must be treated with caution.</b>
65  * !(p)
66  * This class does not store or represent a month, day, time or time-zone.
67  * For example, the value "2007" can be stored _in a {@code Year}.
68  * !(p)
69  * Years represented by this class follow the ISO-8601 standard and use
70  * the proleptic numbering system. Year 1 is preceded by year 0, then by year -1.
71  * !(p)
72  * The ISO-8601 calendar system is the modern civil calendar system used today
73  * _in most of the world. It is equivalent to the proleptic Gregorian calendar
74  * system, _in which today's rules for leap years are applied for all time.
75  * For most applications written today, the ISO-8601 rules are entirely suitable.
76  * However, any application that makes use of historical dates, and requires them
77  * to be accurate will find the ISO-8601 approach unsuitable.
78  *
79  * !(p)
80  * This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
81  * class; use of identity-sensitive operations (including reference equality
82  * ({@code ==}), identity hash code, or synchronization) on instances of
83  * {@code Year} may have unpredictable results and should be avoided.
84  * The {@code equals} method should be used for comparisons.
85  *
86  * @implSpec
87  * This class is immutable and thread-safe.
88  *
89  * @since 1.8
90  */
91 public final class Year
92         : Temporal, TemporalAdjuster, Comparable!(Year) { // , Serializable
93 
94     /**
95      * The minimum supported year, '-999,999,999'.
96      */
97     public enum int MIN_VALUE = -999_999_999;
98     
99     /**
100      * The maximum supported year, '+999,999,999'.
101      */
102     public enum int MAX_VALUE = 999_999_999;
103 
104     /**
105      * Parser.
106      */
107     //  __gshared DateTimeFormatter _PARSER ;
108 
109     //  public static ref  DateTimeFormatter PARSER()
110     //  {
111     //      if(_PARSER is null)
112     //      {
113     //          _PARSER = new DateTimeFormatterBuilder()
114     //         .appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
115     //         .toFormatter();
116     //      }
117     //      return _PARSER;
118     //  }
119 
120     // shared static this()
121     // {
122     //     PARSER = new DateTimeFormatterBuilder()
123     //     .appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
124     //     .toFormatter();
125         // mixin(MakeGlobalVar!(DateTimeFormatter)("PARSER",`new DateTimeFormatterBuilder()
126         // .appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD)
127         // .toFormatter()`));
128     // }
129 
130     /**
131      * The year being represented.
132      */
133     private int year;
134 
135     //-----------------------------------------------------------------------
136     /**
137      * Obtains the current year from the system clock _in the default time-zone.
138      * !(p)
139      * This will query the {@link Clock#systemDefaultZone() system clock} _in the default
140      * time-zone to obtain the current year.
141      * !(p)
142      * Using this method will prevent the ability to use an alternate clock for testing
143      * because the clock is hard-coded.
144      *
145      * @return the current year using the system clock and default time-zone, not null
146      */
147     public static Year now() {
148         return now(Clock.systemDefaultZone());
149     }
150 
151     /**
152      * Obtains the current year from the system clock _in the specified time-zone.
153      * !(p)
154      * This will query the {@link Clock#system(ZoneId) system clock} to obtain the current year.
155      * Specifying the time-zone avoids dependence on the default time-zone.
156      * !(p)
157      * Using this method will prevent the ability to use an alternate clock for testing
158      * because the clock is hard-coded.
159      *
160      * @param zone  the zone ID to use, not null
161      * @return the current year using the system clock, not null
162      */
163     public static Year now(ZoneId zone) {
164         return now(Clock.system(zone));
165     }
166 
167     /**
168      * Obtains the current year from the specified clock.
169      * !(p)
170      * This will query the specified clock to obtain the current year.
171      * Using this method allows the use of an alternate clock for testing.
172      * The alternate clock may be introduced using {@link Clock dependency injection}.
173      *
174      * @param clock  the clock to use, not null
175      * @return the current year, not null
176      */
177     public static Year now(Clock clock) {
178          LocalDate now = LocalDate.now(clock);  // called once
179         return Year.of(now.getYear());
180     }
181 
182     //-----------------------------------------------------------------------
183     /**
184      * Obtains an instance of {@code Year}.
185      * !(p)
186      * This method accepts a year value from the proleptic ISO calendar system.
187      * !(p)
188      * The year 2AD/CE is represented by 2.!(br)
189      * The year 1AD/CE is represented by 1.!(br)
190      * The year 1BC/BCE is represented by 0.!(br)
191      * The year 2BC/BCE is represented by -1.!(br)
192      *
193      * @param isoYear  the ISO proleptic year to represent, from {@code MIN_VALUE} to {@code MAX_VALUE}
194      * @return the year, not null
195      * @throws DateTimeException if the field is invalid
196      */
197     public static Year of(int isoYear) {
198         ChronoField.YEAR.checkValidValue(isoYear);
199         return new Year(isoYear);
200     }
201 
202     //-----------------------------------------------------------------------
203     /**
204      * Obtains an instance of {@code Year} from a temporal object.
205      * !(p)
206      * This obtains a year based on the specified temporal.
207      * A {@code TemporalAccessor} represents an arbitrary set of date and time information,
208      * which this factory converts to an instance of {@code Year}.
209      * !(p)
210      * The conversion extracts the {@link ChronoField#YEAR year} field.
211      * The extraction is only permitted if the temporal object has an ISO
212      * chronology, or can be converted to a {@code LocalDate}.
213      * !(p)
214      * This method matches the signature of the functional interface {@link TemporalQuery}
215      * allowing it to be used as a query via method reference, {@code Year.from}.
216      *
217      * @param temporal  the temporal object to convert, not null
218      * @return the year, not null
219      * @throws DateTimeException if unable to convert to a {@code Year}
220      */
221     public static Year from(TemporalAccessor temporal) {
222         if (cast(Year)(temporal) !is null) {
223             return cast(Year) temporal;
224         }
225         assert(temporal, "temporal");
226         try {
227             if ((IsoChronology.INSTANCE == Chronology.from(temporal)) == false) {
228                 temporal = LocalDate.from(temporal);
229             }
230             return of(temporal.get(ChronoField.YEAR));
231         } catch (DateTimeException ex) {
232             throw new DateTimeException("Unable to obtain Year from TemporalAccessor: " ~
233                     typeid(temporal).name ~ " of type " ~ typeid(temporal).stringof, ex);
234         }
235     }
236 
237     //-----------------------------------------------------------------------
238     /**
239      * Obtains an instance of {@code Year} from a text string such as {@code 2007}.
240      * !(p)
241      * The string must represent a valid year.
242      * Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol.
243      *
244      * @param text  the text to parse such as "2007", not null
245      * @return the parsed year, not null
246      * @throws DateTimeParseException if the text cannot be parsed
247      */
248     // public static Year parse(string text) {
249     //     return parse(text, PARSER);
250     // }
251 
252     /**
253      * Obtains an instance of {@code Year} from a text string using a specific formatter.
254      * !(p)
255      * The text is parsed using the formatter, returning a year.
256      *
257      * @param text  the text to parse, not null
258      * @param formatter  the formatter to use, not null
259      * @return the parsed year, not null
260      * @throws DateTimeParseException if the text cannot be parsed
261      */
262     // public static Year parse(string text, DateTimeFormatter formatter) {
263     //     assert(formatter, "formatter");
264     //     return formatter.parse(text, new class TemporalQuery!Year{
265     //         Year queryFrom(TemporalAccessor temporal)
266     //         {
267     //             if (cast(Year)(temporal) !is null) {
268     //                 return cast(Year) temporal;
269     //             }
270     //             assert(temporal, "temporal");
271     //             try {
272     //                 if ((IsoChronology.INSTANCE == Chronology.from(temporal)) == false) {
273     //                     temporal = LocalDate.from(temporal);
274     //                 }
275     //                 return of(temporal.get(ChronoField.YEAR));
276     //             } catch (DateTimeException ex) {
277     //                 throw new DateTimeException("Unable to obtain Year from TemporalAccessor: " ~
278     //                         typeid(temporal).name ~ " of type " ~ typeid(temporal).stringof, ex);
279     //             }
280     //         }
281     //     });
282     // }
283 
284     //-------------------------------------------------------------------------
285     /**
286      * Checks if the year is a leap year, according to the ISO proleptic
287      * calendar system rules.
288      * !(p)
289      * This method applies the current rules for leap years across the whole time-line.
290      * In general, a year is a leap year if it is divisible by four without
291      * remainder. However, years divisible by 100, are not leap years, with
292      * the exception of years divisible by 400 which are.
293      * !(p)
294      * For example, 1904 is a leap year it is divisible by 4.
295      * 1900 was not a leap year as it is divisible by 100, however 2000 was a
296      * leap year as it is divisible by 400.
297      * !(p)
298      * The calculation is proleptic - applying the same rules into the far future and far past.
299      * This is historically inaccurate, but is correct for the ISO-8601 standard.
300      *
301      * @param year  the year to check
302      * @return true if the year is leap, false otherwise
303      */
304     public static bool isLeap(long year) {
305         return ((year & 3) == 0) && ((year % 100) != 0 || (year % 400) == 0);
306     }
307 
308     //-----------------------------------------------------------------------
309     /**
310      * Constructor.
311      *
312      * @param year  the year to represent
313      */
314     this(int year) {
315         this.year = year;
316     }
317 
318     //-----------------------------------------------------------------------
319     /**
320      * Gets the year value.
321      * !(p)
322      * The year returned by this method is proleptic as per {@code get(YEAR)}.
323      *
324      * @return the year, {@code MIN_VALUE} to {@code MAX_VALUE}
325      */
326     public int getValue() {
327         return year;
328     }
329 
330     //-----------------------------------------------------------------------
331     /**
332      * Checks if the specified field is supported.
333      * !(p)
334      * This checks if this year can be queried for the specified field.
335      * If false, then calling the {@link #range(TemporalField) range},
336      * {@link #get(TemporalField) get} and {@link #_with(TemporalField, long)}
337      * methods will throw an exception.
338      * !(p)
339      * If the field is a {@link ChronoField} then the query is implemented here.
340      * The supported fields are:
341      * !(ul)
342      * !(li){@code YEAR_OF_ERA}
343      * !(li){@code YEAR}
344      * !(li){@code ERA}
345      * </ul>
346      * All other {@code ChronoField} instances will return false.
347      * !(p)
348      * If the field is not a {@code ChronoField}, then the result of this method
349      * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)}
350      * passing {@code this} as the argument.
351      * Whether the field is supported is determined by the field.
352      *
353      * @param field  the field to check, null returns false
354      * @return true if the field is supported on this year, false if not
355      */
356     override
357     public bool isSupported(TemporalField field) {
358         if (cast(ChronoField)(field) !is null) {
359             return field == ChronoField.YEAR || field == ChronoField.YEAR_OF_ERA || field == ChronoField.ERA;
360         }
361         return field !is null && field.isSupportedBy(this);
362     }
363 
364     /**
365      * Checks if the specified unit is supported.
366      * !(p)
367      * This checks if the specified unit can be added to, or subtracted from, this year.
368      * If false, then calling the {@link #plus(long, TemporalUnit)} and
369      * {@link #minus(long, TemporalUnit) minus} methods will throw an exception.
370      * !(p)
371      * If the unit is a {@link ChronoUnit} then the query is implemented here.
372      * The supported units are:
373      * !(ul)
374      * !(li){@code YEARS}
375      * !(li){@code DECADES}
376      * !(li){@code CENTURIES}
377      * !(li){@code MILLENNIA}
378      * !(li){@code ERAS}
379      * </ul>
380      * All other {@code ChronoUnit} instances will return false.
381      * !(p)
382      * If the unit is not a {@code ChronoUnit}, then the result of this method
383      * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)}
384      * passing {@code this} as the argument.
385      * Whether the unit is supported is determined by the unit.
386      *
387      * @param unit  the unit to check, null returns false
388      * @return true if the unit can be added/subtracted, false if not
389      */
390     override
391     public bool isSupported(TemporalUnit unit) {
392         if (cast(ChronoUnit)(unit) !is null) {
393             return unit == ChronoUnit.YEARS || unit == ChronoUnit.DECADES || unit == ChronoUnit.CENTURIES || unit == ChronoUnit.MILLENNIA || unit == ChronoUnit.ERAS;
394         }
395         return unit !is null && unit.isSupportedBy(this);
396     }
397 
398     //-----------------------------------------------------------------------
399     /**
400      * Gets the range of valid values for the specified field.
401      * !(p)
402      * The range object expresses the minimum and maximum valid values for a field.
403      * This year is used to enhance the accuracy of the returned range.
404      * If it is not possible to return the range, because the field is not supported
405      * or for some other reason, an exception is thrown.
406      * !(p)
407      * If the field is a {@link ChronoField} then the query is implemented here.
408      * The {@link #isSupported(TemporalField) supported fields} will return
409      * appropriate range instances.
410      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
411      * !(p)
412      * If the field is not a {@code ChronoField}, then the result of this method
413      * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)}
414      * passing {@code this} as the argument.
415      * Whether the range can be obtained is determined by the field.
416      *
417      * @param field  the field to query the range for, not null
418      * @return the range of valid values for the field, not null
419      * @throws DateTimeException if the range for the field cannot be obtained
420      * @throws UnsupportedTemporalTypeException if the field is not supported
421      */
422     override
423     public ValueRange range(TemporalField field) {
424         if (field == ChronoField.YEAR_OF_ERA) {
425             return (year <= 0 ? ValueRange.of(1, MAX_VALUE + 1) : ValueRange.of(1, MAX_VALUE));
426         }
427         return /* Temporal. super.*/super_range(field);
428         
429     }
430     ValueRange super_range(TemporalField field) {
431         if (cast(ChronoField)(field) !is null) {
432             if (isSupported(field)) {
433                 return field.range();
434             }
435             throw new UnsupportedTemporalTypeException("Unsupported field: " ~ typeid(field).name);
436         }
437         assert(field, "field");
438         return field.rangeRefinedBy(this);
439     }
440     /**
441      * Gets the value of the specified field from this year as an {@code int}.
442      * !(p)
443      * This queries this year for the value of the specified field.
444      * The returned value will always be within the valid range of values for the field.
445      * If it is not possible to return the value, because the field is not supported
446      * or for some other reason, an exception is thrown.
447      * !(p)
448      * If the field is a {@link ChronoField} then the query is implemented here.
449      * The {@link #isSupported(TemporalField) supported fields} will return valid
450      * values based on this year.
451      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
452      * !(p)
453      * If the field is not a {@code ChronoField}, then the result of this method
454      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
455      * passing {@code this} as the argument. Whether the value can be obtained,
456      * and what the value represents, is determined by the field.
457      *
458      * @param field  the field to get, not null
459      * @return the value for the field
460      * @throws DateTimeException if a value for the field cannot be obtained or
461      *         the value is outside the range of valid values for the field
462      * @throws UnsupportedTemporalTypeException if the field is not supported or
463      *         the range of values exceeds an {@code int}
464      * @throws ArithmeticException if numeric overflow occurs
465      */
466     override  // override for Javadoc
467     public int get(TemporalField field) {
468         return range(field).checkValidIntValue(getLong(field), field);
469     }
470 
471     /**
472      * Gets the value of the specified field from this year as a {@code long}.
473      * !(p)
474      * This queries this year for the value of the specified field.
475      * If it is not possible to return the value, because the field is not supported
476      * or for some other reason, an exception is thrown.
477      * !(p)
478      * If the field is a {@link ChronoField} then the query is implemented here.
479      * The {@link #isSupported(TemporalField) supported fields} will return valid
480      * values based on this year.
481      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
482      * !(p)
483      * If the field is not a {@code ChronoField}, then the result of this method
484      * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)}
485      * passing {@code this} as the argument. Whether the value can be obtained,
486      * and what the value represents, is determined by the field.
487      *
488      * @param field  the field to get, not null
489      * @return the value for the field
490      * @throws DateTimeException if a value for the field cannot be obtained
491      * @throws UnsupportedTemporalTypeException if the field is not supported
492      * @throws ArithmeticException if numeric overflow occurs
493      */
494     override
495     public long getLong(TemporalField field) {
496         if (cast(ChronoField)(field) !is null) {
497             auto f = cast(ChronoField) field;
498             {
499                 if ( f ==  ChronoField.YEAR_OF_ERA) return (year < 1 ? 1 - year : year);
500                 if ( f ==  ChronoField.YEAR) return year;
501                 if ( f ==  ChronoField.ERA) return (year < 1 ? 0 : 1);
502             }
503             throw new UnsupportedTemporalTypeException("Unsupported field: " ~ f.toString);
504         }
505         return field.getFrom(this);
506     }
507 
508     //-----------------------------------------------------------------------
509     /**
510      * Checks if the year is a leap year, according to the ISO proleptic
511      * calendar system rules.
512      * !(p)
513      * This method applies the current rules for leap years across the whole time-line.
514      * In general, a year is a leap year if it is divisible by four without
515      * remainder. However, years divisible by 100, are not leap years, with
516      * the exception of years divisible by 400 which are.
517      * !(p)
518      * For example, 1904 is a leap year it is divisible by 4.
519      * 1900 was not a leap year as it is divisible by 100, however 2000 was a
520      * leap year as it is divisible by 400.
521      * !(p)
522      * The calculation is proleptic - applying the same rules into the far future and far past.
523      * This is historically inaccurate, but is correct for the ISO-8601 standard.
524      *
525      * @return true if the year is leap, false otherwise
526      */
527     public bool isLeap() {
528         return Year.isLeap(year);
529     }
530 
531     /**
532      * Checks if the month-day is valid for this year.
533      * !(p)
534      * This method checks whether this year and the input month and day form
535      * a valid date.
536      *
537      * @param monthDay  the month-day to validate, null returns false
538      * @return true if the month and day are valid for this year
539      */
540     public bool isValidMonthDay(MonthDay monthDay) {
541         return monthDay !is null && monthDay.isValidYear(year);
542     }
543 
544     /**
545      * Gets the length of this year _in days.
546      *
547      * @return the length of this year _in days, 365 or 366
548      */
549     public int length() {
550         return isLeap() ? 366 : 365;
551     }
552 
553     //-----------------------------------------------------------------------
554     /**
555      * Returns an adjusted copy of this year.
556      * !(p)
557      * This returns a {@code Year}, based on this one, with the year adjusted.
558      * The adjustment takes place using the specified adjuster strategy object.
559      * Read the documentation of the adjuster to understand what adjustment will be made.
560      * !(p)
561      * The result of this method is obtained by invoking the
562      * {@link TemporalAdjuster#adjustInto(Temporal)} method on the
563      * specified adjuster passing {@code this} as the argument.
564      * !(p)
565      * This instance is immutable and unaffected by this method call.
566      *
567      * @param adjuster the adjuster to use, not null
568      * @return a {@code Year} based on {@code this} with the adjustment made, not null
569      * @throws DateTimeException if the adjustment cannot be made
570      * @throws ArithmeticException if numeric overflow occurs
571      */
572     override
573     public Year _with(TemporalAdjuster adjuster) {
574         return cast(Year) adjuster.adjustInto(this);
575     }
576 
577     /**
578      * Returns a copy of this year with the specified field set to a new value.
579      * !(p)
580      * This returns a {@code Year}, based on this one, with the value
581      * for the specified field changed.
582      * If it is not possible to set the value, because the field is not supported or for
583      * some other reason, an exception is thrown.
584      * !(p)
585      * If the field is a {@link ChronoField} then the adjustment is implemented here.
586      * The supported fields behave as follows:
587      * !(ul)
588      * !(li){@code YEAR_OF_ERA} -
589      *  Returns a {@code Year} with the specified year-of-era
590      *  The era will be unchanged.
591      * !(li){@code YEAR} -
592      *  Returns a {@code Year} with the specified year.
593      *  This completely replaces the date and is equivalent to {@link #of(int)}.
594      * !(li){@code ERA} -
595      *  Returns a {@code Year} with the specified era.
596      *  The year-of-era will be unchanged.
597      * </ul>
598      * !(p)
599      * In all cases, if the new value is outside the valid range of values for the field
600      * then a {@code DateTimeException} will be thrown.
601      * !(p)
602      * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}.
603      * !(p)
604      * If the field is not a {@code ChronoField}, then the result of this method
605      * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)}
606      * passing {@code this} as the argument. In this case, the field determines
607      * whether and how to adjust the instant.
608      * !(p)
609      * This instance is immutable and unaffected by this method call.
610      *
611      * @param field  the field to set _in the result, not null
612      * @param newValue  the new value of the field _in the result
613      * @return a {@code Year} based on {@code this} with the specified field set, not null
614      * @throws DateTimeException if the field cannot be set
615      * @throws UnsupportedTemporalTypeException if the field is not supported
616      * @throws ArithmeticException if numeric overflow occurs
617      */
618     override
619     public Year _with(TemporalField field, long newValue) {
620         if (cast(ChronoField)(field) !is null) {
621             ChronoField f = cast(ChronoField) field;
622             f.checkValidValue(newValue);
623             {
624                 if( f == ChronoField.YEAR_OF_ERA) return Year.of(cast(int) (year < 1 ? 1 - newValue : newValue));
625                 if( f == ChronoField.YEAR) return Year.of(cast(int) newValue);
626                 if( f == ChronoField.ERA) return (getLong(ChronoField.ERA) == newValue ? this : Year.of(1 - year));
627             }
628             throw new UnsupportedTemporalTypeException("Unsupported field: " ~ f.toString);
629         }
630         return cast(Year)(field.adjustInto(this, newValue));
631     }
632 
633     //-----------------------------------------------------------------------
634     /**
635      * Returns a copy of this year with the specified amount added.
636      * !(p)
637      * This returns a {@code Year}, based on this one, with the specified amount added.
638      * The amount is typically {@link Period} but may be any other type implementing
639      * the {@link TemporalAmount} interface.
640      * !(p)
641      * The calculation is delegated to the amount object by calling
642      * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free
643      * to implement the addition _in any way it wishes, however it typically
644      * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation
645      * of the amount implementation to determine if it can be successfully added.
646      * !(p)
647      * This instance is immutable and unaffected by this method call.
648      *
649      * @param amountToAdd  the amount to add, not null
650      * @return a {@code Year} based on this year with the addition made, not null
651      * @throws DateTimeException if the addition cannot be made
652      * @throws ArithmeticException if numeric overflow occurs
653      */
654     override
655     public Year plus(TemporalAmount amountToAdd) {
656         return cast(Year) amountToAdd.addTo(this);
657     }
658 
659     /**
660      * Returns a copy of this year with the specified amount added.
661      * !(p)
662      * This returns a {@code Year}, based on this one, with the amount
663      * _in terms of the unit added. If it is not possible to add the amount, because the
664      * unit is not supported or for some other reason, an exception is thrown.
665      * !(p)
666      * If the field is a {@link ChronoUnit} then the addition is implemented here.
667      * The supported fields behave as follows:
668      * !(ul)
669      * !(li){@code YEARS} -
670      *  Returns a {@code Year} with the specified number of years added.
671      *  This is equivalent to {@link #plusYears(long)}.
672      * !(li){@code DECADES} -
673      *  Returns a {@code Year} with the specified number of decades added.
674      *  This is equivalent to calling {@link #plusYears(long)} with the amount
675      *  multiplied by 10.
676      * !(li){@code CENTURIES} -
677      *  Returns a {@code Year} with the specified number of centuries added.
678      *  This is equivalent to calling {@link #plusYears(long)} with the amount
679      *  multiplied by 100.
680      * !(li){@code MILLENNIA} -
681      *  Returns a {@code Year} with the specified number of millennia added.
682      *  This is equivalent to calling {@link #plusYears(long)} with the amount
683      *  multiplied by 1,000.
684      * !(li){@code ERAS} -
685      *  Returns a {@code Year} with the specified number of eras added.
686      *  Only two eras are supported so the amount must be one, zero or minus one.
687      *  If the amount is non-zero then the year is changed such that the year-of-era
688      *  is unchanged.
689      * </ul>
690      * !(p)
691      * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}.
692      * !(p)
693      * If the field is not a {@code ChronoUnit}, then the result of this method
694      * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)}
695      * passing {@code this} as the argument. In this case, the unit determines
696      * whether and how to perform the addition.
697      * !(p)
698      * This instance is immutable and unaffected by this method call.
699      *
700      * @param amountToAdd  the amount of the unit to add to the result, may be negative
701      * @param unit  the unit of the amount to add, not null
702      * @return a {@code Year} based on this year with the specified amount added, not null
703      * @throws DateTimeException if the addition cannot be made
704      * @throws UnsupportedTemporalTypeException if the unit is not supported
705      * @throws ArithmeticException if numeric overflow occurs
706      */
707     override
708     public Year plus(long amountToAdd, TemporalUnit unit) {
709         if (cast(ChronoUnit)(unit) !is null) {
710             auto f = cast(ChronoUnit) unit;
711             {
712                 if( f == ChronoUnit.YEARS) return plusYears(amountToAdd);
713                 if( f == ChronoUnit.DECADES) return plusYears(MathHelper.multiplyExact(amountToAdd, 10));
714                 if( f == ChronoUnit.CENTURIES) return plusYears(MathHelper.multiplyExact(amountToAdd, 100));
715                 if( f == ChronoUnit.MILLENNIA) return plusYears(MathHelper.multiplyExact(amountToAdd, 1000));
716                 if( f == ChronoUnit.ERAS) return _with(ChronoField.ERA, MathHelper.addExact(getLong(ChronoField.ERA), amountToAdd));
717             }
718             throw new UnsupportedTemporalTypeException("Unsupported unit: " ~ f.toString);
719         }
720         return cast(Year)(unit.addTo(this, amountToAdd));
721     }
722 
723     /**
724      * Returns a copy of this {@code Year} with the specified number of years added.
725      * !(p)
726      * This instance is immutable and unaffected by this method call.
727      *
728      * @param yearsToAdd  the years to add, may be negative
729      * @return a {@code Year} based on this year with the years added, not null
730      * @throws DateTimeException if the result exceeds the supported range
731      */
732     public Year plusYears(long yearsToAdd) {
733         if (yearsToAdd == 0) {
734             return this;
735         }
736         return of(ChronoField.YEAR.checkValidIntValue(year + yearsToAdd));  // overflow safe
737     }
738 
739     //-----------------------------------------------------------------------
740     /**
741      * Returns a copy of this year with the specified amount subtracted.
742      * !(p)
743      * This returns a {@code Year}, based on this one, with the specified amount subtracted.
744      * The amount is typically {@link Period} but may be any other type implementing
745      * the {@link TemporalAmount} interface.
746      * !(p)
747      * The calculation is delegated to the amount object by calling
748      * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free
749      * to implement the subtraction _in any way it wishes, however it typically
750      * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation
751      * of the amount implementation to determine if it can be successfully subtracted.
752      * !(p)
753      * This instance is immutable and unaffected by this method call.
754      *
755      * @param amountToSubtract  the amount to subtract, not null
756      * @return a {@code Year} based on this year with the subtraction made, not null
757      * @throws DateTimeException if the subtraction cannot be made
758      * @throws ArithmeticException if numeric overflow occurs
759      */
760     override
761     public Year minus(TemporalAmount amountToSubtract) {
762         return cast(Year) amountToSubtract.subtractFrom(this);
763     }
764 
765     /**
766      * Returns a copy of this year with the specified amount subtracted.
767      * !(p)
768      * This returns a {@code Year}, based on this one, with the amount
769      * _in terms of the unit subtracted. If it is not possible to subtract the amount,
770      * because the unit is not supported or for some other reason, an exception is thrown.
771      * !(p)
772      * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated.
773      * See that method for a full description of how addition, and thus subtraction, works.
774      * !(p)
775      * This instance is immutable and unaffected by this method call.
776      *
777      * @param amountToSubtract  the amount of the unit to subtract from the result, may be negative
778      * @param unit  the unit of the amount to subtract, not null
779      * @return a {@code Year} based on this year with the specified amount subtracted, not null
780      * @throws DateTimeException if the subtraction cannot be made
781      * @throws UnsupportedTemporalTypeException if the unit is not supported
782      * @throws ArithmeticException if numeric overflow occurs
783      */
784     override
785     public Year minus(long amountToSubtract, TemporalUnit unit) {
786         return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit));
787     }
788 
789     /**
790      * Returns a copy of this {@code Year} with the specified number of years subtracted.
791      * !(p)
792      * This instance is immutable and unaffected by this method call.
793      *
794      * @param yearsToSubtract  the years to subtract, may be negative
795      * @return a {@code Year} based on this year with the year subtracted, not null
796      * @throws DateTimeException if the result exceeds the supported range
797      */
798     public Year minusYears(long yearsToSubtract) {
799         return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract));
800     }
801 
802     //-----------------------------------------------------------------------
803     /**
804      * Queries this year using the specified query.
805      * !(p)
806      * This queries this year using the specified query strategy object.
807      * The {@code TemporalQuery} object defines the logic to be used to
808      * obtain the result. Read the documentation of the query to understand
809      * what the result of this method will be.
810      * !(p)
811      * The result of this method is obtained by invoking the
812      * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the
813      * specified query passing {@code this} as the argument.
814      *
815      * @param !(R) the type of the result
816      * @param query  the query to invoke, not null
817      * @return the query result, null may be returned (defined by the query)
818      * @throws DateTimeException if unable to query (defined by the query)
819      * @throws ArithmeticException if numeric overflow occurs (defined by the query)
820      */
821     /*@SuppressWarnings("unchecked")*/
822     // override
823     public R query(R)(TemporalQuery!(R) query) {
824         if (query == TemporalQueries.chronology()) {
825             return cast(R) IsoChronology.INSTANCE;
826         } else if (query == TemporalQueries.precision()) {
827             return cast(R) (ChronoUnit.YEARS);
828         }
829         return /* Temporal. */super_query(query);
830     }
831     R super_query(R)(TemporalQuery!(R) query) {
832          if (query == TemporalQueries.zoneId()
833                  || query == TemporalQueries.chronology()
834                  || query == TemporalQueries.precision()) {
835              return null;
836          }
837          return query.queryFrom(this);
838      }
839 
840     /**
841      * Adjusts the specified temporal object to have this year.
842      * !(p)
843      * This returns a temporal object of the same observable type as the input
844      * with the year changed to be the same as this.
845      * !(p)
846      * The adjustment is equivalent to using {@link Temporal#_with(TemporalField, long)}
847      * passing {@link ChronoField#YEAR} as the field.
848      * If the specified temporal object does not use the ISO calendar system then
849      * a {@code DateTimeException} is thrown.
850      * !(p)
851      * In most cases, it is clearer to reverse the calling pattern by using
852      * {@link Temporal#_with(TemporalAdjuster)}:
853      * !(pre)
854      *   // these two lines are equivalent, but the second approach is recommended
855      *   temporal = thisYear.adjustInto(temporal);
856      *   temporal = temporal._with(thisYear);
857      * </pre>
858      * !(p)
859      * This instance is immutable and unaffected by this method call.
860      *
861      * @param temporal  the target object to be adjusted, not null
862      * @return the adjusted object, not null
863      * @throws DateTimeException if unable to make the adjustment
864      * @throws ArithmeticException if numeric overflow occurs
865      */
866     override
867     public Temporal adjustInto(Temporal temporal) {
868         if ((Chronology.from(temporal) == IsoChronology.INSTANCE) == false) {
869             throw new DateTimeException("Adjustment only supported on ISO date-time");
870         }
871         return temporal._with(ChronoField.YEAR, year);
872     }
873 
874     /**
875      * Calculates the amount of time until another year _in terms of the specified unit.
876      * !(p)
877      * This calculates the amount of time between two {@code Year}
878      * objects _in terms of a single {@code TemporalUnit}.
879      * The start and end points are {@code this} and the specified year.
880      * The result will be negative if the end is before the start.
881      * The {@code Temporal} passed to this method is converted to a
882      * {@code Year} using {@link #from(TemporalAccessor)}.
883      * For example, the amount _in decades between two year can be calculated
884      * using {@code startYear.until(endYear, DECADES)}.
885      * !(p)
886      * The calculation returns a whole number, representing the number of
887      * complete units between the two years.
888      * For example, the amount _in decades between 2012 and 2031
889      * will only be one decade as it is one year short of two decades.
890      * !(p)
891      * There are two equivalent ways of using this method.
892      * The first is to invoke this method.
893      * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}:
894      * !(pre)
895      *   // these two lines are equivalent
896      *   amount = start.until(end, YEARS);
897      *   amount = YEARS.between(start, end);
898      * </pre>
899      * The choice should be made based on which makes the code more readable.
900      * !(p)
901      * The calculation is implemented _in this method for {@link ChronoUnit}.
902      * The units {@code YEARS}, {@code DECADES}, {@code CENTURIES},
903      * {@code MILLENNIA} and {@code ERAS} are supported.
904      * Other {@code ChronoUnit} values will throw an exception.
905      * !(p)
906      * If the unit is not a {@code ChronoUnit}, then the result of this method
907      * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)}
908      * passing {@code this} as the first argument and the converted input temporal
909      * as the second argument.
910      * !(p)
911      * This instance is immutable and unaffected by this method call.
912      *
913      * @param endExclusive  the end date, exclusive, which is converted to a {@code Year}, not null
914      * @param unit  the unit to measure the amount _in, not null
915      * @return the amount of time between this year and the end year
916      * @throws DateTimeException if the amount cannot be calculated, or the end
917      *  temporal cannot be converted to a {@code Year}
918      * @throws UnsupportedTemporalTypeException if the unit is not supported
919      * @throws ArithmeticException if numeric overflow occurs
920      */
921     override
922     public long until(Temporal endExclusive, TemporalUnit unit) {
923         Year end = Year.from(endExclusive);
924         if (cast(ChronoUnit)(unit) !is null) {
925             long yearsUntil = (cast(long) end.year) - year;  // no overflow
926             auto f = cast(ChronoUnit) unit;
927             {
928                 if ( f == ChronoUnit.YEARS) return yearsUntil;
929                 if ( f == ChronoUnit.DECADES) return yearsUntil / 10;
930                 if ( f == ChronoUnit.CENTURIES) return yearsUntil / 100;
931                 if ( f == ChronoUnit.MILLENNIA) return yearsUntil / 1000;
932                 if ( f == ChronoUnit.ERAS) return end.getLong(ChronoField.ERA) - getLong(ChronoField.ERA);
933             }
934             throw new UnsupportedTemporalTypeException("Unsupported unit: " ~ f.toString);
935         }
936         return unit.between(this, end);
937     }
938 
939     /**
940      * Formats this year using the specified formatter.
941      * !(p)
942      * This year will be passed to the formatter to produce a string.
943      *
944      * @param formatter  the formatter to use, not null
945      * @return the formatted year string, not null
946      * @throws DateTimeException if an error occurs during printing
947      */
948     // public string format(DateTimeFormatter formatter) {
949     //     assert(formatter, "formatter");
950     //     return formatter.format(this);
951     // }
952 
953     //-----------------------------------------------------------------------
954     /**
955      * Combines this year with a day-of-year to create a {@code LocalDate}.
956      * !(p)
957      * This returns a {@code LocalDate} formed from this year and the specified day-of-year.
958      * !(p)
959      * The day-of-year value 366 is only valid _in a leap year.
960      *
961      * @param dayOfYear  the day-of-year to use, from 1 to 365-366
962      * @return the local date formed from this year and the specified date of year, not null
963      * @throws DateTimeException if the day of year is zero or less, 366 or greater or equal
964      *  to 366 and this is not a leap year
965      */
966     public LocalDate atDay(int dayOfYear) {
967         return LocalDate.ofYearDay(year, dayOfYear);
968     }
969 
970     /**
971      * Combines this year with a month to create a {@code YearMonth}.
972      * !(p)
973      * This returns a {@code YearMonth} formed from this year and the specified month.
974      * All possible combinations of year and month are valid.
975      * !(p)
976      * This method can be used as part of a chain to produce a date:
977      * !(pre)
978      *  LocalDate date = year.atMonth(month).atDay(day);
979      * </pre>
980      *
981      * @param month  the month-of-year to use, not null
982      * @return the year-month formed from this year and the specified month, not null
983      */
984     public YearMonth atMonth(Month month) {
985         return YearMonth.of(year, month);
986     }
987 
988     /**
989      * Combines this year with a month to create a {@code YearMonth}.
990      * !(p)
991      * This returns a {@code YearMonth} formed from this year and the specified month.
992      * All possible combinations of year and month are valid.
993      * !(p)
994      * This method can be used as part of a chain to produce a date:
995      * !(pre)
996      *  LocalDate date = year.atMonth(month).atDay(day);
997      * </pre>
998      *
999      * @param month  the month-of-year to use, from 1 (January) to 12 (December)
1000      * @return the year-month formed from this year and the specified month, not null
1001      * @throws DateTimeException if the month is invalid
1002      */
1003     public YearMonth atMonth(int month) {
1004         return YearMonth.of(year, month);
1005     }
1006 
1007     /**
1008      * Combines this year with a month-day to create a {@code LocalDate}.
1009      * !(p)
1010      * This returns a {@code LocalDate} formed from this year and the specified month-day.
1011      * !(p)
1012      * A month-day of February 29th will be adjusted to February 28th _in the resulting
1013      * date if the year is not a leap year.
1014      *
1015      * @param monthDay  the month-day to use, not null
1016      * @return the local date formed from this year and the specified month-day, not null
1017      */
1018     public LocalDate atMonthDay(MonthDay monthDay) {
1019         return monthDay.atYear(year);
1020     }
1021 
1022     //-----------------------------------------------------------------------
1023     /**
1024      * Compares this year to another year.
1025      * !(p)
1026      * The comparison is based on the value of the year.
1027      * It is "consistent with equals", as defined by {@link Comparable}.
1028      *
1029      * @param other  the other year to compare to, not null
1030      * @return the comparator value, negative if less, positive if greater
1031      */
1032     // override
1033     public int compareTo(Year other) {
1034         return year - other.year;
1035     }
1036 
1037     /**
1038      * Checks if this year is after the specified year.
1039      *
1040      * @param other  the other year to compare to, not null
1041      * @return true if this is after the specified year
1042      */
1043     public bool isAfter(Year other) {
1044         return year > other.year;
1045     }
1046 
1047     /**
1048      * Checks if this year is before the specified year.
1049      *
1050      * @param other  the other year to compare to, not null
1051      * @return true if this point is before the specified year
1052      */
1053     public bool isBefore(Year other) {
1054         return year < other.year;
1055     }
1056 
1057     //-----------------------------------------------------------------------
1058     /**
1059      * Checks if this year is equal to another year.
1060      * !(p)
1061      * The comparison is based on the time-line position of the years.
1062      *
1063      * @param obj  the object to check, null returns false
1064      * @return true if this is equal to the other year
1065      */
1066     override
1067     public bool opEquals(Object obj) {
1068         if (this is obj) {
1069             return true;
1070         }
1071         if (cast(Year)(obj) !is null) {
1072             return year == (cast(Year) obj).year;
1073         }
1074         return false;
1075     }
1076 
1077     /**
1078      * A hash code for this year.
1079      *
1080      * @return a suitable hash code
1081      */
1082     override
1083     public size_t toHash() @trusted nothrow {
1084         return year;
1085     }
1086 
1087     //-----------------------------------------------------------------------
1088     /**
1089      * Outputs this year as a {@code string}.
1090      *
1091      * @return a string representation of this year, not null
1092      */
1093     override
1094     public string toString() {
1095         return to!string(year);
1096     }
1097 
1098     //-----------------------------------------------------------------------
1099     /**
1100      * Writes the object using a
1101      * <a href="{@docRoot}/serialized-form.html#hunt.time.Ser">dedicated serialized form</a>.
1102      * @serialData
1103      * !(pre)
1104      *  _out.writeByte(11);  // identifies a Year
1105      *  _out.writeInt(year);
1106      * </pre>
1107      *
1108      * @return the instance of {@code Ser}, not null
1109      */
1110     private Object writeReplace() {
1111         return new Ser(Ser.YEAR_TYPE, this);
1112     }
1113 
1114     /**
1115      * Defend against malicious streams.
1116      *
1117      * @param s the stream to read
1118      * @throws InvalidObjectException= always
1119      */
1120      ///@gxc
1121     // private void readObject(ObjectInputStream s) /*throws InvalidObjectException*/ {
1122     //     throw new InvalidObjectException("Deserialization via serialization delegate");
1123     // }
1124 
1125     void writeExternal(DataOutput _out) /*throws IOException*/ {
1126         _out.writeInt(year);
1127     }
1128 
1129     static Year readExternal(DataInput _in) /*throws IOException*/ {
1130         return Year.of(_in.readInt());
1131     }
1132 
1133     override 
1134     int opCmp(Year o)
1135     {
1136         return compareTo(o);
1137     }
1138 }