1 /*
   2  * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time.format;
  63 
  64 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
  65 import static java.time.temporal.ChronoField.HOUR_OF_DAY;
  66 import static java.time.temporal.ChronoField.INSTANT_SECONDS;
  67 import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
  68 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  69 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
  70 import static java.time.temporal.ChronoField.OFFSET_SECONDS;
  71 import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
  72 import static java.time.temporal.ChronoField.YEAR;
  73 import static java.time.temporal.ChronoField.ERA;
  74 
  75 import java.lang.ref.SoftReference;
  76 import java.math.BigDecimal;
  77 import java.math.BigInteger;
  78 import java.math.RoundingMode;
  79 import java.text.ParsePosition;
  80 import java.time.DateTimeException;
  81 import java.time.Instant;
  82 import java.time.LocalDate;
  83 import java.time.LocalDateTime;
  84 import java.time.LocalTime;
  85 import java.time.ZoneId;
  86 import java.time.ZoneOffset;
  87 import java.time.chrono.ChronoLocalDate;
  88 import java.time.chrono.ChronoLocalDateTime;
  89 import java.time.chrono.Chronology;
  90 import java.time.chrono.Era;
  91 import java.time.chrono.IsoChronology;
  92 import java.time.format.DateTimeTextProvider.LocaleStore;
  93 import java.time.temporal.ChronoField;
  94 import java.time.temporal.IsoFields;
  95 import java.time.temporal.JulianFields;
  96 import java.time.temporal.TemporalAccessor;
  97 import java.time.temporal.TemporalField;
  98 import java.time.temporal.TemporalQueries;
  99 import java.time.temporal.TemporalQuery;
 100 import java.time.temporal.ValueRange;
 101 import java.time.temporal.WeekFields;
 102 import java.time.zone.ZoneRulesProvider;
 103 import java.util.AbstractMap.SimpleImmutableEntry;
 104 import java.util.ArrayList;
 105 import java.util.Arrays;
 106 import java.util.Collections;
 107 import java.util.Comparator;
 108 import java.util.HashMap;
 109 import java.util.HashSet;
 110 import java.util.Iterator;
 111 import java.util.LinkedHashMap;
 112 import java.util.List;
 113 import java.util.Locale;
 114 import java.util.Map;
 115 import java.util.Map.Entry;
 116 import java.util.Objects;
 117 import java.util.Set;
 118 import java.util.TimeZone;
 119 import java.util.concurrent.ConcurrentHashMap;
 120 import java.util.concurrent.ConcurrentMap;
 121 
 122 import sun.text.spi.JavaTimeDateTimePatternProvider;
 123 import sun.util.locale.provider.LocaleProviderAdapter;
 124 import sun.util.locale.provider.LocaleResources;
 125 import sun.util.locale.provider.TimeZoneNameUtility;
 126 
 127 /**
 128  * Builder to create date-time formatters.
 129  * <p>
 130  * This allows a {@code DateTimeFormatter} to be created.
 131  * All date-time formatters are created ultimately using this builder.
 132  * <p>
 133  * The basic elements of date-time can all be added:
 134  * <ul>
 135  * <li>Value - a numeric value</li>
 136  * <li>Fraction - a fractional value including the decimal place. Always use this when
 137  * outputting fractions to ensure that the fraction is parsed correctly</li>
 138  * <li>Text - the textual equivalent for the value</li>
 139  * <li>OffsetId/Offset - the {@linkplain ZoneOffset zone offset}</li>
 140  * <li>ZoneId - the {@linkplain ZoneId time-zone} id</li>
 141  * <li>ZoneText - the name of the time-zone</li>
 142  * <li>ChronologyId - the {@linkplain Chronology chronology} id</li>
 143  * <li>ChronologyText - the name of the chronology</li>
 144  * <li>Literal - a text literal</li>
 145  * <li>Nested and Optional - formats can be nested or made optional</li>
 146  * </ul>
 147  * In addition, any of the elements may be decorated by padding, either with spaces or any other character.
 148  * <p>
 149  * Finally, a shorthand pattern, mostly compatible with {@code java.text.SimpleDateFormat SimpleDateFormat}
 150  * can be used, see {@link #appendPattern(String)}.
 151  * In practice, this simply parses the pattern and calls other methods on the builder.
 152  *
 153  * @implSpec
 154  * This class is a mutable builder intended for use from a single thread.
 155  *
 156  * @since 1.8
 157  */
 158 public final class DateTimeFormatterBuilder {
 159 
 160     /**
 161      * Query for a time-zone that is region-only.
 162      */
 163     private static final TemporalQuery<ZoneId> QUERY_REGION_ONLY = (temporal) -> {
 164         ZoneId zone = temporal.query(TemporalQueries.zoneId());
 165         return (zone != null && zone instanceof ZoneOffset == false ? zone : null);
 166     };
 167 
 168     /**
 169      * The currently active builder, used by the outermost builder.
 170      */
 171     private DateTimeFormatterBuilder active = this;
 172     /**
 173      * The parent builder, null for the outermost builder.
 174      */
 175     private final DateTimeFormatterBuilder parent;
 176     /**
 177      * The list of printers that will be used.
 178      */
 179     private final List<DateTimePrinterParser> printerParsers = new ArrayList<>();
 180     /**
 181      * Whether this builder produces an optional formatter.
 182      */
 183     private final boolean optional;
 184     /**
 185      * The width to pad the next field to.
 186      */
 187     private int padNextWidth;
 188     /**
 189      * The character to pad the next field with.
 190      */
 191     private char padNextChar;
 192     /**
 193      * The index of the last variable width value parser.
 194      */
 195     private int valueParserIndex = -1;
 196 
 197     /**
 198      * Gets the formatting pattern for date and time styles for a locale and chronology.
 199      * The locale and chronology are used to lookup the locale specific format
 200      * for the requested dateStyle and/or timeStyle.
 201      *
 202      * @param dateStyle  the FormatStyle for the date, null for time-only pattern
 203      * @param timeStyle  the FormatStyle for the time, null for date-only pattern
 204      * @param chrono  the Chronology, non-null
 205      * @param locale  the locale, non-null
 206      * @return the locale and Chronology specific formatting pattern
 207      * @throws IllegalArgumentException if both dateStyle and timeStyle are null
 208      */
 209     public static String getLocalizedDateTimePattern(FormatStyle dateStyle, FormatStyle timeStyle,
 210             Chronology chrono, Locale locale) {
 211         Objects.requireNonNull(locale, "locale");
 212         Objects.requireNonNull(chrono, "chrono");
 213         if (dateStyle == null && timeStyle == null) {
 214             throw new IllegalArgumentException("Either dateStyle or timeStyle must be non-null");
 215         }
 216         LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(JavaTimeDateTimePatternProvider.class, locale);
 217         JavaTimeDateTimePatternProvider provider = adapter.getJavaTimeDateTimePatternProvider();
 218         String pattern = provider.getJavaTimeDateTimePattern(convertStyle(timeStyle),
 219                          convertStyle(dateStyle), chrono.getCalendarType(), locale);
 220         return pattern;
 221     }
 222 
 223     /**
 224      * Converts the given FormatStyle to the java.text.DateFormat style.
 225      *
 226      * @param style  the FormatStyle style
 227      * @return the int style, or -1 if style is null, indicating un-required
 228      */
 229     private static int convertStyle(FormatStyle style) {
 230         if (style == null) {
 231             return -1;
 232         }
 233         return style.ordinal();  // indices happen to align
 234     }
 235 
 236     /**
 237      * Constructs a new instance of the builder.
 238      */
 239     public DateTimeFormatterBuilder() {
 240         super();
 241         parent = null;
 242         optional = false;
 243     }
 244 
 245     /**
 246      * Constructs a new instance of the builder.
 247      *
 248      * @param parent  the parent builder, not null
 249      * @param optional  whether the formatter is optional, not null
 250      */
 251     private DateTimeFormatterBuilder(DateTimeFormatterBuilder parent, boolean optional) {
 252         super();
 253         this.parent = parent;
 254         this.optional = optional;
 255     }
 256 
 257     //-----------------------------------------------------------------------
 258     /**
 259      * Changes the parse style to be case sensitive for the remainder of the formatter.
 260      * <p>
 261      * Parsing can be case sensitive or insensitive - by default it is case sensitive.
 262      * This method allows the case sensitivity setting of parsing to be changed.
 263      * <p>
 264      * Calling this method changes the state of the builder such that all
 265      * subsequent builder method calls will parse text in case sensitive mode.
 266      * See {@link #parseCaseInsensitive} for the opposite setting.
 267      * The parse case sensitive/insensitive methods may be called at any point
 268      * in the builder, thus the parser can swap between case parsing modes
 269      * multiple times during the parse.
 270      * <p>
 271      * Since the default is case sensitive, this method should only be used after
 272      * a previous call to {@code #parseCaseInsensitive}.
 273      *
 274      * @return this, for chaining, not null
 275      */
 276     public DateTimeFormatterBuilder parseCaseSensitive() {
 277         appendInternal(SettingsParser.SENSITIVE);
 278         return this;
 279     }
 280 
 281     /**
 282      * Changes the parse style to be case insensitive for the remainder of the formatter.
 283      * <p>
 284      * Parsing can be case sensitive or insensitive - by default it is case sensitive.
 285      * This method allows the case sensitivity setting of parsing to be changed.
 286      * <p>
 287      * Calling this method changes the state of the builder such that all
 288      * subsequent builder method calls will parse text in case insensitive mode.
 289      * See {@link #parseCaseSensitive()} for the opposite setting.
 290      * The parse case sensitive/insensitive methods may be called at any point
 291      * in the builder, thus the parser can swap between case parsing modes
 292      * multiple times during the parse.
 293      *
 294      * @return this, for chaining, not null
 295      */
 296     public DateTimeFormatterBuilder parseCaseInsensitive() {
 297         appendInternal(SettingsParser.INSENSITIVE);
 298         return this;
 299     }
 300 
 301     //-----------------------------------------------------------------------
 302     /**
 303      * Changes the parse style to be strict for the remainder of the formatter.
 304      * <p>
 305      * Parsing can be strict or lenient - by default its strict.
 306      * This controls the degree of flexibility in matching the text and sign styles.
 307      * <p>
 308      * When used, this method changes the parsing to be strict from this point onwards.
 309      * As strict is the default, this is normally only needed after calling {@link #parseLenient()}.
 310      * The change will remain in force until the end of the formatter that is eventually
 311      * constructed or until {@code parseLenient} is called.
 312      *
 313      * @return this, for chaining, not null
 314      */
 315     public DateTimeFormatterBuilder parseStrict() {
 316         appendInternal(SettingsParser.STRICT);
 317         return this;
 318     }
 319 
 320     /**
 321      * Changes the parse style to be lenient for the remainder of the formatter.
 322      * Note that case sensitivity is set separately to this method.
 323      * <p>
 324      * Parsing can be strict or lenient - by default its strict.
 325      * This controls the degree of flexibility in matching the text and sign styles.
 326      * Applications calling this method should typically also call {@link #parseCaseInsensitive()}.
 327      * <p>
 328      * When used, this method changes the parsing to be lenient from this point onwards.
 329      * The change will remain in force until the end of the formatter that is eventually
 330      * constructed or until {@code parseStrict} is called.
 331      *
 332      * @return this, for chaining, not null
 333      */
 334     public DateTimeFormatterBuilder parseLenient() {
 335         appendInternal(SettingsParser.LENIENT);
 336         return this;
 337     }
 338 
 339     //-----------------------------------------------------------------------
 340     /**
 341      * Appends a default value for a field to the formatter for use in parsing.
 342      * <p>
 343      * This appends an instruction to the builder to inject a default value
 344      * into the parsed result. This is especially useful in conjunction with
 345      * optional parts of the formatter.
 346      * <p>
 347      * For example, consider a formatter that parses the year, followed by
 348      * an optional month, with a further optional day-of-month. Using such a
 349      * formatter would require the calling code to check whether a full date,
 350      * year-month or just a year had been parsed. This method can be used to
 351      * default the month and day-of-month to a sensible value, such as the
 352      * first of the month, allowing the calling code to always get a date.
 353      * <p>
 354      * During formatting, this method has no effect.
 355      * <p>
 356      * During parsing, the current state of the parse is inspected.
 357      * If the specified field has no associated value, because it has not been
 358      * parsed successfully at that point, then the specified value is injected
 359      * into the parse result. Injection is immediate, thus the field-value pair
 360      * will be visible to any subsequent elements in the formatter.
 361      * As such, this method is normally called at the end of the builder.
 362      *
 363      * @param field  the field to default the value of, not null
 364      * @param value  the value to default the field to
 365      * @return this, for chaining, not null
 366      */
 367     public DateTimeFormatterBuilder parseDefaulting(TemporalField field, long value) {
 368         Objects.requireNonNull(field, "field");
 369         appendInternal(new DefaultValueParser(field, value));
 370         return this;
 371     }
 372 
 373     //-----------------------------------------------------------------------
 374     /**
 375      * Appends the value of a date-time field to the formatter using a normal
 376      * output style.
 377      * <p>
 378      * The value of the field will be output during a format.
 379      * If the value cannot be obtained then an exception will be thrown.
 380      * <p>
 381      * The value will be printed as per the normal format of an integer value.
 382      * Only negative numbers will be signed. No padding will be added.
 383      * <p>
 384      * The parser for a variable width value such as this normally behaves greedily,
 385      * requiring one digit, but accepting as many digits as possible.
 386      * This behavior can be affected by 'adjacent value parsing'.
 387      * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details.
 388      *
 389      * @param field  the field to append, not null
 390      * @return this, for chaining, not null
 391      */
 392     public DateTimeFormatterBuilder appendValue(TemporalField field) {
 393         Objects.requireNonNull(field, "field");
 394         appendValue(new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL));
 395         return this;
 396     }
 397 
 398     /**
 399      * Appends the value of a date-time field to the formatter using a fixed
 400      * width, zero-padded approach.
 401      * <p>
 402      * The value of the field will be output during a format.
 403      * If the value cannot be obtained then an exception will be thrown.
 404      * <p>
 405      * The value will be zero-padded on the left. If the size of the value
 406      * means that it cannot be printed within the width then an exception is thrown.
 407      * If the value of the field is negative then an exception is thrown during formatting.
 408      * <p>
 409      * This method supports a special technique of parsing known as 'adjacent value parsing'.
 410      * This technique solves the problem where a value, variable or fixed width, is followed by one or more
 411      * fixed length values. The standard parser is greedy, and thus it would normally
 412      * steal the digits that are needed by the fixed width value parsers that follow the
 413      * variable width one.
 414      * <p>
 415      * No action is required to initiate 'adjacent value parsing'.
 416      * When a call to {@code appendValue} is made, the builder
 417      * enters adjacent value parsing setup mode. If the immediately subsequent method
 418      * call or calls on the same builder are for a fixed width value, then the parser will reserve
 419      * space so that the fixed width values can be parsed.
 420      * <p>
 421      * For example, consider {@code builder.appendValue(YEAR).appendValue(MONTH_OF_YEAR, 2);}
 422      * The year is a variable width parse of between 1 and 19 digits.
 423      * The month is a fixed width parse of 2 digits.
 424      * Because these were appended to the same builder immediately after one another,
 425      * the year parser will reserve two digits for the month to parse.
 426      * Thus, the text '201106' will correctly parse to a year of 2011 and a month of 6.
 427      * Without adjacent value parsing, the year would greedily parse all six digits and leave
 428      * nothing for the month.
 429      * <p>
 430      * Adjacent value parsing applies to each set of fixed width not-negative values in the parser
 431      * that immediately follow any kind of value, variable or fixed width.
 432      * Calling any other append method will end the setup of adjacent value parsing.
 433      * Thus, in the unlikely event that you need to avoid adjacent value parsing behavior,
 434      * simply add the {@code appendValue} to another {@code DateTimeFormatterBuilder}
 435      * and add that to this builder.
 436      * <p>
 437      * If adjacent parsing is active, then parsing must match exactly the specified
 438      * number of digits in both strict and lenient modes.
 439      * In addition, no positive or negative sign is permitted.
 440      *
 441      * @param field  the field to append, not null
 442      * @param width  the width of the printed field, from 1 to 19
 443      * @return this, for chaining, not null
 444      * @throws IllegalArgumentException if the width is invalid
 445      */
 446     public DateTimeFormatterBuilder appendValue(TemporalField field, int width) {
 447         Objects.requireNonNull(field, "field");
 448         if (width < 1 || width > 19) {
 449             throw new IllegalArgumentException("The width must be from 1 to 19 inclusive but was " + width);
 450         }
 451         NumberPrinterParser pp = new NumberPrinterParser(field, width, width, SignStyle.NOT_NEGATIVE);
 452         appendValue(pp);
 453         return this;
 454     }
 455 
 456     /**
 457      * Appends the value of a date-time field to the formatter providing full
 458      * control over formatting.
 459      * <p>
 460      * The value of the field will be output during a format.
 461      * If the value cannot be obtained then an exception will be thrown.
 462      * <p>
 463      * This method provides full control of the numeric formatting, including
 464      * zero-padding and the positive/negative sign.
 465      * <p>
 466      * The parser for a variable width value such as this normally behaves greedily,
 467      * accepting as many digits as possible.
 468      * This behavior can be affected by 'adjacent value parsing'.
 469      * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details.
 470      * <p>
 471      * In strict parsing mode, the minimum number of parsed digits is {@code minWidth}
 472      * and the maximum is {@code maxWidth}.
 473      * In lenient parsing mode, the minimum number of parsed digits is one
 474      * and the maximum is 19 (except as limited by adjacent value parsing).
 475      * <p>
 476      * If this method is invoked with equal minimum and maximum widths and a sign style of
 477      * {@code NOT_NEGATIVE} then it delegates to {@code appendValue(TemporalField,int)}.
 478      * In this scenario, the formatting and parsing behavior described there occur.
 479      *
 480      * @param field  the field to append, not null
 481      * @param minWidth  the minimum field width of the printed field, from 1 to 19
 482      * @param maxWidth  the maximum field width of the printed field, from 1 to 19
 483      * @param signStyle  the positive/negative output style, not null
 484      * @return this, for chaining, not null
 485      * @throws IllegalArgumentException if the widths are invalid
 486      */
 487     public DateTimeFormatterBuilder appendValue(
 488             TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) {
 489         if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) {
 490             return appendValue(field, maxWidth);
 491         }
 492         Objects.requireNonNull(field, "field");
 493         Objects.requireNonNull(signStyle, "signStyle");
 494         if (minWidth < 1 || minWidth > 19) {
 495             throw new IllegalArgumentException("The minimum width must be from 1 to 19 inclusive but was " + minWidth);
 496         }
 497         if (maxWidth < 1 || maxWidth > 19) {
 498             throw new IllegalArgumentException("The maximum width must be from 1 to 19 inclusive but was " + maxWidth);
 499         }
 500         if (maxWidth < minWidth) {
 501             throw new IllegalArgumentException("The maximum width must exceed or equal the minimum width but " +
 502                     maxWidth + " < " + minWidth);
 503         }
 504         NumberPrinterParser pp = new NumberPrinterParser(field, minWidth, maxWidth, signStyle);
 505         appendValue(pp);
 506         return this;
 507     }
 508 
 509     //-----------------------------------------------------------------------
 510     /**
 511      * Appends the reduced value of a date-time field to the formatter.
 512      * <p>
 513      * Since fields such as year vary by chronology, it is recommended to use the
 514      * {@link #appendValueReduced(TemporalField, int, int, ChronoLocalDate)} date}
 515      * variant of this method in most cases. This variant is suitable for
 516      * simple fields or working with only the ISO chronology.
 517      * <p>
 518      * For formatting, the {@code width} and {@code maxWidth} are used to
 519      * determine the number of characters to format.
 520      * If they are equal then the format is fixed width.
 521      * If the value of the field is within the range of the {@code baseValue} using
 522      * {@code width} characters then the reduced value is formatted otherwise the value is
 523      * truncated to fit {@code maxWidth}.
 524      * The rightmost characters are output to match the width, left padding with zero.
 525      * <p>
 526      * For strict parsing, the number of characters allowed by {@code width} to {@code maxWidth} are parsed.
 527      * For lenient parsing, the number of characters must be at least 1 and less than 10.
 528      * If the number of digits parsed is equal to {@code width} and the value is positive,
 529      * the value of the field is computed to be the first number greater than
 530      * or equal to the {@code baseValue} with the same least significant characters,
 531      * otherwise the value parsed is the field value.
 532      * This allows a reduced value to be entered for values in range of the baseValue
 533      * and width and absolute values can be entered for values outside the range.
 534      * <p>
 535      * For example, a base value of {@code 1980} and a width of {@code 2} will have
 536      * valid values from {@code 1980} to {@code 2079}.
 537      * During parsing, the text {@code "12"} will result in the value {@code 2012} as that
 538      * is the value within the range where the last two characters are "12".
 539      * By contrast, parsing the text {@code "1915"} will result in the value {@code 1915}.
 540      *
 541      * @param field  the field to append, not null
 542      * @param width  the field width of the printed and parsed field, from 1 to 10
 543      * @param maxWidth  the maximum field width of the printed field, from 1 to 10
 544      * @param baseValue  the base value of the range of valid values
 545      * @return this, for chaining, not null
 546      * @throws IllegalArgumentException if the width or base value is invalid
 547      */
 548     public DateTimeFormatterBuilder appendValueReduced(TemporalField field,
 549             int width, int maxWidth, int baseValue) {
 550         Objects.requireNonNull(field, "field");
 551         ReducedPrinterParser pp = new ReducedPrinterParser(field, width, maxWidth, baseValue, null);
 552         appendValue(pp);
 553         return this;
 554     }
 555 
 556     /**
 557      * Appends the reduced value of a date-time field to the formatter.
 558      * <p>
 559      * This is typically used for formatting and parsing a two digit year.
 560      * <p>
 561      * The base date is used to calculate the full value during parsing.
 562      * For example, if the base date is 1950-01-01 then parsed values for
 563      * a two digit year parse will be in the range 1950-01-01 to 2049-12-31.
 564      * Only the year would be extracted from the date, thus a base date of
 565      * 1950-08-25 would also parse to the range 1950-01-01 to 2049-12-31.
 566      * This behavior is necessary to support fields such as week-based-year
 567      * or other calendar systems where the parsed value does not align with
 568      * standard ISO years.
 569      * <p>
 570      * The exact behavior is as follows. Parse the full set of fields and
 571      * determine the effective chronology using the last chronology if
 572      * it appears more than once. Then convert the base date to the
 573      * effective chronology. Then extract the specified field from the
 574      * chronology-specific base date and use it to determine the
 575      * {@code baseValue} used below.
 576      * <p>
 577      * For formatting, the {@code width} and {@code maxWidth} are used to
 578      * determine the number of characters to format.
 579      * If they are equal then the format is fixed width.
 580      * If the value of the field is within the range of the {@code baseValue} using
 581      * {@code width} characters then the reduced value is formatted otherwise the value is
 582      * truncated to fit {@code maxWidth}.
 583      * The rightmost characters are output to match the width, left padding with zero.
 584      * <p>
 585      * For strict parsing, the number of characters allowed by {@code width} to {@code maxWidth} are parsed.
 586      * For lenient parsing, the number of characters must be at least 1 and less than 10.
 587      * If the number of digits parsed is equal to {@code width} and the value is positive,
 588      * the value of the field is computed to be the first number greater than
 589      * or equal to the {@code baseValue} with the same least significant characters,
 590      * otherwise the value parsed is the field value.
 591      * This allows a reduced value to be entered for values in range of the baseValue
 592      * and width and absolute values can be entered for values outside the range.
 593      * <p>
 594      * For example, a base value of {@code 1980} and a width of {@code 2} will have
 595      * valid values from {@code 1980} to {@code 2079}.
 596      * During parsing, the text {@code "12"} will result in the value {@code 2012} as that
 597      * is the value within the range where the last two characters are "12".
 598      * By contrast, parsing the text {@code "1915"} will result in the value {@code 1915}.
 599      *
 600      * @param field  the field to append, not null
 601      * @param width  the field width of the printed and parsed field, from 1 to 10
 602      * @param maxWidth  the maximum field width of the printed field, from 1 to 10
 603      * @param baseDate  the base date used to calculate the base value for the range
 604      *  of valid values in the parsed chronology, not null
 605      * @return this, for chaining, not null
 606      * @throws IllegalArgumentException if the width or base value is invalid
 607      */
 608     public DateTimeFormatterBuilder appendValueReduced(
 609             TemporalField field, int width, int maxWidth, ChronoLocalDate baseDate) {
 610         Objects.requireNonNull(field, "field");
 611         Objects.requireNonNull(baseDate, "baseDate");
 612         ReducedPrinterParser pp = new ReducedPrinterParser(field, width, maxWidth, 0, baseDate);
 613         appendValue(pp);
 614         return this;
 615     }
 616 
 617     /**
 618      * Appends a fixed or variable width printer-parser handling adjacent value mode.
 619      * If a PrinterParser is not active then the new PrinterParser becomes
 620      * the active PrinterParser.
 621      * Otherwise, the active PrinterParser is modified depending on the new PrinterParser.
 622      * If the new PrinterParser is fixed width and has sign style {@code NOT_NEGATIVE}
 623      * then its width is added to the active PP and
 624      * the new PrinterParser is forced to be fixed width.
 625      * If the new PrinterParser is variable width, the active PrinterParser is changed
 626      * to be fixed width and the new PrinterParser becomes the active PP.
 627      *
 628      * @param pp  the printer-parser, not null
 629      * @return this, for chaining, not null
 630      */
 631     private DateTimeFormatterBuilder appendValue(NumberPrinterParser pp) {
 632         if (active.valueParserIndex >= 0) {
 633             final int activeValueParser = active.valueParserIndex;
 634 
 635             // adjacent parsing mode, update setting in previous parsers
 636             NumberPrinterParser basePP = (NumberPrinterParser) active.printerParsers.get(activeValueParser);
 637             if (pp.minWidth == pp.maxWidth && pp.signStyle == SignStyle.NOT_NEGATIVE) {
 638                 // Append the width to the subsequentWidth of the active parser
 639                 basePP = basePP.withSubsequentWidth(pp.maxWidth);
 640                 // Append the new parser as a fixed width
 641                 appendInternal(pp.withFixedWidth());
 642                 // Retain the previous active parser
 643                 active.valueParserIndex = activeValueParser;
 644             } else {
 645                 // Modify the active parser to be fixed width
 646                 basePP = basePP.withFixedWidth();
 647                 // The new parser becomes the mew active parser
 648                 active.valueParserIndex = appendInternal(pp);
 649             }
 650             // Replace the modified parser with the updated one
 651             active.printerParsers.set(activeValueParser, basePP);
 652         } else {
 653             // The new Parser becomes the active parser
 654             active.valueParserIndex = appendInternal(pp);
 655         }
 656         return this;
 657     }
 658 
 659     //-----------------------------------------------------------------------
 660     /**
 661      * Appends the fractional value of a date-time field to the formatter.
 662      * <p>
 663      * The fractional value of the field will be output including the
 664      * preceding decimal point. The preceding value is not output.
 665      * For example, the second-of-minute value of 15 would be output as {@code .25}.
 666      * <p>
 667      * The width of the printed fraction can be controlled. Setting the
 668      * minimum width to zero will cause no output to be generated.
 669      * The printed fraction will have the minimum width necessary between
 670      * the minimum and maximum widths - trailing zeroes are omitted.
 671      * No rounding occurs due to the maximum width - digits are simply dropped.
 672      * <p>
 673      * When parsing in strict mode, the number of parsed digits must be between
 674      * the minimum and maximum width. In strict mode, if the minimum and maximum widths
 675      * are equal and there is no decimal point then the parser will
 676      * participate in adjacent value parsing, see
 677      * {@link appendValue(java.time.temporal.TemporalField, int)}. When parsing in lenient mode,
 678      * the minimum width is considered to be zero and the maximum is nine.
 679      * <p>
 680      * If the value cannot be obtained then an exception will be thrown.
 681      * If the value is negative an exception will be thrown.
 682      * If the field does not have a fixed set of valid values then an
 683      * exception will be thrown.
 684      * If the field value in the date-time to be printed is invalid it
 685      * cannot be printed and an exception will be thrown.
 686      *
 687      * @param field  the field to append, not null
 688      * @param minWidth  the minimum width of the field excluding the decimal point, from 0 to 9
 689      * @param maxWidth  the maximum width of the field excluding the decimal point, from 1 to 9
 690      * @param decimalPoint  whether to output the localized decimal point symbol
 691      * @return this, for chaining, not null
 692      * @throws IllegalArgumentException if the field has a variable set of valid values or
 693      *  either width is invalid
 694      */
 695     public DateTimeFormatterBuilder appendFraction(
 696             TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) {
 697         if (minWidth == maxWidth && decimalPoint == false) {
 698             // adjacent parsing
 699             appendValue(new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint));
 700         } else {
 701             appendInternal(new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint));
 702         }
 703         return this;
 704     }
 705 
 706     //-----------------------------------------------------------------------
 707     /**
 708      * Appends the text of a date-time field to the formatter using the full
 709      * text style.
 710      * <p>
 711      * The text of the field will be output during a format.
 712      * The value must be within the valid range of the field.
 713      * If the value cannot be obtained then an exception will be thrown.
 714      * If the field has no textual representation, then the numeric value will be used.
 715      * <p>
 716      * The value will be printed as per the normal format of an integer value.
 717      * Only negative numbers will be signed. No padding will be added.
 718      *
 719      * @param field  the field to append, not null
 720      * @return this, for chaining, not null
 721      */
 722     public DateTimeFormatterBuilder appendText(TemporalField field) {
 723         return appendText(field, TextStyle.FULL);
 724     }
 725 
 726     /**
 727      * Appends the text of a date-time field to the formatter.
 728      * <p>
 729      * The text of the field will be output during a format.
 730      * The value must be within the valid range of the field.
 731      * If the value cannot be obtained then an exception will be thrown.
 732      * If the field has no textual representation, then the numeric value will be used.
 733      * <p>
 734      * The value will be printed as per the normal format of an integer value.
 735      * Only negative numbers will be signed. No padding will be added.
 736      *
 737      * @param field  the field to append, not null
 738      * @param textStyle  the text style to use, not null
 739      * @return this, for chaining, not null
 740      */
 741     public DateTimeFormatterBuilder appendText(TemporalField field, TextStyle textStyle) {
 742         Objects.requireNonNull(field, "field");
 743         Objects.requireNonNull(textStyle, "textStyle");
 744         appendInternal(new TextPrinterParser(field, textStyle, DateTimeTextProvider.getInstance()));
 745         return this;
 746     }
 747 
 748     /**
 749      * Appends the text of a date-time field to the formatter using the specified
 750      * map to supply the text.
 751      * <p>
 752      * The standard text outputting methods use the localized text in the JDK.
 753      * This method allows that text to be specified directly.
 754      * The supplied map is not validated by the builder to ensure that formatting or
 755      * parsing is possible, thus an invalid map may throw an error during later use.
 756      * <p>
 757      * Supplying the map of text provides considerable flexibility in formatting and parsing.
 758      * For example, a legacy application might require or supply the months of the
 759      * year as "JNY", "FBY", "MCH" etc. These do not match the standard set of text
 760      * for localized month names. Using this method, a map can be created which
 761      * defines the connection between each value and the text:
 762      * <pre>
 763      * Map&lt;Long, String&gt; map = new HashMap&lt;&gt;();
 764      * map.put(1L, "JNY");
 765      * map.put(2L, "FBY");
 766      * map.put(3L, "MCH");
 767      * ...
 768      * builder.appendText(MONTH_OF_YEAR, map);
 769      * </pre>
 770      * <p>
 771      * Other uses might be to output the value with a suffix, such as "1st", "2nd", "3rd",
 772      * or as Roman numerals "I", "II", "III", "IV".
 773      * <p>
 774      * During formatting, the value is obtained and checked that it is in the valid range.
 775      * If text is not available for the value then it is output as a number.
 776      * During parsing, the parser will match against the map of text and numeric values.
 777      *
 778      * @param field  the field to append, not null
 779      * @param textLookup  the map from the value to the text
 780      * @return this, for chaining, not null
 781      */
 782     public DateTimeFormatterBuilder appendText(TemporalField field, Map<Long, String> textLookup) {
 783         Objects.requireNonNull(field, "field");
 784         Objects.requireNonNull(textLookup, "textLookup");
 785         Map<Long, String> copy = new LinkedHashMap<>(textLookup);
 786         Map<TextStyle, Map<Long, String>> map = Collections.singletonMap(TextStyle.FULL, copy);
 787         final LocaleStore store = new LocaleStore(map);
 788         DateTimeTextProvider provider = new DateTimeTextProvider() {
 789             @Override
 790             public String getText(TemporalField field, long value, TextStyle style, Locale locale) {
 791                 return store.getText(value, style);
 792             }
 793             @Override
 794             public Iterator<Entry<String, Long>> getTextIterator(TemporalField field, TextStyle style, Locale locale) {
 795                 return store.getTextIterator(style);
 796             }
 797         };
 798         appendInternal(new TextPrinterParser(field, TextStyle.FULL, provider));
 799         return this;
 800     }
 801 
 802     //-----------------------------------------------------------------------
 803     /**
 804      * Appends an instant using ISO-8601 to the formatter, formatting fractional
 805      * digits in groups of three.
 806      * <p>
 807      * Instants have a fixed output format.
 808      * They are converted to a date-time with a zone-offset of UTC and formatted
 809      * using the standard ISO-8601 format.
 810      * With this method, formatting nano-of-second outputs zero, three, six
 811      * or nine digits as necessary.
 812      * The localized decimal style is not used.
 813      * <p>
 814      * The instant is obtained using {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
 815      * and optionally {@code NANO_OF_SECOND}. The value of {@code INSTANT_SECONDS}
 816      * may be outside the maximum range of {@code LocalDateTime}.
 817      * <p>
 818      * The {@linkplain ResolverStyle resolver style} has no effect on instant parsing.
 819      * The end-of-day time of '24:00' is handled as midnight at the start of the following day.
 820      * The leap-second time of '23:59:59' is handled to some degree, see
 821      * {@link DateTimeFormatter#parsedLeapSecond()} for full details.
 822      * <p>
 823      * An alternative to this method is to format/parse the instant as a single
 824      * epoch-seconds value. That is achieved using {@code appendValue(INSTANT_SECONDS)}.
 825      *
 826      * @return this, for chaining, not null
 827      */
 828     public DateTimeFormatterBuilder appendInstant() {
 829         appendInternal(new InstantPrinterParser(-2));
 830         return this;
 831     }
 832 
 833     /**
 834      * Appends an instant using ISO-8601 to the formatter with control over
 835      * the number of fractional digits.
 836      * <p>
 837      * Instants have a fixed output format, although this method provides some
 838      * control over the fractional digits. They are converted to a date-time
 839      * with a zone-offset of UTC and printed using the standard ISO-8601 format.
 840      * The localized decimal style is not used.
 841      * <p>
 842      * The {@code fractionalDigits} parameter allows the output of the fractional
 843      * second to be controlled. Specifying zero will cause no fractional digits
 844      * to be output. From 1 to 9 will output an increasing number of digits, using
 845      * zero right-padding if necessary. The special value -1 is used to output as
 846      * many digits as necessary to avoid any trailing zeroes.
 847      * <p>
 848      * When parsing in strict mode, the number of parsed digits must match the
 849      * fractional digits. When parsing in lenient mode, any number of fractional
 850      * digits from zero to nine are accepted.
 851      * <p>
 852      * The instant is obtained using {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
 853      * and optionally {@code NANO_OF_SECOND}. The value of {@code INSTANT_SECONDS}
 854      * may be outside the maximum range of {@code LocalDateTime}.
 855      * <p>
 856      * The {@linkplain ResolverStyle resolver style} has no effect on instant parsing.
 857      * The end-of-day time of '24:00' is handled as midnight at the start of the following day.
 858      * The leap-second time of '23:59:60' is handled to some degree, see
 859      * {@link DateTimeFormatter#parsedLeapSecond()} for full details.
 860      * <p>
 861      * An alternative to this method is to format/parse the instant as a single
 862      * epoch-seconds value. That is achieved using {@code appendValue(INSTANT_SECONDS)}.
 863      *
 864      * @param fractionalDigits  the number of fractional second digits to format with,
 865      *  from 0 to 9, or -1 to use as many digits as necessary
 866      * @return this, for chaining, not null
 867      * @throws IllegalArgumentException if the number of fractional digits is invalid
 868      */
 869     public DateTimeFormatterBuilder appendInstant(int fractionalDigits) {
 870         if (fractionalDigits < -1 || fractionalDigits > 9) {
 871             throw new IllegalArgumentException("The fractional digits must be from -1 to 9 inclusive but was " + fractionalDigits);
 872         }
 873         appendInternal(new InstantPrinterParser(fractionalDigits));
 874         return this;
 875     }
 876 
 877     //-----------------------------------------------------------------------
 878     /**
 879      * Appends the zone offset, such as '+01:00', to the formatter.
 880      * <p>
 881      * This appends an instruction to format/parse the offset ID to the builder.
 882      * This is equivalent to calling {@code appendOffset("+HH:mm:ss", "Z")}.
 883      * See {@link #appendOffset(String, String)} for details on formatting
 884      * and parsing.
 885      *
 886      * @return this, for chaining, not null
 887      */
 888     public DateTimeFormatterBuilder appendOffsetId() {
 889         appendInternal(OffsetIdPrinterParser.INSTANCE_ID_Z);
 890         return this;
 891     }
 892 
 893     /**
 894      * Appends the zone offset, such as '+01:00', to the formatter.
 895      * <p>
 896      * This appends an instruction to format/parse the offset ID to the builder.
 897      * <p>
 898      * During formatting, the offset is obtained using a mechanism equivalent
 899      * to querying the temporal with {@link TemporalQueries#offset()}.
 900      * It will be printed using the format defined below.
 901      * If the offset cannot be obtained then an exception is thrown unless the
 902      * section of the formatter is optional.
 903      * <p>
 904      * When parsing in strict mode, the input must contain the mandatory
 905      * and optional elements are defined by the specified pattern.
 906      * If the offset cannot be parsed then an exception is thrown unless
 907      * the section of the formatter is optional.
 908      * <p>
 909      * When parsing in lenient mode, only the hours are mandatory - minutes
 910      * and seconds are optional. The colons are required if the specified
 911      * pattern contains a colon. If the specified pattern is "+HH", the
 912      * presence of colons is determined by whether the character after the
 913      * hour digits is a colon or not.
 914      * If the offset cannot be parsed then an exception is thrown unless
 915      * the section of the formatter is optional.
 916      * <p>
 917      * The format of the offset is controlled by a pattern which must be one
 918      * of the following:
 919      * <ul>
 920      * <li>{@code +HH} - hour only, ignoring minute and second
 921      * <li>{@code +HHmm} - hour, with minute if non-zero, ignoring second, no colon
 922      * <li>{@code +HH:mm} - hour, with minute if non-zero, ignoring second, with colon
 923      * <li>{@code +HHMM} - hour and minute, ignoring second, no colon
 924      * <li>{@code +HH:MM} - hour and minute, ignoring second, with colon
 925      * <li>{@code +HHMMss} - hour and minute, with second if non-zero, no colon
 926      * <li>{@code +HH:MM:ss} - hour and minute, with second if non-zero, with colon
 927      * <li>{@code +HHMMSS} - hour, minute and second, no colon
 928      * <li>{@code +HH:MM:SS} - hour, minute and second, with colon
 929      * <li>{@code +HHmmss} - hour, with minute if non-zero or with minute and
 930      * second if non-zero, no colon
 931      * <li>{@code +HH:mm:ss} - hour, with minute if non-zero or with minute and
 932      * second if non-zero, with colon
 933      * <li>{@code +H} - hour only, ignoring minute and second
 934      * <li>{@code +Hmm} - hour, with minute if non-zero, ignoring second, no colon
 935      * <li>{@code +H:mm} - hour, with minute if non-zero, ignoring second, with colon
 936      * <li>{@code +HMM} - hour and minute, ignoring second, no colon
 937      * <li>{@code +H:MM} - hour and minute, ignoring second, with colon
 938      * <li>{@code +HMMss} - hour and minute, with second if non-zero, no colon
 939      * <li>{@code +H:MM:ss} - hour and minute, with second if non-zero, with colon
 940      * <li>{@code +HMMSS} - hour, minute and second, no colon
 941      * <li>{@code +H:MM:SS} - hour, minute and second, with colon
 942      * <li>{@code +Hmmss} - hour, with minute if non-zero or with minute and
 943      * second if non-zero, no colon
 944      * <li>{@code +H:mm:ss} - hour, with minute if non-zero or with minute and
 945      * second if non-zero, with colon
 946      * </ul>
 947      * Patterns containing "HH" will format and parse a two digit hour,
 948      * zero-padded if necessary. Patterns containing "H" will format with no
 949      * zero-padding, and parse either one or two digits.
 950      * In lenient mode, the parser will be greedy and parse the maximum digits possible.
 951      * The "no offset" text controls what text is printed when the total amount of
 952      * the offset fields to be output is zero.
 953      * Example values would be 'Z', '+00:00', 'UTC' or 'GMT'.
 954      * Three formats are accepted for parsing UTC - the "no offset" text, and the
 955      * plus and minus versions of zero defined by the pattern.
 956      *
 957      * @param pattern  the pattern to use, not null
 958      * @param noOffsetText  the text to use when the offset is zero, not null
 959      * @return this, for chaining, not null
 960      * @throws IllegalArgumentException if the pattern is invalid
 961      */
 962     public DateTimeFormatterBuilder appendOffset(String pattern, String noOffsetText) {
 963         appendInternal(new OffsetIdPrinterParser(pattern, noOffsetText));
 964         return this;
 965     }
 966 
 967     /**
 968      * Appends the localized zone offset, such as 'GMT+01:00', to the formatter.
 969      * <p>
 970      * This appends a localized zone offset to the builder, the format of the
 971      * localized offset is controlled by the specified {@link FormatStyle style}
 972      * to this method:
 973      * <ul>
 974      * <li>{@link TextStyle#FULL full} - formats with localized offset text, such
 975      * as 'GMT, 2-digit hour and minute field, optional second field if non-zero,
 976      * and colon.
 977      * <li>{@link TextStyle#SHORT short} - formats with localized offset text,
 978      * such as 'GMT, hour without leading zero, optional 2-digit minute and
 979      * second if non-zero, and colon.
 980      * </ul>
 981      * <p>
 982      * During formatting, the offset is obtained using a mechanism equivalent
 983      * to querying the temporal with {@link TemporalQueries#offset()}.
 984      * If the offset cannot be obtained then an exception is thrown unless the
 985      * section of the formatter is optional.
 986      * <p>
 987      * During parsing, the offset is parsed using the format defined above.
 988      * If the offset cannot be parsed then an exception is thrown unless the
 989      * section of the formatter is optional.
 990      *
 991      * @param style  the format style to use, not null
 992      * @return this, for chaining, not null
 993      * @throws IllegalArgumentException if style is neither {@link TextStyle#FULL
 994      * full} nor {@link TextStyle#SHORT short}
 995      */
 996     public DateTimeFormatterBuilder appendLocalizedOffset(TextStyle style) {
 997         Objects.requireNonNull(style, "style");
 998         if (style != TextStyle.FULL && style != TextStyle.SHORT) {
 999             throw new IllegalArgumentException("Style must be either full or short");
1000         }
1001         appendInternal(new LocalizedOffsetIdPrinterParser(style));
1002         return this;
1003     }
1004 
1005     //-----------------------------------------------------------------------
1006     /**
1007      * Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to the formatter.
1008      * <p>
1009      * This appends an instruction to format/parse the zone ID to the builder.
1010      * The zone ID is obtained in a strict manner suitable for {@code ZonedDateTime}.
1011      * By contrast, {@code OffsetDateTime} does not have a zone ID suitable
1012      * for use with this method, see {@link #appendZoneOrOffsetId()}.
1013      * <p>
1014      * During formatting, the zone is obtained using a mechanism equivalent
1015      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1016      * It will be printed using the result of {@link ZoneId#getId()}.
1017      * If the zone cannot be obtained then an exception is thrown unless the
1018      * section of the formatter is optional.
1019      * <p>
1020      * During parsing, the text must match a known zone or offset.
1021      * There are two types of zone ID, offset-based, such as '+01:30' and
1022      * region-based, such as 'Europe/London'. These are parsed differently.
1023      * If the parse starts with '+', '-', 'UT', 'UTC' or 'GMT', then the parser
1024      * expects an offset-based zone and will not match region-based zones.
1025      * The offset ID, such as '+02:30', may be at the start of the parse,
1026      * or prefixed by  'UT', 'UTC' or 'GMT'. The offset ID parsing is
1027      * equivalent to using {@link #appendOffset(String, String)} using the
1028      * arguments 'HH:MM:ss' and the no offset string '0'.
1029      * If the parse starts with 'UT', 'UTC' or 'GMT', and the parser cannot
1030      * match a following offset ID, then {@link ZoneOffset#UTC} is selected.
1031      * In all other cases, the list of known region-based zones is used to
1032      * find the longest available match. If no match is found, and the parse
1033      * starts with 'Z', then {@code ZoneOffset.UTC} is selected.
1034      * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
1035      * <p>
1036      * For example, the following will parse:
1037      * <pre>
1038      *   "Europe/London"           -- ZoneId.of("Europe/London")
1039      *   "Z"                       -- ZoneOffset.UTC
1040      *   "UT"                      -- ZoneId.of("UT")
1041      *   "UTC"                     -- ZoneId.of("UTC")
1042      *   "GMT"                     -- ZoneId.of("GMT")
1043      *   "+01:30"                  -- ZoneOffset.of("+01:30")
1044      *   "UT+01:30"                -- ZoneOffset.of("+01:30")
1045      *   "UTC+01:30"               -- ZoneOffset.of("+01:30")
1046      *   "GMT+01:30"               -- ZoneOffset.of("+01:30")
1047      * </pre>
1048      *
1049      * @return this, for chaining, not null
1050      * @see #appendZoneRegionId()
1051      */
1052     public DateTimeFormatterBuilder appendZoneId() {
1053         appendInternal(new ZoneIdPrinterParser(TemporalQueries.zoneId(), "ZoneId()"));
1054         return this;
1055     }
1056 
1057     /**
1058      * Appends the time-zone region ID, such as 'Europe/Paris', to the formatter,
1059      * rejecting the zone ID if it is a {@code ZoneOffset}.
1060      * <p>
1061      * This appends an instruction to format/parse the zone ID to the builder
1062      * only if it is a region-based ID.
1063      * <p>
1064      * During formatting, the zone is obtained using a mechanism equivalent
1065      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1066      * If the zone is a {@code ZoneOffset} or it cannot be obtained then
1067      * an exception is thrown unless the section of the formatter is optional.
1068      * If the zone is not an offset, then the zone will be printed using
1069      * the zone ID from {@link ZoneId#getId()}.
1070      * <p>
1071      * During parsing, the text must match a known zone or offset.
1072      * There are two types of zone ID, offset-based, such as '+01:30' and
1073      * region-based, such as 'Europe/London'. These are parsed differently.
1074      * If the parse starts with '+', '-', 'UT', 'UTC' or 'GMT', then the parser
1075      * expects an offset-based zone and will not match region-based zones.
1076      * The offset ID, such as '+02:30', may be at the start of the parse,
1077      * or prefixed by  'UT', 'UTC' or 'GMT'. The offset ID parsing is
1078      * equivalent to using {@link #appendOffset(String, String)} using the
1079      * arguments 'HH:MM:ss' and the no offset string '0'.
1080      * If the parse starts with 'UT', 'UTC' or 'GMT', and the parser cannot
1081      * match a following offset ID, then {@link ZoneOffset#UTC} is selected.
1082      * In all other cases, the list of known region-based zones is used to
1083      * find the longest available match. If no match is found, and the parse
1084      * starts with 'Z', then {@code ZoneOffset.UTC} is selected.
1085      * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
1086      * <p>
1087      * For example, the following will parse:
1088      * <pre>
1089      *   "Europe/London"           -- ZoneId.of("Europe/London")
1090      *   "Z"                       -- ZoneOffset.UTC
1091      *   "UT"                      -- ZoneId.of("UT")
1092      *   "UTC"                     -- ZoneId.of("UTC")
1093      *   "GMT"                     -- ZoneId.of("GMT")
1094      *   "+01:30"                  -- ZoneOffset.of("+01:30")
1095      *   "UT+01:30"                -- ZoneOffset.of("+01:30")
1096      *   "UTC+01:30"               -- ZoneOffset.of("+01:30")
1097      *   "GMT+01:30"               -- ZoneOffset.of("+01:30")
1098      * </pre>
1099      * <p>
1100      * Note that this method is identical to {@code appendZoneId()} except
1101      * in the mechanism used to obtain the zone.
1102      * Note also that parsing accepts offsets, whereas formatting will never
1103      * produce one.
1104      *
1105      * @return this, for chaining, not null
1106      * @see #appendZoneId()
1107      */
1108     public DateTimeFormatterBuilder appendZoneRegionId() {
1109         appendInternal(new ZoneIdPrinterParser(QUERY_REGION_ONLY, "ZoneRegionId()"));
1110         return this;
1111     }
1112 
1113     /**
1114      * Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to
1115      * the formatter, using the best available zone ID.
1116      * <p>
1117      * This appends an instruction to format/parse the best available
1118      * zone or offset ID to the builder.
1119      * The zone ID is obtained in a lenient manner that first attempts to
1120      * find a true zone ID, such as that on {@code ZonedDateTime}, and
1121      * then attempts to find an offset, such as that on {@code OffsetDateTime}.
1122      * <p>
1123      * During formatting, the zone is obtained using a mechanism equivalent
1124      * to querying the temporal with {@link TemporalQueries#zone()}.
1125      * It will be printed using the result of {@link ZoneId#getId()}.
1126      * If the zone cannot be obtained then an exception is thrown unless the
1127      * section of the formatter is optional.
1128      * <p>
1129      * During parsing, the text must match a known zone or offset.
1130      * There are two types of zone ID, offset-based, such as '+01:30' and
1131      * region-based, such as 'Europe/London'. These are parsed differently.
1132      * If the parse starts with '+', '-', 'UT', 'UTC' or 'GMT', then the parser
1133      * expects an offset-based zone and will not match region-based zones.
1134      * The offset ID, such as '+02:30', may be at the start of the parse,
1135      * or prefixed by  'UT', 'UTC' or 'GMT'. The offset ID parsing is
1136      * equivalent to using {@link #appendOffset(String, String)} using the
1137      * arguments 'HH:MM:ss' and the no offset string '0'.
1138      * If the parse starts with 'UT', 'UTC' or 'GMT', and the parser cannot
1139      * match a following offset ID, then {@link ZoneOffset#UTC} is selected.
1140      * In all other cases, the list of known region-based zones is used to
1141      * find the longest available match. If no match is found, and the parse
1142      * starts with 'Z', then {@code ZoneOffset.UTC} is selected.
1143      * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
1144      * <p>
1145      * For example, the following will parse:
1146      * <pre>
1147      *   "Europe/London"           -- ZoneId.of("Europe/London")
1148      *   "Z"                       -- ZoneOffset.UTC
1149      *   "UT"                      -- ZoneId.of("UT")
1150      *   "UTC"                     -- ZoneId.of("UTC")
1151      *   "GMT"                     -- ZoneId.of("GMT")
1152      *   "+01:30"                  -- ZoneOffset.of("+01:30")
1153      *   "UT+01:30"                -- ZoneOffset.of("UT+01:30")
1154      *   "UTC+01:30"               -- ZoneOffset.of("UTC+01:30")
1155      *   "GMT+01:30"               -- ZoneOffset.of("GMT+01:30")
1156      * </pre>
1157      * <p>
1158      * Note that this method is identical to {@code appendZoneId()} except
1159      * in the mechanism used to obtain the zone.
1160      *
1161      * @return this, for chaining, not null
1162      * @see #appendZoneId()
1163      */
1164     public DateTimeFormatterBuilder appendZoneOrOffsetId() {
1165         appendInternal(new ZoneIdPrinterParser(TemporalQueries.zone(), "ZoneOrOffsetId()"));
1166         return this;
1167     }
1168 
1169     /**
1170      * Appends the time-zone name, such as 'British Summer Time', to the formatter.
1171      * <p>
1172      * This appends an instruction to format/parse the textual name of the zone to
1173      * the builder.
1174      * <p>
1175      * During formatting, the zone is obtained using a mechanism equivalent
1176      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1177      * If the zone is a {@code ZoneOffset} it will be printed using the
1178      * result of {@link ZoneOffset#getId()}.
1179      * If the zone is not an offset, the textual name will be looked up
1180      * for the locale set in the {@link DateTimeFormatter}.
1181      * If the temporal object being printed represents an instant, or if it is a
1182      * local date-time that is not in a daylight saving gap or overlap then
1183      * the text will be the summer or winter time text as appropriate.
1184      * If the lookup for text does not find any suitable result, then the
1185      * {@link ZoneId#getId() ID} will be printed.
1186      * If the zone cannot be obtained then an exception is thrown unless the
1187      * section of the formatter is optional.
1188      * <p>
1189      * During parsing, either the textual zone name, the zone ID or the offset
1190      * is accepted. Many textual zone names are not unique, such as CST can be
1191      * for both "Central Standard Time" and "China Standard Time". In this
1192      * situation, the zone id will be determined by the region information from
1193      * formatter's  {@link DateTimeFormatter#getLocale() locale} and the standard
1194      * zone id for that area, for example, America/New_York for the America Eastern
1195      * zone. The {@link #appendZoneText(TextStyle, Set)} may be used
1196      * to specify a set of preferred {@link ZoneId} in this situation.
1197      *
1198      * @param textStyle  the text style to use, not null
1199      * @return this, for chaining, not null
1200      */
1201     public DateTimeFormatterBuilder appendZoneText(TextStyle textStyle) {
1202         appendInternal(new ZoneTextPrinterParser(textStyle, null, false));
1203         return this;
1204     }
1205 
1206     /**
1207      * Appends the time-zone name, such as 'British Summer Time', to the formatter.
1208      * <p>
1209      * This appends an instruction to format/parse the textual name of the zone to
1210      * the builder.
1211      * <p>
1212      * During formatting, the zone is obtained using a mechanism equivalent
1213      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1214      * If the zone is a {@code ZoneOffset} it will be printed using the
1215      * result of {@link ZoneOffset#getId()}.
1216      * If the zone is not an offset, the textual name will be looked up
1217      * for the locale set in the {@link DateTimeFormatter}.
1218      * If the temporal object being printed represents an instant, or if it is a
1219      * local date-time that is not in a daylight saving gap or overlap, then the text
1220      * will be the summer or winter time text as appropriate.
1221      * If the lookup for text does not find any suitable result, then the
1222      * {@link ZoneId#getId() ID} will be printed.
1223      * If the zone cannot be obtained then an exception is thrown unless the
1224      * section of the formatter is optional.
1225      * <p>
1226      * During parsing, either the textual zone name, the zone ID or the offset
1227      * is accepted. Many textual zone names are not unique, such as CST can be
1228      * for both "Central Standard Time" and "China Standard Time". In this
1229      * situation, the zone id will be determined by the region information from
1230      * formatter's  {@link DateTimeFormatter#getLocale() locale} and the standard
1231      * zone id for that area, for example, America/New_York for the America Eastern
1232      * zone. This method also allows a set of preferred {@link ZoneId} to be
1233      * specified for parsing. The matched preferred zone id will be used if the
1234      * textural zone name being parsed is not unique.
1235      * <p>
1236      * If the zone cannot be parsed then an exception is thrown unless the
1237      * section of the formatter is optional.
1238      *
1239      * @param textStyle  the text style to use, not null
1240      * @param preferredZones  the set of preferred zone ids, not null
1241      * @return this, for chaining, not null
1242      */
1243     public DateTimeFormatterBuilder appendZoneText(TextStyle textStyle,
1244                                                    Set<ZoneId> preferredZones) {
1245         Objects.requireNonNull(preferredZones, "preferredZones");
1246         appendInternal(new ZoneTextPrinterParser(textStyle, preferredZones, false));
1247         return this;
1248     }
1249     //----------------------------------------------------------------------
1250     /**
1251      * Appends the generic time-zone name, such as 'Pacific Time', to the formatter.
1252      * <p>
1253      * This appends an instruction to format/parse the generic textual
1254      * name of the zone to the builder. The generic name is the same throughout the whole
1255      * year, ignoring any daylight saving changes. For example, 'Pacific Time' is the
1256      * generic name, whereas 'Pacific Standard Time' and 'Pacific Daylight Time' are the
1257      * specific names, see {@link #appendZoneText(TextStyle)}.
1258      * <p>
1259      * During formatting, the zone is obtained using a mechanism equivalent
1260      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1261      * If the zone is a {@code ZoneOffset} it will be printed using the
1262      * result of {@link ZoneOffset#getId()}.
1263      * If the zone is not an offset, the textual name will be looked up
1264      * for the locale set in the {@link DateTimeFormatter}.
1265      * If the lookup for text does not find any suitable result, then the
1266      * {@link ZoneId#getId() ID} will be printed.
1267      * If the zone cannot be obtained then an exception is thrown unless the
1268      * section of the formatter is optional.
1269      * <p>
1270      * During parsing, either the textual zone name, the zone ID or the offset
1271      * is accepted. Many textual zone names are not unique, such as CST can be
1272      * for both "Central Standard Time" and "China Standard Time". In this
1273      * situation, the zone id will be determined by the region information from
1274      * formatter's  {@link DateTimeFormatter#getLocale() locale} and the standard
1275      * zone id for that area, for example, America/New_York for the America Eastern zone.
1276      * The {@link #appendGenericZoneText(TextStyle, Set)} may be used
1277      * to specify a set of preferred {@link ZoneId} in this situation.
1278      *
1279      * @param textStyle  the text style to use, not null
1280      * @return this, for chaining, not null
1281      */
1282     public DateTimeFormatterBuilder appendGenericZoneText(TextStyle textStyle) {
1283         appendInternal(new ZoneTextPrinterParser(textStyle, null, true));
1284         return this;
1285     }
1286 
1287     /**
1288      * Appends the generic time-zone name, such as 'Pacific Time', to the formatter.
1289      * <p>
1290      * This appends an instruction to format/parse the generic textual
1291      * name of the zone to the builder. The generic name is the same throughout the whole
1292      * year, ignoring any daylight saving changes. For example, 'Pacific Time' is the
1293      * generic name, whereas 'Pacific Standard Time' and 'Pacific Daylight Time' are the
1294      * specific names, see {@link #appendZoneText(TextStyle)}.
1295      * <p>
1296      * This method also allows a set of preferred {@link ZoneId} to be
1297      * specified for parsing. The matched preferred zone id will be used if the
1298      * textural zone name being parsed is not unique.
1299      * <p>
1300      * See {@link #appendGenericZoneText(TextStyle)} for details about
1301      * formatting and parsing.
1302      *
1303      * @param textStyle  the text style to use, not null
1304      * @param preferredZones  the set of preferred zone ids, not null
1305      * @return this, for chaining, not null
1306      */
1307     public DateTimeFormatterBuilder appendGenericZoneText(TextStyle textStyle,
1308                                                           Set<ZoneId> preferredZones) {
1309         appendInternal(new ZoneTextPrinterParser(textStyle, preferredZones, true));
1310         return this;
1311     }
1312 
1313     //-----------------------------------------------------------------------
1314     /**
1315      * Appends the chronology ID, such as 'ISO' or 'ThaiBuddhist', to the formatter.
1316      * <p>
1317      * This appends an instruction to format/parse the chronology ID to the builder.
1318      * <p>
1319      * During formatting, the chronology is obtained using a mechanism equivalent
1320      * to querying the temporal with {@link TemporalQueries#chronology()}.
1321      * It will be printed using the result of {@link Chronology#getId()}.
1322      * If the chronology cannot be obtained then an exception is thrown unless the
1323      * section of the formatter is optional.
1324      * <p>
1325      * During parsing, the chronology is parsed and must match one of the chronologies
1326      * in {@link Chronology#getAvailableChronologies()}.
1327      * If the chronology cannot be parsed then an exception is thrown unless the
1328      * section of the formatter is optional.
1329      * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
1330      *
1331      * @return this, for chaining, not null
1332      */
1333     public DateTimeFormatterBuilder appendChronologyId() {
1334         appendInternal(new ChronoPrinterParser(null));
1335         return this;
1336     }
1337 
1338     /**
1339      * Appends the chronology name to the formatter.
1340      * <p>
1341      * The calendar system name will be output during a format.
1342      * If the chronology cannot be obtained then an exception will be thrown.
1343      *
1344      * @param textStyle  the text style to use, not null
1345      * @return this, for chaining, not null
1346      */
1347     public DateTimeFormatterBuilder appendChronologyText(TextStyle textStyle) {
1348         Objects.requireNonNull(textStyle, "textStyle");
1349         appendInternal(new ChronoPrinterParser(textStyle));
1350         return this;
1351     }
1352 
1353     //-----------------------------------------------------------------------
1354     /**
1355      * Appends a localized date-time pattern to the formatter.
1356      * <p>
1357      * This appends a localized section to the builder, suitable for outputting
1358      * a date, time or date-time combination. The format of the localized
1359      * section is lazily looked up based on four items:
1360      * <ul>
1361      * <li>the {@code dateStyle} specified to this method
1362      * <li>the {@code timeStyle} specified to this method
1363      * <li>the {@code Locale} of the {@code DateTimeFormatter}
1364      * <li>the {@code Chronology}, selecting the best available
1365      * </ul>
1366      * During formatting, the chronology is obtained from the temporal object
1367      * being formatted, which may have been overridden by
1368      * {@link DateTimeFormatter#withChronology(Chronology)}.
1369      * The {@code FULL} and {@code LONG} styles typically require a time-zone.
1370      * When formatting using these styles, a {@code ZoneId} must be available,
1371      * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}.
1372      * <p>
1373      * During parsing, if a chronology has already been parsed, then it is used.
1374      * Otherwise the default from {@code DateTimeFormatter.withChronology(Chronology)}
1375      * is used, with {@code IsoChronology} as the fallback.
1376      * <p>
1377      * Note that this method provides similar functionality to methods on
1378      * {@code DateFormat} such as {@link java.text.DateFormat#getDateTimeInstance(int, int)}.
1379      *
1380      * @param dateStyle  the date style to use, null means no date required
1381      * @param timeStyle  the time style to use, null means no time required
1382      * @return this, for chaining, not null
1383      * @throws IllegalArgumentException if both the date and time styles are null
1384      */
1385     public DateTimeFormatterBuilder appendLocalized(FormatStyle dateStyle, FormatStyle timeStyle) {
1386         if (dateStyle == null && timeStyle == null) {
1387             throw new IllegalArgumentException("Either the date or time style must be non-null");
1388         }
1389         appendInternal(new LocalizedPrinterParser(dateStyle, timeStyle));
1390         return this;
1391     }
1392 
1393     //-----------------------------------------------------------------------
1394     /**
1395      * Appends a character literal to the formatter.
1396      * <p>
1397      * This character will be output during a format.
1398      *
1399      * @param literal  the literal to append, not null
1400      * @return this, for chaining, not null
1401      */
1402     public DateTimeFormatterBuilder appendLiteral(char literal) {
1403         appendInternal(new CharLiteralPrinterParser(literal));
1404         return this;
1405     }
1406 
1407     /**
1408      * Appends a string literal to the formatter.
1409      * <p>
1410      * This string will be output during a format.
1411      * <p>
1412      * If the literal is empty, nothing is added to the formatter.
1413      *
1414      * @param literal  the literal to append, not null
1415      * @return this, for chaining, not null
1416      */
1417     public DateTimeFormatterBuilder appendLiteral(String literal) {
1418         Objects.requireNonNull(literal, "literal");
1419         if (literal.length() > 0) {
1420             if (literal.length() == 1) {
1421                 appendInternal(new CharLiteralPrinterParser(literal.charAt(0)));
1422             } else {
1423                 appendInternal(new StringLiteralPrinterParser(literal));
1424             }
1425         }
1426         return this;
1427     }
1428 
1429     //-----------------------------------------------------------------------
1430     /**
1431      * Appends all the elements of a formatter to the builder.
1432      * <p>
1433      * This method has the same effect as appending each of the constituent
1434      * parts of the formatter directly to this builder.
1435      *
1436      * @param formatter  the formatter to add, not null
1437      * @return this, for chaining, not null
1438      */
1439     public DateTimeFormatterBuilder append(DateTimeFormatter formatter) {
1440         Objects.requireNonNull(formatter, "formatter");
1441         appendInternal(formatter.toPrinterParser(false));
1442         return this;
1443     }
1444 
1445     /**
1446      * Appends a formatter to the builder which will optionally format/parse.
1447      * <p>
1448      * This method has the same effect as appending each of the constituent
1449      * parts directly to this builder surrounded by an {@link #optionalStart()} and
1450      * {@link #optionalEnd()}.
1451      * <p>
1452      * The formatter will format if data is available for all the fields contained within it.
1453      * The formatter will parse if the string matches, otherwise no error is returned.
1454      *
1455      * @param formatter  the formatter to add, not null
1456      * @return this, for chaining, not null
1457      */
1458     public DateTimeFormatterBuilder appendOptional(DateTimeFormatter formatter) {
1459         Objects.requireNonNull(formatter, "formatter");
1460         appendInternal(formatter.toPrinterParser(true));
1461         return this;
1462     }
1463 
1464     //-----------------------------------------------------------------------
1465     /**
1466      * Appends the elements defined by the specified pattern to the builder.
1467      * <p>
1468      * All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters.
1469      * The characters '#', '{' and '}' are reserved for future use.
1470      * The characters '[' and ']' indicate optional patterns.
1471      * The following pattern letters are defined:
1472      * <pre>
1473      *  Symbol  Meaning                     Presentation      Examples
1474      *  ------  -------                     ------------      -------
1475      *   G       era                         text              AD; Anno Domini; A
1476      *   u       year                        year              2004; 04
1477      *   y       year-of-era                 year              2004; 04
1478      *   D       day-of-year                 number            189
1479      *   M/L     month-of-year               number/text       7; 07; Jul; July; J
1480      *   d       day-of-month                number            10
1481      *   g       modified-julian-day         number            2451334
1482      *
1483      *   Q/q     quarter-of-year             number/text       3; 03; Q3; 3rd quarter
1484      *   Y       week-based-year             year              1996; 96
1485      *   w       week-of-week-based-year     number            27
1486      *   W       week-of-month               number            4
1487      *   E       day-of-week                 text              Tue; Tuesday; T
1488      *   e/c     localized day-of-week       number/text       2; 02; Tue; Tuesday; T
1489      *   F       week-of-month               number            3
1490      *
1491      *   a       am-pm-of-day                text              PM
1492      *   h       clock-hour-of-am-pm (1-12)  number            12
1493      *   K       hour-of-am-pm (0-11)        number            0
1494      *   k       clock-hour-of-am-pm (1-24)  number            0
1495      *
1496      *   H       hour-of-day (0-23)          number            0
1497      *   m       minute-of-hour              number            30
1498      *   s       second-of-minute            number            55
1499      *   S       fraction-of-second          fraction          978
1500      *   A       milli-of-day                number            1234
1501      *   n       nano-of-second              number            987654321
1502      *   N       nano-of-day                 number            1234000000
1503      *
1504      *   V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
1505      *   v       generic time-zone name      zone-name         PT, Pacific Time
1506      *   z       time-zone name              zone-name         Pacific Standard Time; PST
1507      *   O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
1508      *   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15
1509      *   x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15
1510      *   Z       zone-offset                 offset-Z          +0000; -0800; -08:00
1511      *
1512      *   p       pad next                    pad modifier      1
1513      *
1514      *   '       escape for text             delimiter
1515      *   ''      single quote                literal           '
1516      *   [       optional section start
1517      *   ]       optional section end
1518      *   #       reserved for future use
1519      *   {       reserved for future use
1520      *   }       reserved for future use
1521      * </pre>
1522      * <p>
1523      * The count of pattern letters determine the format.
1524      * See <a href="DateTimeFormatter.html#patterns">DateTimeFormatter</a> for a user-focused description of the patterns.
1525      * The following tables define how the pattern letters map to the builder.
1526      * <p>
1527      * <b>Date fields</b>: Pattern letters to output a date.
1528      * <pre>
1529      *  Pattern  Count  Equivalent builder methods
1530      *  -------  -----  --------------------------
1531      *    G       1      appendText(ChronoField.ERA, TextStyle.SHORT)
1532      *    GG      2      appendText(ChronoField.ERA, TextStyle.SHORT)
1533      *    GGG     3      appendText(ChronoField.ERA, TextStyle.SHORT)
1534      *    GGGG    4      appendText(ChronoField.ERA, TextStyle.FULL)
1535      *    GGGGG   5      appendText(ChronoField.ERA, TextStyle.NARROW)
1536      *
1537      *    u       1      appendValue(ChronoField.YEAR, 1, 19, SignStyle.NORMAL)
1538      *    uu      2      appendValueReduced(ChronoField.YEAR, 2, 2000)
1539      *    uuu     3      appendValue(ChronoField.YEAR, 3, 19, SignStyle.NORMAL)
1540      *    u..u    4..n   appendValue(ChronoField.YEAR, n, 19, SignStyle.EXCEEDS_PAD)
1541      *    y       1      appendValue(ChronoField.YEAR_OF_ERA, 1, 19, SignStyle.NORMAL)
1542      *    yy      2      appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2000)
1543      *    yyy     3      appendValue(ChronoField.YEAR_OF_ERA, 3, 19, SignStyle.NORMAL)
1544      *    y..y    4..n   appendValue(ChronoField.YEAR_OF_ERA, n, 19, SignStyle.EXCEEDS_PAD)
1545      *    Y       1      append special localized WeekFields element for numeric week-based-year
1546      *    YY      2      append special localized WeekFields element for reduced numeric week-based-year 2 digits
1547      *    YYY     3      append special localized WeekFields element for numeric week-based-year (3, 19, SignStyle.NORMAL)
1548      *    Y..Y    4..n   append special localized WeekFields element for numeric week-based-year (n, 19, SignStyle.EXCEEDS_PAD)
1549      *
1550      *    Q       1      appendValue(IsoFields.QUARTER_OF_YEAR)
1551      *    QQ      2      appendValue(IsoFields.QUARTER_OF_YEAR, 2)
1552      *    QQQ     3      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.SHORT)
1553      *    QQQQ    4      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.FULL)
1554      *    QQQQQ   5      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.NARROW)
1555      *    q       1      appendValue(IsoFields.QUARTER_OF_YEAR)
1556      *    qq      2      appendValue(IsoFields.QUARTER_OF_YEAR, 2)
1557      *    qqq     3      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.SHORT_STANDALONE)
1558      *    qqqq    4      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.FULL_STANDALONE)
1559      *    qqqqq   5      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.NARROW_STANDALONE)
1560      *
1561      *    M       1      appendValue(ChronoField.MONTH_OF_YEAR)
1562      *    MM      2      appendValue(ChronoField.MONTH_OF_YEAR, 2)
1563      *    MMM     3      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT)
1564      *    MMMM    4      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.FULL)
1565      *    MMMMM   5      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.NARROW)
1566      *    L       1      appendValue(ChronoField.MONTH_OF_YEAR)
1567      *    LL      2      appendValue(ChronoField.MONTH_OF_YEAR, 2)
1568      *    LLL     3      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT_STANDALONE)
1569      *    LLLL    4      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.FULL_STANDALONE)
1570      *    LLLLL   5      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.NARROW_STANDALONE)
1571      *
1572      *    w       1      append special localized WeekFields element for numeric week-of-year
1573      *    ww      2      append special localized WeekFields element for numeric week-of-year, zero-padded
1574      *    W       1      append special localized WeekFields element for numeric week-of-month
1575      *    d       1      appendValue(ChronoField.DAY_OF_MONTH)
1576      *    dd      2      appendValue(ChronoField.DAY_OF_MONTH, 2)
1577      *    D       1      appendValue(ChronoField.DAY_OF_YEAR)
1578      *    DD      2      appendValue(ChronoField.DAY_OF_YEAR, 2, 3, SignStyle.NOT_NEGATIVE)
1579      *    DDD     3      appendValue(ChronoField.DAY_OF_YEAR, 3)
1580      *    F       1      appendValue(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)
1581      *    g..g    1..n   appendValue(JulianFields.MODIFIED_JULIAN_DAY, n, 19, SignStyle.NORMAL)
1582      *    E       1      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
1583      *    EE      2      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
1584      *    EEE     3      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
1585      *    EEEE    4      appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL)
1586      *    EEEEE   5      appendText(ChronoField.DAY_OF_WEEK, TextStyle.NARROW)
1587      *    e       1      append special localized WeekFields element for numeric day-of-week
1588      *    ee      2      append special localized WeekFields element for numeric day-of-week, zero-padded
1589      *    eee     3      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
1590      *    eeee    4      appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL)
1591      *    eeeee   5      appendText(ChronoField.DAY_OF_WEEK, TextStyle.NARROW)
1592      *    c       1      append special localized WeekFields element for numeric day-of-week
1593      *    ccc     3      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT_STANDALONE)
1594      *    cccc    4      appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL_STANDALONE)
1595      *    ccccc   5      appendText(ChronoField.DAY_OF_WEEK, TextStyle.NARROW_STANDALONE)
1596      * </pre>
1597      * <p>
1598      * <b>Time fields</b>: Pattern letters to output a time.
1599      * <pre>
1600      *  Pattern  Count  Equivalent builder methods
1601      *  -------  -----  --------------------------
1602      *    a       1      appendText(ChronoField.AMPM_OF_DAY, TextStyle.SHORT)
1603      *    h       1      appendValue(ChronoField.CLOCK_HOUR_OF_AMPM)
1604      *    hh      2      appendValue(ChronoField.CLOCK_HOUR_OF_AMPM, 2)
1605      *    H       1      appendValue(ChronoField.HOUR_OF_DAY)
1606      *    HH      2      appendValue(ChronoField.HOUR_OF_DAY, 2)
1607      *    k       1      appendValue(ChronoField.CLOCK_HOUR_OF_DAY)
1608      *    kk      2      appendValue(ChronoField.CLOCK_HOUR_OF_DAY, 2)
1609      *    K       1      appendValue(ChronoField.HOUR_OF_AMPM)
1610      *    KK      2      appendValue(ChronoField.HOUR_OF_AMPM, 2)
1611      *    m       1      appendValue(ChronoField.MINUTE_OF_HOUR)
1612      *    mm      2      appendValue(ChronoField.MINUTE_OF_HOUR, 2)
1613      *    s       1      appendValue(ChronoField.SECOND_OF_MINUTE)
1614      *    ss      2      appendValue(ChronoField.SECOND_OF_MINUTE, 2)
1615      *
1616      *    S..S    1..n   appendFraction(ChronoField.NANO_OF_SECOND, n, n, false)
1617      *    A..A    1..n   appendValue(ChronoField.MILLI_OF_DAY, n, 19, SignStyle.NOT_NEGATIVE)
1618      *    n..n    1..n   appendValue(ChronoField.NANO_OF_SECOND, n, 19, SignStyle.NOT_NEGATIVE)
1619      *    N..N    1..n   appendValue(ChronoField.NANO_OF_DAY, n, 19, SignStyle.NOT_NEGATIVE)
1620      * </pre>
1621      * <p>
1622      * <b>Zone ID</b>: Pattern letters to output {@code ZoneId}.
1623      * <pre>
1624      *  Pattern  Count  Equivalent builder methods
1625      *  -------  -----  --------------------------
1626      *    VV      2      appendZoneId()
1627      *    v       1      appendGenericZoneText(TextStyle.SHORT)
1628      *    vvvv    4      appendGenericZoneText(TextStyle.FULL)
1629      *    z       1      appendZoneText(TextStyle.SHORT)
1630      *    zz      2      appendZoneText(TextStyle.SHORT)
1631      *    zzz     3      appendZoneText(TextStyle.SHORT)
1632      *    zzzz    4      appendZoneText(TextStyle.FULL)
1633      * </pre>
1634      * <p>
1635      * <b>Zone offset</b>: Pattern letters to output {@code ZoneOffset}.
1636      * <pre>
1637      *  Pattern  Count  Equivalent builder methods
1638      *  -------  -----  --------------------------
1639      *    O       1      appendLocalizedOffset(TextStyle.SHORT)
1640      *    OOOO    4      appendLocalizedOffset(TextStyle.FULL)
1641      *    X       1      appendOffset("+HHmm","Z")
1642      *    XX      2      appendOffset("+HHMM","Z")
1643      *    XXX     3      appendOffset("+HH:MM","Z")
1644      *    XXXX    4      appendOffset("+HHMMss","Z")
1645      *    XXXXX   5      appendOffset("+HH:MM:ss","Z")
1646      *    x       1      appendOffset("+HHmm","+00")
1647      *    xx      2      appendOffset("+HHMM","+0000")
1648      *    xxx     3      appendOffset("+HH:MM","+00:00")
1649      *    xxxx    4      appendOffset("+HHMMss","+0000")
1650      *    xxxxx   5      appendOffset("+HH:MM:ss","+00:00")
1651      *    Z       1      appendOffset("+HHMM","+0000")
1652      *    ZZ      2      appendOffset("+HHMM","+0000")
1653      *    ZZZ     3      appendOffset("+HHMM","+0000")
1654      *    ZZZZ    4      appendLocalizedOffset(TextStyle.FULL)
1655      *    ZZZZZ   5      appendOffset("+HH:MM:ss","Z")
1656      * </pre>
1657      * <p>
1658      * <b>Modifiers</b>: Pattern letters that modify the rest of the pattern:
1659      * <pre>
1660      *  Pattern  Count  Equivalent builder methods
1661      *  -------  -----  --------------------------
1662      *    [       1      optionalStart()
1663      *    ]       1      optionalEnd()
1664      *    p..p    1..n   padNext(n)
1665      * </pre>
1666      * <p>
1667      * Any sequence of letters not specified above, unrecognized letter or
1668      * reserved character will throw an exception.
1669      * Future versions may add to the set of patterns.
1670      * It is recommended to use single quotes around all characters that you want
1671      * to output directly to ensure that future changes do not break your application.
1672      * <p>
1673      * Note that the pattern string is similar, but not identical, to
1674      * {@link java.text.SimpleDateFormat SimpleDateFormat}.
1675      * The pattern string is also similar, but not identical, to that defined by the
1676      * Unicode Common Locale Data Repository (CLDR/LDML).
1677      * Pattern letters 'X' and 'u' are aligned with Unicode CLDR/LDML.
1678      * By contrast, {@code SimpleDateFormat} uses 'u' for the numeric day of week.
1679      * Pattern letters 'y' and 'Y' parse years of two digits and more than 4 digits differently.
1680      * Pattern letters 'n', 'A', 'N', and 'p' are added.
1681      * Number types will reject large numbers.
1682      *
1683      * @param pattern  the pattern to add, not null
1684      * @return this, for chaining, not null
1685      * @throws IllegalArgumentException if the pattern is invalid
1686      */
1687     public DateTimeFormatterBuilder appendPattern(String pattern) {
1688         Objects.requireNonNull(pattern, "pattern");
1689         parsePattern(pattern);
1690         return this;
1691     }
1692 
1693     private void parsePattern(String pattern) {
1694         for (int pos = 0; pos < pattern.length(); pos++) {
1695             char cur = pattern.charAt(pos);
1696             if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) {
1697                 int start = pos++;
1698                 for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++);  // short loop
1699                 int count = pos - start;
1700                 // padding
1701                 if (cur == 'p') {
1702                     int pad = 0;
1703                     if (pos < pattern.length()) {
1704                         cur = pattern.charAt(pos);
1705                         if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) {
1706                             pad = count;
1707                             start = pos++;
1708                             for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++);  // short loop
1709                             count = pos - start;
1710                         }
1711                     }
1712                     if (pad == 0) {
1713                         throw new IllegalArgumentException(
1714                                 "Pad letter 'p' must be followed by valid pad pattern: " + pattern);
1715                     }
1716                     padNext(pad); // pad and continue parsing
1717                 }
1718                 // main rules
1719                 TemporalField field = FIELD_MAP.get(cur);
1720                 if (field != null) {
1721                     parseField(cur, count, field);
1722                 } else if (cur == 'z') {
1723                     if (count > 4) {
1724                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1725                     } else if (count == 4) {
1726                         appendZoneText(TextStyle.FULL);
1727                     } else {
1728                         appendZoneText(TextStyle.SHORT);
1729                     }
1730                 } else if (cur == 'V') {
1731                     if (count != 2) {
1732                         throw new IllegalArgumentException("Pattern letter count must be 2: " + cur);
1733                     }
1734                     appendZoneId();
1735                 } else if (cur == 'v') {
1736                     if (count == 1) {
1737                         appendGenericZoneText(TextStyle.SHORT);
1738                     } else if (count == 4) {
1739                         appendGenericZoneText(TextStyle.FULL);
1740                     } else {
1741                         throw new IllegalArgumentException("Wrong number of  pattern letters: " + cur);
1742                     }
1743                 } else if (cur == 'Z') {
1744                     if (count < 4) {
1745                         appendOffset("+HHMM", "+0000");
1746                     } else if (count == 4) {
1747                         appendLocalizedOffset(TextStyle.FULL);
1748                     } else if (count == 5) {
1749                         appendOffset("+HH:MM:ss","Z");
1750                     } else {
1751                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1752                     }
1753                 } else if (cur == 'O') {
1754                     if (count == 1) {
1755                         appendLocalizedOffset(TextStyle.SHORT);
1756                     } else if (count == 4) {
1757                         appendLocalizedOffset(TextStyle.FULL);
1758                     } else {
1759                         throw new IllegalArgumentException("Pattern letter count must be 1 or 4: " + cur);
1760                     }
1761                 } else if (cur == 'X') {
1762                     if (count > 5) {
1763                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1764                     }
1765                     appendOffset(OffsetIdPrinterParser.PATTERNS[count + (count == 1 ? 0 : 1)], "Z");
1766                 } else if (cur == 'x') {
1767                     if (count > 5) {
1768                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1769                     }
1770                     String zero = (count == 1 ? "+00" : (count % 2 == 0 ? "+0000" : "+00:00"));
1771                     appendOffset(OffsetIdPrinterParser.PATTERNS[count + (count == 1 ? 0 : 1)], zero);
1772                 } else if (cur == 'W') {
1773                     // Fields defined by Locale
1774                     if (count > 1) {
1775                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1776                     }
1777                     appendInternal(new WeekBasedFieldPrinterParser(cur, count));
1778                 } else if (cur == 'w') {
1779                     // Fields defined by Locale
1780                     if (count > 2) {
1781                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1782                     }
1783                     appendInternal(new WeekBasedFieldPrinterParser(cur, count));
1784                 } else if (cur == 'Y') {
1785                     // Fields defined by Locale
1786                     appendInternal(new WeekBasedFieldPrinterParser(cur, count));
1787                 } else {
1788                     throw new IllegalArgumentException("Unknown pattern letter: " + cur);
1789                 }
1790                 pos--;
1791 
1792             } else if (cur == '\'') {
1793                 // parse literals
1794                 int start = pos++;
1795                 for ( ; pos < pattern.length(); pos++) {
1796                     if (pattern.charAt(pos) == '\'') {
1797                         if (pos + 1 < pattern.length() && pattern.charAt(pos + 1) == '\'') {
1798                             pos++;
1799                         } else {
1800                             break;  // end of literal
1801                         }
1802                     }
1803                 }
1804                 if (pos >= pattern.length()) {
1805                     throw new IllegalArgumentException("Pattern ends with an incomplete string literal: " + pattern);
1806                 }
1807                 String str = pattern.substring(start + 1, pos);
1808                 if (str.length() == 0) {
1809                     appendLiteral('\'');
1810                 } else {
1811                     appendLiteral(str.replace("''", "'"));
1812                 }
1813 
1814             } else if (cur == '[') {
1815                 optionalStart();
1816 
1817             } else if (cur == ']') {
1818                 if (active.parent == null) {
1819                     throw new IllegalArgumentException("Pattern invalid as it contains ] without previous [");
1820                 }
1821                 optionalEnd();
1822 
1823             } else if (cur == '{' || cur == '}' || cur == '#') {
1824                 throw new IllegalArgumentException("Pattern includes reserved character: '" + cur + "'");
1825             } else {
1826                 appendLiteral(cur);
1827             }
1828         }
1829     }
1830 
1831     @SuppressWarnings("fallthrough")
1832     private void parseField(char cur, int count, TemporalField field) {
1833         boolean standalone = false;
1834         switch (cur) {
1835             case 'u':
1836             case 'y':
1837                 if (count == 2) {
1838                     appendValueReduced(field, 2, 2, ReducedPrinterParser.BASE_DATE);
1839                 } else if (count < 4) {
1840                     appendValue(field, count, 19, SignStyle.NORMAL);
1841                 } else {
1842                     appendValue(field, count, 19, SignStyle.EXCEEDS_PAD);
1843                 }
1844                 break;
1845             case 'c':
1846                 if (count == 2) {
1847                     throw new IllegalArgumentException("Invalid pattern \"cc\"");
1848                 }
1849                 /*fallthrough*/
1850             case 'L':
1851             case 'q':
1852                 standalone = true;
1853                 /*fallthrough*/
1854             case 'M':
1855             case 'Q':
1856             case 'E':
1857             case 'e':
1858                 switch (count) {
1859                     case 1:
1860                     case 2:
1861                         if (cur == 'c' || cur == 'e') {
1862                             appendInternal(new WeekBasedFieldPrinterParser(cur, count));
1863                         } else if (cur == 'E') {
1864                             appendText(field, TextStyle.SHORT);
1865                         } else {
1866                             if (count == 1) {
1867                                 appendValue(field);
1868                             } else {
1869                                 appendValue(field, 2);
1870                             }
1871                         }
1872                         break;
1873                     case 3:
1874                         appendText(field, standalone ? TextStyle.SHORT_STANDALONE : TextStyle.SHORT);
1875                         break;
1876                     case 4:
1877                         appendText(field, standalone ? TextStyle.FULL_STANDALONE : TextStyle.FULL);
1878                         break;
1879                     case 5:
1880                         appendText(field, standalone ? TextStyle.NARROW_STANDALONE : TextStyle.NARROW);
1881                         break;
1882                     default:
1883                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1884                 }
1885                 break;
1886             case 'a':
1887                 if (count == 1) {
1888                     appendText(field, TextStyle.SHORT);
1889                 } else {
1890                     throw new IllegalArgumentException("Too many pattern letters: " + cur);
1891                 }
1892                 break;
1893             case 'G':
1894                 switch (count) {
1895                     case 1:
1896                     case 2:
1897                     case 3:
1898                         appendText(field, TextStyle.SHORT);
1899                         break;
1900                     case 4:
1901                         appendText(field, TextStyle.FULL);
1902                         break;
1903                     case 5:
1904                         appendText(field, TextStyle.NARROW);
1905                         break;
1906                     default:
1907                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1908                 }
1909                 break;
1910             case 'S':
1911                 appendFraction(NANO_OF_SECOND, count, count, false);
1912                 break;
1913             case 'F':
1914                 if (count == 1) {
1915                     appendValue(field);
1916                 } else {
1917                     throw new IllegalArgumentException("Too many pattern letters: " + cur);
1918                 }
1919                 break;
1920             case 'd':
1921             case 'h':
1922             case 'H':
1923             case 'k':
1924             case 'K':
1925             case 'm':
1926             case 's':
1927                 if (count == 1) {
1928                     appendValue(field);
1929                 } else if (count == 2) {
1930                     appendValue(field, count);
1931                 } else {
1932                     throw new IllegalArgumentException("Too many pattern letters: " + cur);
1933                 }
1934                 break;
1935             case 'D':
1936                 if (count == 1) {
1937                     appendValue(field);
1938                 } else if (count == 2 || count == 3) {
1939                     appendValue(field, count, 3, SignStyle.NOT_NEGATIVE);
1940                 } else {
1941                     throw new IllegalArgumentException("Too many pattern letters: " + cur);
1942                 }
1943                 break;
1944             case 'g':
1945                 appendValue(field, count, 19, SignStyle.NORMAL);
1946                 break;
1947             case 'A':
1948             case 'n':
1949             case 'N':
1950                 appendValue(field, count, 19, SignStyle.NOT_NEGATIVE);
1951                 break;
1952             default:
1953                 if (count == 1) {
1954                     appendValue(field);
1955                 } else {
1956                     appendValue(field, count);
1957                 }
1958                 break;
1959         }
1960     }
1961 
1962     /** Map of letters to fields. */
1963     private static final Map<Character, TemporalField> FIELD_MAP = new HashMap<>();
1964     static {
1965         // SDF = SimpleDateFormat
1966         FIELD_MAP.put('G', ChronoField.ERA);                       // SDF, LDML (different to both for 1/2 chars)
1967         FIELD_MAP.put('y', ChronoField.YEAR_OF_ERA);               // SDF, LDML
1968         FIELD_MAP.put('u', ChronoField.YEAR);                      // LDML (different in SDF)
1969         FIELD_MAP.put('Q', IsoFields.QUARTER_OF_YEAR);             // LDML (removed quarter from 310)
1970         FIELD_MAP.put('q', IsoFields.QUARTER_OF_YEAR);             // LDML (stand-alone)
1971         FIELD_MAP.put('M', ChronoField.MONTH_OF_YEAR);             // SDF, LDML
1972         FIELD_MAP.put('L', ChronoField.MONTH_OF_YEAR);             // SDF, LDML (stand-alone)
1973         FIELD_MAP.put('D', ChronoField.DAY_OF_YEAR);               // SDF, LDML
1974         FIELD_MAP.put('d', ChronoField.DAY_OF_MONTH);              // SDF, LDML
1975         FIELD_MAP.put('F', ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH);  // SDF, LDML
1976         FIELD_MAP.put('E', ChronoField.DAY_OF_WEEK);               // SDF, LDML (different to both for 1/2 chars)
1977         FIELD_MAP.put('c', ChronoField.DAY_OF_WEEK);               // LDML (stand-alone)
1978         FIELD_MAP.put('e', ChronoField.DAY_OF_WEEK);               // LDML (needs localized week number)
1979         FIELD_MAP.put('a', ChronoField.AMPM_OF_DAY);               // SDF, LDML
1980         FIELD_MAP.put('H', ChronoField.HOUR_OF_DAY);               // SDF, LDML
1981         FIELD_MAP.put('k', ChronoField.CLOCK_HOUR_OF_DAY);         // SDF, LDML
1982         FIELD_MAP.put('K', ChronoField.HOUR_OF_AMPM);              // SDF, LDML
1983         FIELD_MAP.put('h', ChronoField.CLOCK_HOUR_OF_AMPM);        // SDF, LDML
1984         FIELD_MAP.put('m', ChronoField.MINUTE_OF_HOUR);            // SDF, LDML
1985         FIELD_MAP.put('s', ChronoField.SECOND_OF_MINUTE);          // SDF, LDML
1986         FIELD_MAP.put('S', ChronoField.NANO_OF_SECOND);            // LDML (SDF uses milli-of-second number)
1987         FIELD_MAP.put('A', ChronoField.MILLI_OF_DAY);              // LDML
1988         FIELD_MAP.put('n', ChronoField.NANO_OF_SECOND);            // 310 (proposed for LDML)
1989         FIELD_MAP.put('N', ChronoField.NANO_OF_DAY);               // 310 (proposed for LDML)
1990         FIELD_MAP.put('g', JulianFields.MODIFIED_JULIAN_DAY);
1991         // 310 - z - time-zone names, matches LDML and SimpleDateFormat 1 to 4
1992         // 310 - Z - matches SimpleDateFormat and LDML
1993         // 310 - V - time-zone id, matches LDML
1994         // 310 - v - general timezone names, not matching exactly with LDML because LDML specify to fall back
1995         //           to 'VVVV' if general-nonlocation unavailable but here it's not falling back because of lack of data
1996         // 310 - p - prefix for padding
1997         // 310 - X - matches LDML, almost matches SDF for 1, exact match 2&3, extended 4&5
1998         // 310 - x - matches LDML
1999         // 310 - w, W, and Y are localized forms matching LDML
2000         // LDML - U - cycle year name, not supported by 310 yet
2001         // LDML - l - deprecated
2002         // LDML - j - not relevant
2003     }
2004 
2005     //-----------------------------------------------------------------------
2006     /**
2007      * Causes the next added printer/parser to pad to a fixed width using a space.
2008      * <p>
2009      * This padding will pad to a fixed width using spaces.
2010      * <p>
2011      * During formatting, the decorated element will be output and then padded
2012      * to the specified width. An exception will be thrown during formatting if
2013      * the pad width is exceeded.
2014      * <p>
2015      * During parsing, the padding and decorated element are parsed.
2016      * If parsing is lenient, then the pad width is treated as a maximum.
2017      * The padding is parsed greedily. Thus, if the decorated element starts with
2018      * the pad character, it will not be parsed.
2019      *
2020      * @param padWidth  the pad width, 1 or greater
2021      * @return this, for chaining, not null
2022      * @throws IllegalArgumentException if pad width is too small
2023      */
2024     public DateTimeFormatterBuilder padNext(int padWidth) {
2025         return padNext(padWidth, ' ');
2026     }
2027 
2028     /**
2029      * Causes the next added printer/parser to pad to a fixed width.
2030      * <p>
2031      * This padding is intended for padding other than zero-padding.
2032      * Zero-padding should be achieved using the appendValue methods.
2033      * <p>
2034      * During formatting, the decorated element will be output and then padded
2035      * to the specified width. An exception will be thrown during formatting if
2036      * the pad width is exceeded.
2037      * <p>
2038      * During parsing, the padding and decorated element are parsed.
2039      * If parsing is lenient, then the pad width is treated as a maximum.
2040      * If parsing is case insensitive, then the pad character is matched ignoring case.
2041      * The padding is parsed greedily. Thus, if the decorated element starts with
2042      * the pad character, it will not be parsed.
2043      *
2044      * @param padWidth  the pad width, 1 or greater
2045      * @param padChar  the pad character
2046      * @return this, for chaining, not null
2047      * @throws IllegalArgumentException if pad width is too small
2048      */
2049     public DateTimeFormatterBuilder padNext(int padWidth, char padChar) {
2050         if (padWidth < 1) {
2051             throw new IllegalArgumentException("The pad width must be at least one but was " + padWidth);
2052         }
2053         active.padNextWidth = padWidth;
2054         active.padNextChar = padChar;
2055         active.valueParserIndex = -1;
2056         return this;
2057     }
2058 
2059     //-----------------------------------------------------------------------
2060     /**
2061      * Mark the start of an optional section.
2062      * <p>
2063      * The output of formatting can include optional sections, which may be nested.
2064      * An optional section is started by calling this method and ended by calling
2065      * {@link #optionalEnd()} or by ending the build process.
2066      * <p>
2067      * All elements in the optional section are treated as optional.
2068      * During formatting, the section is only output if data is available in the
2069      * {@code TemporalAccessor} for all the elements in the section.
2070      * During parsing, the whole section may be missing from the parsed string.
2071      * <p>
2072      * For example, consider a builder setup as
2073      * {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2)}.
2074      * The optional section ends automatically at the end of the builder.
2075      * During formatting, the minute will only be output if its value can be obtained from the date-time.
2076      * During parsing, the input will be successfully parsed whether the minute is present or not.
2077      *
2078      * @return this, for chaining, not null
2079      */
2080     public DateTimeFormatterBuilder optionalStart() {
2081         active.valueParserIndex = -1;
2082         active = new DateTimeFormatterBuilder(active, true);
2083         return this;
2084     }
2085 
2086     /**
2087      * Ends an optional section.
2088      * <p>
2089      * The output of formatting can include optional sections, which may be nested.
2090      * An optional section is started by calling {@link #optionalStart()} and ended
2091      * using this method (or at the end of the builder).
2092      * <p>
2093      * Calling this method without having previously called {@code optionalStart}
2094      * will throw an exception.
2095      * Calling this method immediately after calling {@code optionalStart} has no effect
2096      * on the formatter other than ending the (empty) optional section.
2097      * <p>
2098      * All elements in the optional section are treated as optional.
2099      * During formatting, the section is only output if data is available in the
2100      * {@code TemporalAccessor} for all the elements in the section.
2101      * During parsing, the whole section may be missing from the parsed string.
2102      * <p>
2103      * For example, consider a builder setup as
2104      * {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2).optionalEnd()}.
2105      * During formatting, the minute will only be output if its value can be obtained from the date-time.
2106      * During parsing, the input will be successfully parsed whether the minute is present or not.
2107      *
2108      * @return this, for chaining, not null
2109      * @throws IllegalStateException if there was no previous call to {@code optionalStart}
2110      */
2111     public DateTimeFormatterBuilder optionalEnd() {
2112         if (active.parent == null) {
2113             throw new IllegalStateException("Cannot call optionalEnd() as there was no previous call to optionalStart()");
2114         }
2115         if (active.printerParsers.size() > 0) {
2116             CompositePrinterParser cpp = new CompositePrinterParser(active.printerParsers, active.optional);
2117             active = active.parent;
2118             appendInternal(cpp);
2119         } else {
2120             active = active.parent;
2121         }
2122         return this;
2123     }
2124 
2125     //-----------------------------------------------------------------------
2126     /**
2127      * Appends a printer and/or parser to the internal list handling padding.
2128      *
2129      * @param pp  the printer-parser to add, not null
2130      * @return the index into the active parsers list
2131      */
2132     private int appendInternal(DateTimePrinterParser pp) {
2133         Objects.requireNonNull(pp, "pp");
2134         if (active.padNextWidth > 0) {
2135             if (pp != null) {
2136                 pp = new PadPrinterParserDecorator(pp, active.padNextWidth, active.padNextChar);
2137             }
2138             active.padNextWidth = 0;
2139             active.padNextChar = 0;
2140         }
2141         active.printerParsers.add(pp);
2142         active.valueParserIndex = -1;
2143         return active.printerParsers.size() - 1;
2144     }
2145 
2146     //-----------------------------------------------------------------------
2147     /**
2148      * Completes this builder by creating the {@code DateTimeFormatter}
2149      * using the default locale.
2150      * <p>
2151      * This will create a formatter with the {@linkplain Locale#getDefault(Locale.Category) default FORMAT locale}.
2152      * Numbers will be printed and parsed using the standard DecimalStyle.
2153      * The resolver style will be {@link ResolverStyle#SMART SMART}.
2154      * <p>
2155      * Calling this method will end any open optional sections by repeatedly
2156      * calling {@link #optionalEnd()} before creating the formatter.
2157      * <p>
2158      * This builder can still be used after creating the formatter if desired,
2159      * although the state may have been changed by calls to {@code optionalEnd}.
2160      *
2161      * @return the created formatter, not null
2162      */
2163     public DateTimeFormatter toFormatter() {
2164         return toFormatter(Locale.getDefault(Locale.Category.FORMAT));
2165     }
2166 
2167     /**
2168      * Completes this builder by creating the {@code DateTimeFormatter}
2169      * using the specified locale.
2170      * <p>
2171      * This will create a formatter with the specified locale.
2172      * Numbers will be printed and parsed using the standard DecimalStyle.
2173      * The resolver style will be {@link ResolverStyle#SMART SMART}.
2174      * <p>
2175      * Calling this method will end any open optional sections by repeatedly
2176      * calling {@link #optionalEnd()} before creating the formatter.
2177      * <p>
2178      * This builder can still be used after creating the formatter if desired,
2179      * although the state may have been changed by calls to {@code optionalEnd}.
2180      *
2181      * @param locale  the locale to use for formatting, not null
2182      * @return the created formatter, not null
2183      */
2184     public DateTimeFormatter toFormatter(Locale locale) {
2185         return toFormatter(locale, ResolverStyle.SMART, null);
2186     }
2187 
2188     /**
2189      * Completes this builder by creating the formatter.
2190      * This uses the default locale.
2191      *
2192      * @param resolverStyle  the resolver style to use, not null
2193      * @return the created formatter, not null
2194      */
2195     DateTimeFormatter toFormatter(ResolverStyle resolverStyle, Chronology chrono) {
2196         return toFormatter(Locale.getDefault(Locale.Category.FORMAT), resolverStyle, chrono);
2197     }
2198 
2199     /**
2200      * Completes this builder by creating the formatter.
2201      *
2202      * @param locale  the locale to use for formatting, not null
2203      * @param chrono  the chronology to use, may be null
2204      * @return the created formatter, not null
2205      */
2206     private DateTimeFormatter toFormatter(Locale locale, ResolverStyle resolverStyle, Chronology chrono) {
2207         Objects.requireNonNull(locale, "locale");
2208         while (active.parent != null) {
2209             optionalEnd();
2210         }
2211         CompositePrinterParser pp = new CompositePrinterParser(printerParsers, false);
2212         return new DateTimeFormatter(pp, locale, DecimalStyle.STANDARD,
2213                 resolverStyle, null, chrono, null);
2214     }
2215 
2216     //-----------------------------------------------------------------------
2217     /**
2218      * Strategy for formatting/parsing date-time information.
2219      * <p>
2220      * The printer may format any part, or the whole, of the input date-time object.
2221      * Typically, a complete format is constructed from a number of smaller
2222      * units, each outputting a single field.
2223      * <p>
2224      * The parser may parse any piece of text from the input, storing the result
2225      * in the context. Typically, each individual parser will just parse one
2226      * field, such as the day-of-month, storing the value in the context.
2227      * Once the parse is complete, the caller will then resolve the parsed values
2228      * to create the desired object, such as a {@code LocalDate}.
2229      * <p>
2230      * The parse position will be updated during the parse. Parsing will start at
2231      * the specified index and the return value specifies the new parse position
2232      * for the next parser. If an error occurs, the returned index will be negative
2233      * and will have the error position encoded using the complement operator.
2234      *
2235      * @implSpec
2236      * This interface must be implemented with care to ensure other classes operate correctly.
2237      * All implementations that can be instantiated must be final, immutable and thread-safe.
2238      * <p>
2239      * The context is not a thread-safe object and a new instance will be created
2240      * for each format that occurs. The context must not be stored in an instance
2241      * variable or shared with any other threads.
2242      */
2243     interface DateTimePrinterParser {
2244 
2245         /**
2246          * Prints the date-time object to the buffer.
2247          * <p>
2248          * The context holds information to use during the format.
2249          * It also contains the date-time information to be printed.
2250          * <p>
2251          * The buffer must not be mutated beyond the content controlled by the implementation.
2252          *
2253          * @param context  the context to format using, not null
2254          * @param buf  the buffer to append to, not null
2255          * @return false if unable to query the value from the date-time, true otherwise
2256          * @throws DateTimeException if the date-time cannot be printed successfully
2257          */
2258         boolean format(DateTimePrintContext context, StringBuilder buf);
2259 
2260         /**
2261          * Parses text into date-time information.
2262          * <p>
2263          * The context holds information to use during the parse.
2264          * It is also used to store the parsed date-time information.
2265          *
2266          * @param context  the context to use and parse into, not null
2267          * @param text  the input text to parse, not null
2268          * @param position  the position to start parsing at, from 0 to the text length
2269          * @return the new parse position, where negative means an error with the
2270          *  error position encoded using the complement ~ operator
2271          * @throws NullPointerException if the context or text is null
2272          * @throws IndexOutOfBoundsException if the position is invalid
2273          */
2274         int parse(DateTimeParseContext context, CharSequence text, int position);
2275     }
2276 
2277     //-----------------------------------------------------------------------
2278     /**
2279      * Composite printer and parser.
2280      */
2281     static final class CompositePrinterParser implements DateTimePrinterParser {
2282         private final DateTimePrinterParser[] printerParsers;
2283         private final boolean optional;
2284 
2285         CompositePrinterParser(List<DateTimePrinterParser> printerParsers, boolean optional) {
2286             this(printerParsers.toArray(new DateTimePrinterParser[printerParsers.size()]), optional);
2287         }
2288 
2289         CompositePrinterParser(DateTimePrinterParser[] printerParsers, boolean optional) {
2290             this.printerParsers = printerParsers;
2291             this.optional = optional;
2292         }
2293 
2294         /**
2295          * Returns a copy of this printer-parser with the optional flag changed.
2296          *
2297          * @param optional  the optional flag to set in the copy
2298          * @return the new printer-parser, not null
2299          */
2300         public CompositePrinterParser withOptional(boolean optional) {
2301             if (optional == this.optional) {
2302                 return this;
2303             }
2304             return new CompositePrinterParser(printerParsers, optional);
2305         }
2306 
2307         @Override
2308         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2309             int length = buf.length();
2310             if (optional) {
2311                 context.startOptional();
2312             }
2313             try {
2314                 for (DateTimePrinterParser pp : printerParsers) {
2315                     if (pp.format(context, buf) == false) {
2316                         buf.setLength(length);  // reset buffer
2317                         return true;
2318                     }
2319                 }
2320             } finally {
2321                 if (optional) {
2322                     context.endOptional();
2323                 }
2324             }
2325             return true;
2326         }
2327 
2328         @Override
2329         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2330             if (optional) {
2331                 context.startOptional();
2332                 int pos = position;
2333                 for (DateTimePrinterParser pp : printerParsers) {
2334                     pos = pp.parse(context, text, pos);
2335                     if (pos < 0) {
2336                         context.endOptional(false);
2337                         return position;  // return original position
2338                     }
2339                 }
2340                 context.endOptional(true);
2341                 return pos;
2342             } else {
2343                 for (DateTimePrinterParser pp : printerParsers) {
2344                     position = pp.parse(context, text, position);
2345                     if (position < 0) {
2346                         break;
2347                     }
2348                 }
2349                 return position;
2350             }
2351         }
2352 
2353         @Override
2354         public String toString() {
2355             StringBuilder buf = new StringBuilder();
2356             if (printerParsers != null) {
2357                 buf.append(optional ? "[" : "(");
2358                 for (DateTimePrinterParser pp : printerParsers) {
2359                     buf.append(pp);
2360                 }
2361                 buf.append(optional ? "]" : ")");
2362             }
2363             return buf.toString();
2364         }
2365     }
2366 
2367     //-----------------------------------------------------------------------
2368     /**
2369      * Pads the output to a fixed width.
2370      */
2371     static final class PadPrinterParserDecorator implements DateTimePrinterParser {
2372         private final DateTimePrinterParser printerParser;
2373         private final int padWidth;
2374         private final char padChar;
2375 
2376         /**
2377          * Constructor.
2378          *
2379          * @param printerParser  the printer, not null
2380          * @param padWidth  the width to pad to, 1 or greater
2381          * @param padChar  the pad character
2382          */
2383         PadPrinterParserDecorator(DateTimePrinterParser printerParser, int padWidth, char padChar) {
2384             // input checked by DateTimeFormatterBuilder
2385             this.printerParser = printerParser;
2386             this.padWidth = padWidth;
2387             this.padChar = padChar;
2388         }
2389 
2390         @Override
2391         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2392             int preLen = buf.length();
2393             if (printerParser.format(context, buf) == false) {
2394                 return false;
2395             }
2396             int len = buf.length() - preLen;
2397             if (len > padWidth) {
2398                 throw new DateTimeException(
2399                     "Cannot print as output of " + len + " characters exceeds pad width of " + padWidth);
2400             }
2401             for (int i = 0; i < padWidth - len; i++) {
2402                 buf.insert(preLen, padChar);
2403             }
2404             return true;
2405         }
2406 
2407         @Override
2408         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2409             // cache context before changed by decorated parser
2410             final boolean strict = context.isStrict();
2411             // parse
2412             if (position > text.length()) {
2413                 throw new IndexOutOfBoundsException();
2414             }
2415             if (position == text.length()) {
2416                 return ~position;  // no more characters in the string
2417             }
2418             int endPos = position + padWidth;
2419             if (endPos > text.length()) {
2420                 if (strict) {
2421                     return ~position;  // not enough characters in the string to meet the parse width
2422                 }
2423                 endPos = text.length();
2424             }
2425             int pos = position;
2426             while (pos < endPos && context.charEquals(text.charAt(pos), padChar)) {
2427                 pos++;
2428             }
2429             text = text.subSequence(0, endPos);
2430             int resultPos = printerParser.parse(context, text, pos);
2431             if (resultPos != endPos && strict) {
2432                 return ~(position + pos);  // parse of decorated field didn't parse to the end
2433             }
2434             return resultPos;
2435         }
2436 
2437         @Override
2438         public String toString() {
2439             return "Pad(" + printerParser + "," + padWidth + (padChar == ' ' ? ")" : ",'" + padChar + "')");
2440         }
2441     }
2442 
2443     //-----------------------------------------------------------------------
2444     /**
2445      * Enumeration to apply simple parse settings.
2446      */
2447     static enum SettingsParser implements DateTimePrinterParser {
2448         SENSITIVE,
2449         INSENSITIVE,
2450         STRICT,
2451         LENIENT;
2452 
2453         @Override
2454         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2455             return true;  // nothing to do here
2456         }
2457 
2458         @Override
2459         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2460             // using ordinals to avoid javac synthetic inner class
2461             switch (ordinal()) {
2462                 case 0: context.setCaseSensitive(true); break;
2463                 case 1: context.setCaseSensitive(false); break;
2464                 case 2: context.setStrict(true); break;
2465                 case 3: context.setStrict(false); break;
2466             }
2467             return position;
2468         }
2469 
2470         @Override
2471         public String toString() {
2472             // using ordinals to avoid javac synthetic inner class
2473             switch (ordinal()) {
2474                 case 0: return "ParseCaseSensitive(true)";
2475                 case 1: return "ParseCaseSensitive(false)";
2476                 case 2: return "ParseStrict(true)";
2477                 case 3: return "ParseStrict(false)";
2478             }
2479             throw new IllegalStateException("Unreachable");
2480         }
2481     }
2482 
2483     //-----------------------------------------------------------------------
2484     /**
2485      * Defaults a value into the parse if not currently present.
2486      */
2487     static class DefaultValueParser implements DateTimePrinterParser {
2488         private final TemporalField field;
2489         private final long value;
2490 
2491         DefaultValueParser(TemporalField field, long value) {
2492             this.field = field;
2493             this.value = value;
2494         }
2495 
2496         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2497             return true;
2498         }
2499 
2500         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2501             if (context.getParsed(field) == null) {
2502                 context.setParsedField(field, value, position, position);
2503             }
2504             return position;
2505         }
2506     }
2507 
2508     //-----------------------------------------------------------------------
2509     /**
2510      * Prints or parses a character literal.
2511      */
2512     static final class CharLiteralPrinterParser implements DateTimePrinterParser {
2513         private final char literal;
2514 
2515         CharLiteralPrinterParser(char literal) {
2516             this.literal = literal;
2517         }
2518 
2519         @Override
2520         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2521             buf.append(literal);
2522             return true;
2523         }
2524 
2525         @Override
2526         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2527             int length = text.length();
2528             if (position == length) {
2529                 return ~position;
2530             }
2531             char ch = text.charAt(position);
2532             if (ch != literal) {
2533                 if (context.isCaseSensitive() ||
2534                         (Character.toUpperCase(ch) != Character.toUpperCase(literal) &&
2535                          Character.toLowerCase(ch) != Character.toLowerCase(literal))) {
2536                     return ~position;
2537                 }
2538             }
2539             return position + 1;
2540         }
2541 
2542         @Override
2543         public String toString() {
2544             if (literal == '\'') {
2545                 return "''";
2546             }
2547             return "'" + literal + "'";
2548         }
2549     }
2550 
2551     //-----------------------------------------------------------------------
2552     /**
2553      * Prints or parses a string literal.
2554      */
2555     static final class StringLiteralPrinterParser implements DateTimePrinterParser {
2556         private final String literal;
2557 
2558         StringLiteralPrinterParser(String literal) {
2559             this.literal = literal;  // validated by caller
2560         }
2561 
2562         @Override
2563         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2564             buf.append(literal);
2565             return true;
2566         }
2567 
2568         @Override
2569         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2570             int length = text.length();
2571             if (position > length || position < 0) {
2572                 throw new IndexOutOfBoundsException();
2573             }
2574             if (context.subSequenceEquals(text, position, literal, 0, literal.length()) == false) {
2575                 return ~position;
2576             }
2577             return position + literal.length();
2578         }
2579 
2580         @Override
2581         public String toString() {
2582             String converted = literal.replace("'", "''");
2583             return "'" + converted + "'";
2584         }
2585     }
2586 
2587     //-----------------------------------------------------------------------
2588     /**
2589      * Prints and parses a numeric date-time field with optional padding.
2590      */
2591     static class NumberPrinterParser implements DateTimePrinterParser {
2592 
2593         /**
2594          * Array of 10 to the power of n.
2595          */
2596         static final long[] EXCEED_POINTS = new long[] {
2597             0L,
2598             10L,
2599             100L,
2600             1000L,
2601             10000L,
2602             100000L,
2603             1000000L,
2604             10000000L,
2605             100000000L,
2606             1000000000L,
2607             10000000000L,
2608         };
2609 
2610         final TemporalField field;
2611         final int minWidth;
2612         final int maxWidth;
2613         private final SignStyle signStyle;
2614         final int subsequentWidth;
2615 
2616         /**
2617          * Constructor.
2618          *
2619          * @param field  the field to format, not null
2620          * @param minWidth  the minimum field width, from 1 to 19
2621          * @param maxWidth  the maximum field width, from minWidth to 19
2622          * @param signStyle  the positive/negative sign style, not null
2623          */
2624         NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) {
2625             // validated by caller
2626             this.field = field;
2627             this.minWidth = minWidth;
2628             this.maxWidth = maxWidth;
2629             this.signStyle = signStyle;
2630             this.subsequentWidth = 0;
2631         }
2632 
2633         /**
2634          * Constructor.
2635          *
2636          * @param field  the field to format, not null
2637          * @param minWidth  the minimum field width, from 1 to 19
2638          * @param maxWidth  the maximum field width, from minWidth to 19
2639          * @param signStyle  the positive/negative sign style, not null
2640          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater,
2641          *  -1 if fixed width due to active adjacent parsing
2642          */
2643         protected NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle, int subsequentWidth) {
2644             // validated by caller
2645             this.field = field;
2646             this.minWidth = minWidth;
2647             this.maxWidth = maxWidth;
2648             this.signStyle = signStyle;
2649             this.subsequentWidth = subsequentWidth;
2650         }
2651 
2652         /**
2653          * Returns a new instance with fixed width flag set.
2654          *
2655          * @return a new updated printer-parser, not null
2656          */
2657         NumberPrinterParser withFixedWidth() {
2658             if (subsequentWidth == -1) {
2659                 return this;
2660             }
2661             return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, -1);
2662         }
2663 
2664         /**
2665          * Returns a new instance with an updated subsequent width.
2666          *
2667          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater
2668          * @return a new updated printer-parser, not null
2669          */
2670         NumberPrinterParser withSubsequentWidth(int subsequentWidth) {
2671             return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, this.subsequentWidth + subsequentWidth);
2672         }
2673 
2674         @Override
2675         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2676             Long valueLong = context.getValue(field);
2677             if (valueLong == null) {
2678                 return false;
2679             }
2680             long value = getValue(context, valueLong);
2681             DecimalStyle decimalStyle = context.getDecimalStyle();
2682             String str = (value == Long.MIN_VALUE ? "9223372036854775808" : Long.toString(Math.abs(value)));
2683             if (str.length() > maxWidth) {
2684                 throw new DateTimeException("Field " + field +
2685                     " cannot be printed as the value " + value +
2686                     " exceeds the maximum print width of " + maxWidth);
2687             }
2688             str = decimalStyle.convertNumberToI18N(str);
2689 
2690             if (value >= 0) {
2691                 switch (signStyle) {
2692                     case EXCEEDS_PAD:
2693                         if (minWidth < 19 && value >= EXCEED_POINTS[minWidth]) {
2694                             buf.append(decimalStyle.getPositiveSign());
2695                         }
2696                         break;
2697                     case ALWAYS:
2698                         buf.append(decimalStyle.getPositiveSign());
2699                         break;
2700                 }
2701             } else {
2702                 switch (signStyle) {
2703                     case NORMAL:
2704                     case EXCEEDS_PAD:
2705                     case ALWAYS:
2706                         buf.append(decimalStyle.getNegativeSign());
2707                         break;
2708                     case NOT_NEGATIVE:
2709                         throw new DateTimeException("Field " + field +
2710                             " cannot be printed as the value " + value +
2711                             " cannot be negative according to the SignStyle");
2712                 }
2713             }
2714             for (int i = 0; i < minWidth - str.length(); i++) {
2715                 buf.append(decimalStyle.getZeroDigit());
2716             }
2717             buf.append(str);
2718             return true;
2719         }
2720 
2721         /**
2722          * Gets the value to output.
2723          *
2724          * @param context  the context
2725          * @param value  the value of the field, not null
2726          * @return the value
2727          */
2728         long getValue(DateTimePrintContext context, long value) {
2729             return value;
2730         }
2731 
2732         /**
2733          * For NumberPrinterParser, the width is fixed depending on the
2734          * minWidth, maxWidth, signStyle and whether subsequent fields are fixed.
2735          * @param context the context
2736          * @return true if the field is fixed width
2737          * @see DateTimeFormatterBuilder#appendValue(java.time.temporal.TemporalField, int)
2738          */
2739         boolean isFixedWidth(DateTimeParseContext context) {
2740             return subsequentWidth == -1 ||
2741                 (subsequentWidth > 0 && minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE);
2742         }
2743 
2744         @Override
2745         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2746             int length = text.length();
2747             if (position == length) {
2748                 return ~position;
2749             }
2750             char sign = text.charAt(position);  // IOOBE if invalid position
2751             boolean negative = false;
2752             boolean positive = false;
2753             if (sign == context.getDecimalStyle().getPositiveSign()) {
2754                 if (signStyle.parse(true, context.isStrict(), minWidth == maxWidth) == false) {
2755                     return ~position;
2756                 }
2757                 positive = true;
2758                 position++;
2759             } else if (sign == context.getDecimalStyle().getNegativeSign()) {
2760                 if (signStyle.parse(false, context.isStrict(), minWidth == maxWidth) == false) {
2761                     return ~position;
2762                 }
2763                 negative = true;
2764                 position++;
2765             } else {
2766                 if (signStyle == SignStyle.ALWAYS && context.isStrict()) {
2767                     return ~position;
2768                 }
2769             }
2770             int effMinWidth = (context.isStrict() || isFixedWidth(context) ? minWidth : 1);
2771             int minEndPos = position + effMinWidth;
2772             if (minEndPos > length) {
2773                 return ~position;
2774             }
2775             int effMaxWidth = (context.isStrict() || isFixedWidth(context) ? maxWidth : 9) + Math.max(subsequentWidth, 0);
2776             long total = 0;
2777             BigInteger totalBig = null;
2778             int pos = position;
2779             for (int pass = 0; pass < 2; pass++) {
2780                 int maxEndPos = Math.min(pos + effMaxWidth, length);
2781                 while (pos < maxEndPos) {
2782                     char ch = text.charAt(pos++);
2783                     int digit = context.getDecimalStyle().convertToDigit(ch);
2784                     if (digit < 0) {
2785                         pos--;
2786                         if (pos < minEndPos) {
2787                             return ~position;  // need at least min width digits
2788                         }
2789                         break;
2790                     }
2791                     if ((pos - position) > 18) {
2792                         if (totalBig == null) {
2793                             totalBig = BigInteger.valueOf(total);
2794                         }
2795                         totalBig = totalBig.multiply(BigInteger.TEN).add(BigInteger.valueOf(digit));
2796                     } else {
2797                         total = total * 10 + digit;
2798                     }
2799                 }
2800                 if (subsequentWidth > 0 && pass == 0) {
2801                     // re-parse now we know the correct width
2802                     int parseLen = pos - position;
2803                     effMaxWidth = Math.max(effMinWidth, parseLen - subsequentWidth);
2804                     pos = position;
2805                     total = 0;
2806                     totalBig = null;
2807                 } else {
2808                     break;
2809                 }
2810             }
2811             if (negative) {
2812                 if (totalBig != null) {
2813                     if (totalBig.equals(BigInteger.ZERO) && context.isStrict()) {
2814                         return ~(position - 1);  // minus zero not allowed
2815                     }
2816                     totalBig = totalBig.negate();
2817                 } else {
2818                     if (total == 0 && context.isStrict()) {
2819                         return ~(position - 1);  // minus zero not allowed
2820                     }
2821                     total = -total;
2822                 }
2823             } else if (signStyle == SignStyle.EXCEEDS_PAD && context.isStrict()) {
2824                 int parseLen = pos - position;
2825                 if (positive) {
2826                     if (parseLen <= minWidth) {
2827                         return ~(position - 1);  // '+' only parsed if minWidth exceeded
2828                     }
2829                 } else {
2830                     if (parseLen > minWidth) {
2831                         return ~position;  // '+' must be parsed if minWidth exceeded
2832                     }
2833                 }
2834             }
2835             if (totalBig != null) {
2836                 if (totalBig.bitLength() > 63) {
2837                     // overflow, parse 1 less digit
2838                     totalBig = totalBig.divide(BigInteger.TEN);
2839                     pos--;
2840                 }
2841                 return setValue(context, totalBig.longValue(), position, pos);
2842             }
2843             return setValue(context, total, position, pos);
2844         }
2845 
2846         /**
2847          * Stores the value.
2848          *
2849          * @param context  the context to store into, not null
2850          * @param value  the value
2851          * @param errorPos  the position of the field being parsed
2852          * @param successPos  the position after the field being parsed
2853          * @return the new position
2854          */
2855         int setValue(DateTimeParseContext context, long value, int errorPos, int successPos) {
2856             return context.setParsedField(field, value, errorPos, successPos);
2857         }
2858 
2859         @Override
2860         public String toString() {
2861             if (minWidth == 1 && maxWidth == 19 && signStyle == SignStyle.NORMAL) {
2862                 return "Value(" + field + ")";
2863             }
2864             if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) {
2865                 return "Value(" + field + "," + minWidth + ")";
2866             }
2867             return "Value(" + field + "," + minWidth + "," + maxWidth + "," + signStyle + ")";
2868         }
2869     }
2870 
2871     //-----------------------------------------------------------------------
2872     /**
2873      * Prints and parses a reduced numeric date-time field.
2874      */
2875     static final class ReducedPrinterParser extends NumberPrinterParser {
2876         /**
2877          * The base date for reduced value parsing.
2878          */
2879         static final LocalDate BASE_DATE = LocalDate.of(2000, 1, 1);
2880 
2881         private final int baseValue;
2882         private final ChronoLocalDate baseDate;
2883 
2884         /**
2885          * Constructor.
2886          *
2887          * @param field  the field to format, validated not null
2888          * @param minWidth  the minimum field width, from 1 to 10
2889          * @param maxWidth  the maximum field width, from 1 to 10
2890          * @param baseValue  the base value
2891          * @param baseDate  the base date
2892          */
2893         ReducedPrinterParser(TemporalField field, int minWidth, int maxWidth,
2894                 int baseValue, ChronoLocalDate baseDate) {
2895             this(field, minWidth, maxWidth, baseValue, baseDate, 0);
2896             if (minWidth < 1 || minWidth > 10) {
2897                 throw new IllegalArgumentException("The minWidth must be from 1 to 10 inclusive but was " + minWidth);
2898             }
2899             if (maxWidth < 1 || maxWidth > 10) {
2900                 throw new IllegalArgumentException("The maxWidth must be from 1 to 10 inclusive but was " + minWidth);
2901             }
2902             if (maxWidth < minWidth) {
2903                 throw new IllegalArgumentException("Maximum width must exceed or equal the minimum width but " +
2904                         maxWidth + " < " + minWidth);
2905             }
2906             if (baseDate == null) {
2907                 if (field.range().isValidValue(baseValue) == false) {
2908                     throw new IllegalArgumentException("The base value must be within the range of the field");
2909                 }
2910                 if ((((long) baseValue) + EXCEED_POINTS[maxWidth]) > Integer.MAX_VALUE) {
2911                     throw new DateTimeException("Unable to add printer-parser as the range exceeds the capacity of an int");
2912                 }
2913             }
2914         }
2915 
2916         /**
2917          * Constructor.
2918          * The arguments have already been checked.
2919          *
2920          * @param field  the field to format, validated not null
2921          * @param minWidth  the minimum field width, from 1 to 10
2922          * @param maxWidth  the maximum field width, from 1 to 10
2923          * @param baseValue  the base value
2924          * @param baseDate  the base date
2925          * @param subsequentWidth the subsequentWidth for this instance
2926          */
2927         private ReducedPrinterParser(TemporalField field, int minWidth, int maxWidth,
2928                 int baseValue, ChronoLocalDate baseDate, int subsequentWidth) {
2929             super(field, minWidth, maxWidth, SignStyle.NOT_NEGATIVE, subsequentWidth);
2930             this.baseValue = baseValue;
2931             this.baseDate = baseDate;
2932         }
2933 
2934         @Override
2935         long getValue(DateTimePrintContext context, long value) {
2936             long absValue = Math.abs(value);
2937             int baseValue = this.baseValue;
2938             if (baseDate != null) {
2939                 Chronology chrono = Chronology.from(context.getTemporal());
2940                 baseValue = chrono.date(baseDate).get(field);
2941             }
2942             if (value >= baseValue && value < baseValue + EXCEED_POINTS[minWidth]) {
2943                 // Use the reduced value if it fits in minWidth
2944                 return absValue % EXCEED_POINTS[minWidth];
2945             }
2946             // Otherwise truncate to fit in maxWidth
2947             return absValue % EXCEED_POINTS[maxWidth];
2948         }
2949 
2950         @Override
2951         int setValue(DateTimeParseContext context, long value, int errorPos, int successPos) {
2952             int baseValue = this.baseValue;
2953             if (baseDate != null) {
2954                 Chronology chrono = context.getEffectiveChronology();
2955                 baseValue = chrono.date(baseDate).get(field);
2956 
2957                 // In case the Chronology is changed later, add a callback when/if it changes
2958                 final long initialValue = value;
2959                 context.addChronoChangedListener(
2960                         (_unused) ->  {
2961                             /* Repeat the set of the field using the current Chronology
2962                              * The success/error position is ignored because the value is
2963                              * intentionally being overwritten.
2964                              */
2965                             setValue(context, initialValue, errorPos, successPos);
2966                         });
2967             }
2968             int parseLen = successPos - errorPos;
2969             if (parseLen == minWidth && value >= 0) {
2970                 long range = EXCEED_POINTS[minWidth];
2971                 long lastPart = baseValue % range;
2972                 long basePart = baseValue - lastPart;
2973                 if (baseValue > 0) {
2974                     value = basePart + value;
2975                 } else {
2976                     value = basePart - value;
2977                 }
2978                 if (value < baseValue) {
2979                     value += range;
2980                 }
2981             }
2982             return context.setParsedField(field, value, errorPos, successPos);
2983         }
2984 
2985         /**
2986          * Returns a new instance with fixed width flag set.
2987          *
2988          * @return a new updated printer-parser, not null
2989          */
2990         @Override
2991         ReducedPrinterParser withFixedWidth() {
2992             if (subsequentWidth == -1) {
2993                 return this;
2994             }
2995             return new ReducedPrinterParser(field, minWidth, maxWidth, baseValue, baseDate, -1);
2996         }
2997 
2998         /**
2999          * Returns a new instance with an updated subsequent width.
3000          *
3001          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater
3002          * @return a new updated printer-parser, not null
3003          */
3004         @Override
3005         ReducedPrinterParser withSubsequentWidth(int subsequentWidth) {
3006             return new ReducedPrinterParser(field, minWidth, maxWidth, baseValue, baseDate,
3007                     this.subsequentWidth + subsequentWidth);
3008         }
3009 
3010         /**
3011          * For a ReducedPrinterParser, fixed width is false if the mode is strict,
3012          * otherwise it is set as for NumberPrinterParser.
3013          * @param context the context
3014          * @return if the field is fixed width
3015          * @see DateTimeFormatterBuilder#appendValueReduced(java.time.temporal.TemporalField, int, int, int)
3016          */
3017         @Override
3018         boolean isFixedWidth(DateTimeParseContext context) {
3019            if (context.isStrict() == false) {
3020                return false;
3021            }
3022            return super.isFixedWidth(context);
3023         }
3024 
3025         @Override
3026         public String toString() {
3027             return "ReducedValue(" + field + "," + minWidth + "," + maxWidth +
3028                     "," + Objects.requireNonNullElse(baseDate, baseValue) + ")";
3029         }
3030     }
3031 
3032     //-----------------------------------------------------------------------
3033     /**
3034      * Prints and parses a numeric date-time field with optional padding.
3035      */
3036     static final class FractionPrinterParser extends NumberPrinterParser {
3037        private final boolean decimalPoint;
3038 
3039         /**
3040          * Constructor.
3041          *
3042          * @param field  the field to output, not null
3043          * @param minWidth  the minimum width to output, from 0 to 9
3044          * @param maxWidth  the maximum width to output, from 0 to 9
3045          * @param decimalPoint  whether to output the localized decimal point symbol
3046          */
3047         FractionPrinterParser(TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) {
3048             this(field, minWidth, maxWidth, decimalPoint, 0);
3049             Objects.requireNonNull(field, "field");
3050             if (field.range().isFixed() == false) {
3051                 throw new IllegalArgumentException("Field must have a fixed set of values: " + field);
3052             }
3053             if (minWidth < 0 || minWidth > 9) {
3054                 throw new IllegalArgumentException("Minimum width must be from 0 to 9 inclusive but was " + minWidth);
3055             }
3056             if (maxWidth < 1 || maxWidth > 9) {
3057                 throw new IllegalArgumentException("Maximum width must be from 1 to 9 inclusive but was " + maxWidth);
3058             }
3059             if (maxWidth < minWidth) {
3060                 throw new IllegalArgumentException("Maximum width must exceed or equal the minimum width but " +
3061                         maxWidth + " < " + minWidth);
3062             }
3063         }
3064 
3065         /**
3066          * Constructor.
3067          *
3068          * @param field  the field to output, not null
3069          * @param minWidth  the minimum width to output, from 0 to 9
3070          * @param maxWidth  the maximum width to output, from 0 to 9
3071          * @param decimalPoint  whether to output the localized decimal point symbol
3072          * @param subsequentWidth the subsequentWidth for this instance
3073          */
3074         FractionPrinterParser(TemporalField field, int minWidth, int maxWidth, boolean decimalPoint, int subsequentWidth) {
3075             super(field, minWidth, maxWidth, SignStyle.NOT_NEGATIVE, subsequentWidth);
3076             this.decimalPoint = decimalPoint;
3077         }
3078 
3079         /**
3080          * Returns a new instance with fixed width flag set.
3081          *
3082          * @return a new updated printer-parser, not null
3083          */
3084         @Override
3085         FractionPrinterParser withFixedWidth() {
3086             if (subsequentWidth == -1) {
3087                 return this;
3088             }
3089             return new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint, -1);
3090         }
3091 
3092         /**
3093          * Returns a new instance with an updated subsequent width.
3094          *
3095          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater
3096          * @return a new updated printer-parser, not null
3097          */
3098         @Override
3099         FractionPrinterParser withSubsequentWidth(int subsequentWidth) {
3100             return new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint, this.subsequentWidth + subsequentWidth);
3101         }
3102 
3103         /**
3104          * For FractionPrinterPrinterParser, the width is fixed if context is sttrict,
3105          * minWidth equal to maxWidth and decimalpoint is absent.
3106          * @param context the context
3107          * @return if the field is fixed width
3108          * @see DateTimeFormatterBuilder#appendValueFraction(java.time.temporal.TemporalField, int, int, boolean)
3109          */
3110         @Override
3111         boolean isFixedWidth(DateTimeParseContext context) {
3112             if (context.isStrict() && minWidth == maxWidth && decimalPoint == false) {
3113                 return true;
3114             }
3115             return false;
3116         }
3117 
3118         @Override
3119         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3120             Long value = context.getValue(field);
3121             if (value == null) {
3122                 return false;
3123             }
3124             DecimalStyle decimalStyle = context.getDecimalStyle();
3125             BigDecimal fraction = convertToFraction(value);
3126             if (fraction.scale() == 0) {  // scale is zero if value is zero
3127                 if (minWidth > 0) {
3128                     if (decimalPoint) {
3129                         buf.append(decimalStyle.getDecimalSeparator());
3130                     }
3131                     for (int i = 0; i < minWidth; i++) {
3132                         buf.append(decimalStyle.getZeroDigit());
3133                     }
3134                 }
3135             } else {
3136                 int outputScale = Math.min(Math.max(fraction.scale(), minWidth), maxWidth);
3137                 fraction = fraction.setScale(outputScale, RoundingMode.FLOOR);
3138                 String str = fraction.toPlainString().substring(2);
3139                 str = decimalStyle.convertNumberToI18N(str);
3140                 if (decimalPoint) {
3141                     buf.append(decimalStyle.getDecimalSeparator());
3142                 }
3143                 buf.append(str);
3144             }
3145             return true;
3146         }
3147 
3148         @Override
3149         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3150             int effectiveMin = (context.isStrict() || isFixedWidth(context) ? minWidth : 0);
3151             int effectiveMax = (context.isStrict() || isFixedWidth(context) ? maxWidth : 9);
3152             int length = text.length();
3153             if (position == length) {
3154                 // valid if whole field is optional, invalid if minimum width
3155                 return (effectiveMin > 0 ? ~position : position);
3156             }
3157             if (decimalPoint) {
3158                 if (text.charAt(position) != context.getDecimalStyle().getDecimalSeparator()) {
3159                     // valid if whole field is optional, invalid if minimum width
3160                     return (effectiveMin > 0 ? ~position : position);
3161                 }
3162                 position++;
3163             }
3164             int minEndPos = position + effectiveMin;
3165             if (minEndPos > length) {
3166                 return ~position;  // need at least min width digits
3167             }
3168             int maxEndPos = Math.min(position + effectiveMax, length);
3169             int total = 0;  // can use int because we are only parsing up to 9 digits
3170             int pos = position;
3171             while (pos < maxEndPos) {
3172                 char ch = text.charAt(pos++);
3173                 int digit = context.getDecimalStyle().convertToDigit(ch);
3174                 if (digit < 0) {
3175                     if (pos < minEndPos) {
3176                         return ~position;  // need at least min width digits
3177                     }
3178                     pos--;
3179                     break;
3180                 }
3181                 total = total * 10 + digit;
3182             }
3183             BigDecimal fraction = new BigDecimal(total).movePointLeft(pos - position);
3184             long value = convertFromFraction(fraction);
3185             return context.setParsedField(field, value, position, pos);
3186         }
3187 
3188         /**
3189          * Converts a value for this field to a fraction between 0 and 1.
3190          * <p>
3191          * The fractional value is between 0 (inclusive) and 1 (exclusive).
3192          * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
3193          * The fraction is obtained by calculation from the field range using 9 decimal
3194          * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
3195          * The calculation is inaccurate if the values do not run continuously from smallest to largest.
3196          * <p>
3197          * For example, the second-of-minute value of 15 would be returned as 0.25,
3198          * assuming the standard definition of 60 seconds in a minute.
3199          *
3200          * @param value  the value to convert, must be valid for this rule
3201          * @return the value as a fraction within the range, from 0 to 1, not null
3202          * @throws DateTimeException if the value cannot be converted to a fraction
3203          */
3204         private BigDecimal convertToFraction(long value) {
3205             ValueRange range = field.range();
3206             range.checkValidValue(value, field);
3207             BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
3208             BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
3209             BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD);
3210             BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR);
3211             // stripTrailingZeros bug
3212             return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros();
3213         }
3214 
3215         /**
3216          * Converts a fraction from 0 to 1 for this field to a value.
3217          * <p>
3218          * The fractional value must be between 0 (inclusive) and 1 (exclusive).
3219          * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
3220          * The value is obtained by calculation from the field range and a rounding
3221          * mode of {@link RoundingMode#FLOOR FLOOR}.
3222          * The calculation is inaccurate if the values do not run continuously from smallest to largest.
3223          * <p>
3224          * For example, the fractional second-of-minute of 0.25 would be converted to 15,
3225          * assuming the standard definition of 60 seconds in a minute.
3226          *
3227          * @param fraction  the fraction to convert, not null
3228          * @return the value of the field, valid for this rule
3229          * @throws DateTimeException if the value cannot be converted
3230          */
3231         private long convertFromFraction(BigDecimal fraction) {
3232             ValueRange range = field.range();
3233             BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
3234             BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
3235             BigDecimal valueBD = fraction.multiply(rangeBD).setScale(0, RoundingMode.FLOOR).add(minBD);
3236             return valueBD.longValueExact();
3237         }
3238 
3239         @Override
3240         public String toString() {
3241             String decimal = (decimalPoint ? ",DecimalPoint" : "");
3242             return "Fraction(" + field + "," + minWidth + "," + maxWidth + decimal + ")";
3243         }
3244     }
3245 
3246     //-----------------------------------------------------------------------
3247     /**
3248      * Prints or parses field text.
3249      */
3250     static final class TextPrinterParser implements DateTimePrinterParser {
3251         private final TemporalField field;
3252         private final TextStyle textStyle;
3253         private final DateTimeTextProvider provider;
3254         /**
3255          * The cached number printer parser.
3256          * Immutable and volatile, so no synchronization needed.
3257          */
3258         private volatile NumberPrinterParser numberPrinterParser;
3259 
3260         /**
3261          * Constructor.
3262          *
3263          * @param field  the field to output, not null
3264          * @param textStyle  the text style, not null
3265          * @param provider  the text provider, not null
3266          */
3267         TextPrinterParser(TemporalField field, TextStyle textStyle, DateTimeTextProvider provider) {
3268             // validated by caller
3269             this.field = field;
3270             this.textStyle = textStyle;
3271             this.provider = provider;
3272         }
3273 
3274         @Override
3275         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3276             Long value = context.getValue(field);
3277             if (value == null) {
3278                 return false;
3279             }
3280             String text;
3281             Chronology chrono = context.getTemporal().query(TemporalQueries.chronology());
3282             if (chrono == null || chrono == IsoChronology.INSTANCE) {
3283                 text = provider.getText(field, value, textStyle, context.getLocale());
3284             } else {
3285                 text = provider.getText(chrono, field, value, textStyle, context.getLocale());
3286             }
3287             if (text == null) {
3288                 return numberPrinterParser().format(context, buf);
3289             }
3290             buf.append(text);
3291             return true;
3292         }
3293 
3294         @Override
3295         public int parse(DateTimeParseContext context, CharSequence parseText, int position) {
3296             int length = parseText.length();
3297             if (position < 0 || position > length) {
3298                 throw new IndexOutOfBoundsException();
3299             }
3300             TextStyle style = (context.isStrict() ? textStyle : null);
3301             Chronology chrono = context.getEffectiveChronology();
3302             Iterator<Entry<String, Long>> it;
3303             if (chrono == null || chrono == IsoChronology.INSTANCE) {
3304                 it = provider.getTextIterator(field, style, context.getLocale());
3305             } else {
3306                 it = provider.getTextIterator(chrono, field, style, context.getLocale());
3307             }
3308             if (it != null) {
3309                 while (it.hasNext()) {
3310                     Entry<String, Long> entry = it.next();
3311                     String itText = entry.getKey();
3312                     if (context.subSequenceEquals(itText, 0, parseText, position, itText.length())) {
3313                         return context.setParsedField(field, entry.getValue(), position, position + itText.length());
3314                     }
3315                 }
3316                 if (field == ERA && !context.isStrict()) {
3317                     // parse the possible era name from era.toString()
3318                     List<Era> eras = chrono.eras();
3319                     for (Era era : eras) {
3320                         String name = era.toString();
3321                         if (context.subSequenceEquals(name, 0, parseText, position, name.length())) {
3322                             return context.setParsedField(field, era.getValue(), position, position + name.length());
3323                         }
3324                     }
3325                 }
3326                 if (context.isStrict()) {
3327                     return ~position;
3328                 }
3329             }
3330             return numberPrinterParser().parse(context, parseText, position);
3331         }
3332 
3333         /**
3334          * Create and cache a number printer parser.
3335          * @return the number printer parser for this field, not null
3336          */
3337         private NumberPrinterParser numberPrinterParser() {
3338             if (numberPrinterParser == null) {
3339                 numberPrinterParser = new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL);
3340             }
3341             return numberPrinterParser;
3342         }
3343 
3344         @Override
3345         public String toString() {
3346             if (textStyle == TextStyle.FULL) {
3347                 return "Text(" + field + ")";
3348             }
3349             return "Text(" + field + "," + textStyle + ")";
3350         }
3351     }
3352 
3353     //-----------------------------------------------------------------------
3354     /**
3355      * Prints or parses an ISO-8601 instant.
3356      */
3357     static final class InstantPrinterParser implements DateTimePrinterParser {
3358         // days in a 400 year cycle = 146097
3359         // days in a 10,000 year cycle = 146097 * 25
3360         // seconds per day = 86400
3361         private static final long SECONDS_PER_10000_YEARS = 146097L * 25L * 86400L;
3362         private static final long SECONDS_0000_TO_1970 = ((146097L * 5L) - (30L * 365L + 7L)) * 86400L;
3363         private final int fractionalDigits;
3364 
3365         InstantPrinterParser(int fractionalDigits) {
3366             this.fractionalDigits = fractionalDigits;
3367         }
3368 
3369         @Override
3370         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3371             // use INSTANT_SECONDS, thus this code is not bound by Instant.MAX
3372             Long inSecs = context.getValue(INSTANT_SECONDS);
3373             Long inNanos = null;
3374             if (context.getTemporal().isSupported(NANO_OF_SECOND)) {
3375                 inNanos = context.getTemporal().getLong(NANO_OF_SECOND);
3376             }
3377             if (inSecs == null) {
3378                 return false;
3379             }
3380             long inSec = inSecs;
3381             int inNano = NANO_OF_SECOND.checkValidIntValue(inNanos != null ? inNanos : 0);
3382             // format mostly using LocalDateTime.toString
3383             if (inSec >= -SECONDS_0000_TO_1970) {
3384                 // current era
3385                 long zeroSecs = inSec - SECONDS_PER_10000_YEARS + SECONDS_0000_TO_1970;
3386                 long hi = Math.floorDiv(zeroSecs, SECONDS_PER_10000_YEARS) + 1;
3387                 long lo = Math.floorMod(zeroSecs, SECONDS_PER_10000_YEARS);
3388                 LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC);
3389                 if (hi > 0) {
3390                     buf.append('+').append(hi);
3391                 }
3392                 buf.append(ldt);
3393                 if (ldt.getSecond() == 0) {
3394                     buf.append(":00");
3395                 }
3396             } else {
3397                 // before current era
3398                 long zeroSecs = inSec + SECONDS_0000_TO_1970;
3399                 long hi = zeroSecs / SECONDS_PER_10000_YEARS;
3400                 long lo = zeroSecs % SECONDS_PER_10000_YEARS;
3401                 LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC);
3402                 int pos = buf.length();
3403                 buf.append(ldt);
3404                 if (ldt.getSecond() == 0) {
3405                     buf.append(":00");
3406                 }
3407                 if (hi < 0) {
3408                     if (ldt.getYear() == -10_000) {
3409                         buf.replace(pos, pos + 2, Long.toString(hi - 1));
3410                     } else if (lo == 0) {
3411                         buf.insert(pos, hi);
3412                     } else {
3413                         buf.insert(pos + 1, Math.abs(hi));
3414                     }
3415                 }
3416             }
3417             // add fraction
3418             if ((fractionalDigits < 0 && inNano > 0) || fractionalDigits > 0) {
3419                 buf.append('.');
3420                 int div = 100_000_000;
3421                 for (int i = 0; ((fractionalDigits == -1 && inNano > 0) ||
3422                                     (fractionalDigits == -2 && (inNano > 0 || (i % 3) != 0)) ||
3423                                     i < fractionalDigits); i++) {
3424                     int digit = inNano / div;
3425                     buf.append((char) (digit + '0'));
3426                     inNano = inNano - (digit * div);
3427                     div = div / 10;
3428                 }
3429             }
3430             buf.append('Z');
3431             return true;
3432         }
3433 
3434         @Override
3435         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3436             // new context to avoid overwriting fields like year/month/day
3437             int minDigits = (fractionalDigits < 0 ? 0 : fractionalDigits);
3438             int maxDigits = (fractionalDigits < 0 ? 9 : fractionalDigits);
3439             CompositePrinterParser parser = new DateTimeFormatterBuilder()
3440                     .append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T')
3441                     .appendValue(HOUR_OF_DAY, 2).appendLiteral(':')
3442                     .appendValue(MINUTE_OF_HOUR, 2).appendLiteral(':')
3443                     .appendValue(SECOND_OF_MINUTE, 2)
3444                     .appendFraction(NANO_OF_SECOND, minDigits, maxDigits, true)
3445                     .appendLiteral('Z')
3446                     .toFormatter().toPrinterParser(false);
3447             DateTimeParseContext newContext = context.copy();
3448             int pos = parser.parse(newContext, text, position);
3449             if (pos < 0) {
3450                 return pos;
3451             }
3452             // parser restricts most fields to 2 digits, so definitely int
3453             // correctly parsed nano is also guaranteed to be valid
3454             long yearParsed = newContext.getParsed(YEAR);
3455             int month = newContext.getParsed(MONTH_OF_YEAR).intValue();
3456             int day = newContext.getParsed(DAY_OF_MONTH).intValue();
3457             int hour = newContext.getParsed(HOUR_OF_DAY).intValue();
3458             int min = newContext.getParsed(MINUTE_OF_HOUR).intValue();
3459             Long secVal = newContext.getParsed(SECOND_OF_MINUTE);
3460             Long nanoVal = newContext.getParsed(NANO_OF_SECOND);
3461             int sec = (secVal != null ? secVal.intValue() : 0);
3462             int nano = (nanoVal != null ? nanoVal.intValue() : 0);
3463             int days = 0;
3464             if (hour == 24 && min == 0 && sec == 0 && nano == 0) {
3465                 hour = 0;
3466                 days = 1;
3467             } else if (hour == 23 && min == 59 && sec == 60) {
3468                 context.setParsedLeapSecond();
3469                 sec = 59;
3470             }
3471             int year = (int) yearParsed % 10_000;
3472             long instantSecs;
3473             try {
3474                 LocalDateTime ldt = LocalDateTime.of(year, month, day, hour, min, sec, 0).plusDays(days);
3475                 instantSecs = ldt.toEpochSecond(ZoneOffset.UTC);
3476                 instantSecs += Math.multiplyExact(yearParsed / 10_000L, SECONDS_PER_10000_YEARS);
3477             } catch (RuntimeException ex) {
3478                 return ~position;
3479             }
3480             int successPos = pos;
3481             successPos = context.setParsedField(INSTANT_SECONDS, instantSecs, position, successPos);
3482             return context.setParsedField(NANO_OF_SECOND, nano, position, successPos);
3483         }
3484 
3485         @Override
3486         public String toString() {
3487             return "Instant()";
3488         }
3489     }
3490 
3491     //-----------------------------------------------------------------------
3492     /**
3493      * Prints or parses an offset ID.
3494      */
3495     static final class OffsetIdPrinterParser implements DateTimePrinterParser {
3496         static final String[] PATTERNS = new String[] {
3497                 "+HH", "+HHmm", "+HH:mm", "+HHMM", "+HH:MM", "+HHMMss", "+HH:MM:ss", "+HHMMSS", "+HH:MM:SS", "+HHmmss", "+HH:mm:ss",
3498                 "+H",  "+Hmm",  "+H:mm",  "+HMM",  "+H:MM",  "+HMMss",  "+H:MM:ss",  "+HMMSS",  "+H:MM:SS",  "+Hmmss",  "+H:mm:ss",
3499         };  // order used in pattern builder
3500         static final OffsetIdPrinterParser INSTANCE_ID_Z = new OffsetIdPrinterParser("+HH:MM:ss", "Z");
3501         static final OffsetIdPrinterParser INSTANCE_ID_ZERO = new OffsetIdPrinterParser("+HH:MM:ss", "0");
3502 
3503         private final String noOffsetText;
3504         private final int type;
3505         private final int style;
3506 
3507         /**
3508          * Constructor.
3509          *
3510          * @param pattern  the pattern
3511          * @param noOffsetText  the text to use for UTC, not null
3512          */
3513         OffsetIdPrinterParser(String pattern, String noOffsetText) {
3514             Objects.requireNonNull(pattern, "pattern");
3515             Objects.requireNonNull(noOffsetText, "noOffsetText");
3516             this.type = checkPattern(pattern);
3517             this.style = type % 11;
3518             this.noOffsetText = noOffsetText;
3519         }
3520 
3521         private int checkPattern(String pattern) {
3522             for (int i = 0; i < PATTERNS.length; i++) {
3523                 if (PATTERNS[i].equals(pattern)) {
3524                     return i;
3525                 }
3526             }
3527             throw new IllegalArgumentException("Invalid zone offset pattern: " + pattern);
3528         }
3529 
3530         private boolean isPaddedHour() {
3531             return type < 11;
3532         }
3533 
3534         private boolean isColon() {
3535             return style > 0 && (style % 2) == 0;
3536         }
3537 
3538         @Override
3539         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3540             Long offsetSecs = context.getValue(OFFSET_SECONDS);
3541             if (offsetSecs == null) {
3542                 return false;
3543             }
3544             int totalSecs = Math.toIntExact(offsetSecs);
3545             if (totalSecs == 0) {
3546                 buf.append(noOffsetText);
3547             } else {
3548                 int absHours = Math.abs((totalSecs / 3600) % 100);  // anything larger than 99 silently dropped
3549                 int absMinutes = Math.abs((totalSecs / 60) % 60);
3550                 int absSeconds = Math.abs(totalSecs % 60);
3551                 int bufPos = buf.length();
3552                 int output = absHours;
3553                 buf.append(totalSecs < 0 ? "-" : "+");
3554                 if (isPaddedHour() || absHours >= 10) {
3555                     formatZeroPad(false, absHours, buf);
3556                 } else {
3557                     buf.append((char) (absHours + '0'));
3558                 }
3559                 if ((style >= 3 && style <= 8) || (style >= 9 && absSeconds > 0) || (style >= 1 && absMinutes > 0)) {
3560                     formatZeroPad(isColon(), absMinutes, buf);
3561                     output += absMinutes;
3562                     if (style == 7 || style == 8 || (style >= 5 && absSeconds > 0)) {
3563                         formatZeroPad(isColon(), absSeconds, buf);
3564                         output += absSeconds;
3565                     }
3566                 }
3567                 if (output == 0) {
3568                     buf.setLength(bufPos);
3569                     buf.append(noOffsetText);
3570                 }
3571             }
3572             return true;
3573         }
3574 
3575         private void formatZeroPad(boolean colon, int value, StringBuilder buf) {
3576             buf.append(colon ? ":" : "")
3577                     .append((char) (value / 10 + '0'))
3578                     .append((char) (value % 10 + '0'));
3579         }
3580 
3581         @Override
3582         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3583             int length = text.length();
3584             int noOffsetLen = noOffsetText.length();
3585             if (noOffsetLen == 0) {
3586                 if (position == length) {
3587                     return context.setParsedField(OFFSET_SECONDS, 0, position, position);
3588                 }
3589             } else {
3590                 if (position == length) {
3591                     return ~position;
3592                 }
3593                 if (context.subSequenceEquals(text, position, noOffsetText, 0, noOffsetLen)) {
3594                     return context.setParsedField(OFFSET_SECONDS, 0, position, position + noOffsetLen);
3595                 }
3596             }
3597 
3598             // parse normal plus/minus offset
3599             char sign = text.charAt(position);  // IOOBE if invalid position
3600             if (sign == '+' || sign == '-') {
3601                 // starts
3602                 int negative = (sign == '-' ? -1 : 1);
3603                 boolean isColon = isColon();
3604                 boolean paddedHour = isPaddedHour();
3605                 int[] array = new int[4];
3606                 array[0] = position + 1;
3607                 int parseType = type;
3608                 // select parse type when lenient
3609                 if (!context.isStrict()) {
3610                     if (paddedHour) {
3611                         if (isColon || (parseType == 0 && length > position + 3 && text.charAt(position + 3) == ':')) {
3612                             isColon = true; // needed in cases like ("+HH", "+01:01")
3613                             parseType = 10;
3614                         } else {
3615                             parseType = 9;
3616                         }
3617                     } else {
3618                         if (isColon || (parseType == 11 && length > position + 3 && (text.charAt(position + 2) == ':' || text.charAt(position + 3) == ':'))) {
3619                             isColon = true;
3620                             parseType = 21;  // needed in cases like ("+H", "+1:01")
3621                         } else {
3622                             parseType = 20;
3623                         }
3624                     }
3625                 }
3626                 // parse according to the selected pattern
3627                 switch (parseType) {
3628                     case 0: // +HH
3629                     case 11: // +H
3630                         parseHour(text, paddedHour, array);
3631                         break;
3632                     case 1: // +HHmm
3633                     case 2: // +HH:mm
3634                     case 13: // +H:mm
3635                         parseHour(text, paddedHour, array);
3636                         parseMinute(text, isColon, false, array);
3637                         break;
3638                     case 3: // +HHMM
3639                     case 4: // +HH:MM
3640                     case 15: // +H:MM
3641                         parseHour(text, paddedHour, array);
3642                         parseMinute(text, isColon, true, array);
3643                         break;
3644                     case 5: // +HHMMss
3645                     case 6: // +HH:MM:ss
3646                     case 17: // +H:MM:ss
3647                         parseHour(text, paddedHour, array);
3648                         parseMinute(text, isColon, true, array);
3649                         parseSecond(text, isColon, false, array);
3650                         break;
3651                     case 7: // +HHMMSS
3652                     case 8: // +HH:MM:SS
3653                     case 19: // +H:MM:SS
3654                         parseHour(text, paddedHour, array);
3655                         parseMinute(text, isColon, true, array);
3656                         parseSecond(text, isColon, true, array);
3657                         break;
3658                     case 9: // +HHmmss
3659                     case 10: // +HH:mm:ss
3660                     case 21: // +H:mm:ss
3661                         parseHour(text, paddedHour, array);
3662                         parseOptionalMinuteSecond(text, isColon, array);
3663                         break;
3664                     case 12: // +Hmm
3665                         parseVariableWidthDigits(text, 1, 4, array);
3666                         break;
3667                     case 14: // +HMM
3668                         parseVariableWidthDigits(text, 3, 4, array);
3669                         break;
3670                     case 16: // +HMMss
3671                         parseVariableWidthDigits(text, 3, 6, array);
3672                         break;
3673                     case 18: // +HMMSS
3674                         parseVariableWidthDigits(text, 5, 6, array);
3675                         break;
3676                     case 20: // +Hmmss
3677                         parseVariableWidthDigits(text, 1, 6, array);
3678                         break;
3679                 }
3680                 if (array[0] > 0) {
3681                     if (array[1] > 23 || array[2] > 59 || array[3] > 59) {
3682                         throw new DateTimeException("Value out of range: Hour[0-23], Minute[0-59], Second[0-59]");
3683                     }
3684                     long offsetSecs = negative * (array[1] * 3600L + array[2] * 60L + array[3]);
3685                     return context.setParsedField(OFFSET_SECONDS, offsetSecs, position, array[0]);
3686                 }
3687             }
3688             // handle special case of empty no offset text
3689             if (noOffsetLen == 0) {
3690                 return context.setParsedField(OFFSET_SECONDS, 0, position, position);
3691             }
3692             return ~position;
3693         }
3694 
3695         private void parseHour(CharSequence parseText, boolean paddedHour, int[] array) {
3696             if (paddedHour) {
3697                 // parse two digits
3698                 if (!parseDigits(parseText, false, 1, array)) {
3699                     array[0] = ~array[0];
3700                 }
3701             } else {
3702                 // parse one or two digits
3703                 parseVariableWidthDigits(parseText, 1, 2, array);
3704             }
3705         }
3706 
3707         private void parseMinute(CharSequence parseText, boolean isColon, boolean mandatory, int[] array) {
3708             if (!parseDigits(parseText, isColon, 2, array)) {
3709                 if (mandatory) {
3710                     array[0] = ~array[0];
3711                 }
3712             }
3713         }
3714 
3715         private void parseSecond(CharSequence parseText, boolean isColon, boolean mandatory, int[] array) {
3716             if (!parseDigits(parseText, isColon, 3, array)) {
3717                 if (mandatory) {
3718                     array[0] = ~array[0];
3719                 }
3720             }
3721         }
3722 
3723         private void parseOptionalMinuteSecond(CharSequence parseText, boolean isColon, int[] array) {
3724             if (parseDigits(parseText, isColon, 2, array)) {
3725                 parseDigits(parseText, isColon, 3, array);
3726             }
3727         }
3728 
3729         private boolean parseDigits(CharSequence parseText, boolean isColon, int arrayIndex, int[] array) {
3730             int pos = array[0];
3731             if (pos < 0) {
3732                 return true;
3733             }
3734             if (isColon && arrayIndex != 1) { //  ':' will precede only in case of minute/second
3735                 if (pos + 1 > parseText.length() || parseText.charAt(pos) != ':') {
3736                     return false;
3737                 }
3738                 pos++;
3739             }
3740             if (pos + 2 > parseText.length()) {
3741                 return false;
3742             }
3743             char ch1 = parseText.charAt(pos++);
3744             char ch2 = parseText.charAt(pos++);
3745             if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') {
3746                 return false;
3747             }
3748             int value = (ch1 - 48) * 10 + (ch2 - 48);
3749             if (value < 0 || value > 59) {
3750                 return false;
3751             }
3752             array[arrayIndex] = value;
3753             array[0] = pos;
3754             return true;
3755         }
3756 
3757         private void parseVariableWidthDigits(CharSequence parseText, int minDigits, int maxDigits, int[] array) {
3758             // scan the text to find the available number of digits up to maxDigits
3759             // so long as the number available is minDigits or more, the input is valid
3760             // then parse the number of available digits
3761             int pos = array[0];
3762             int available = 0;
3763             char[] chars = new char[maxDigits];
3764             for (int i = 0; i < maxDigits; i++) {
3765                 if (pos + 1  > parseText.length()) {
3766                     break;
3767                 }
3768                 char ch = parseText.charAt(pos++);
3769                 if (ch < '0' || ch > '9') {
3770                     pos--;
3771                     break;
3772                 }
3773                 chars[i] = ch;
3774                 available++;
3775             }
3776             if (available < minDigits) {
3777                 array[0] = ~array[0];
3778                 return;
3779             }
3780             switch (available) {
3781                 case 1:
3782                     array[1] = (chars[0] - 48);
3783                     break;
3784                 case 2:
3785                     array[1] = ((chars[0] - 48) * 10 + (chars[1] - 48));
3786                     break;
3787                 case 3:
3788                     array[1] = (chars[0] - 48);
3789                     array[2] = ((chars[1] - 48) * 10 + (chars[2] - 48));
3790                     break;
3791                 case 4:
3792                     array[1] = ((chars[0] - 48) * 10 + (chars[1] - 48));
3793                     array[2] = ((chars[2] - 48) * 10 + (chars[3] - 48));
3794                     break;
3795                 case 5:
3796                     array[1] = (chars[0] - 48);
3797                     array[2] = ((chars[1] - 48) * 10 + (chars[2] - 48));
3798                     array[3] = ((chars[3] - 48) * 10 + (chars[4] - 48));
3799                     break;
3800                 case 6:
3801                     array[1] = ((chars[0] - 48) * 10 + (chars[1] - 48));
3802                     array[2] = ((chars[2] - 48) * 10 + (chars[3] - 48));
3803                     array[3] = ((chars[4] - 48) * 10 + (chars[5] - 48));
3804                     break;
3805             }
3806             array[0] = pos;
3807         }
3808 
3809         @Override
3810         public String toString() {
3811             String converted = noOffsetText.replace("'", "''");
3812             return "Offset(" + PATTERNS[type] + ",'" + converted + "')";
3813         }
3814     }
3815 
3816     //-----------------------------------------------------------------------
3817     /**
3818      * Prints or parses an offset ID.
3819      */
3820     static final class LocalizedOffsetIdPrinterParser implements DateTimePrinterParser {
3821         private final TextStyle style;
3822 
3823         /**
3824          * Constructor.
3825          *
3826          * @param style  the style, not null
3827          */
3828         LocalizedOffsetIdPrinterParser(TextStyle style) {
3829             this.style = style;
3830         }
3831 
3832         private static StringBuilder appendHMS(StringBuilder buf, int t) {
3833             return buf.append((char)(t / 10 + '0'))
3834                       .append((char)(t % 10 + '0'));
3835         }
3836 
3837         @Override
3838         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3839             Long offsetSecs = context.getValue(OFFSET_SECONDS);
3840             if (offsetSecs == null) {
3841                 return false;
3842             }
3843             String gmtText = "GMT";  // TODO: get localized version of 'GMT'
3844             buf.append(gmtText);
3845             int totalSecs = Math.toIntExact(offsetSecs);
3846             if (totalSecs != 0) {
3847                 int absHours = Math.abs((totalSecs / 3600) % 100);  // anything larger than 99 silently dropped
3848                 int absMinutes = Math.abs((totalSecs / 60) % 60);
3849                 int absSeconds = Math.abs(totalSecs % 60);
3850                 buf.append(totalSecs < 0 ? "-" : "+");
3851                 if (style == TextStyle.FULL) {
3852                     appendHMS(buf, absHours);
3853                     buf.append(':');
3854                     appendHMS(buf, absMinutes);
3855                     if (absSeconds != 0) {
3856                        buf.append(':');
3857                        appendHMS(buf, absSeconds);
3858                     }
3859                 } else {
3860                     if (absHours >= 10) {
3861                         buf.append((char)(absHours / 10 + '0'));
3862                     }
3863                     buf.append((char)(absHours % 10 + '0'));
3864                     if (absMinutes != 0 || absSeconds != 0) {
3865                         buf.append(':');
3866                         appendHMS(buf, absMinutes);
3867                         if (absSeconds != 0) {
3868                             buf.append(':');
3869                             appendHMS(buf, absSeconds);
3870                         }
3871                     }
3872                 }
3873             }
3874             return true;
3875         }
3876 
3877         int getDigit(CharSequence text, int position) {
3878             char c = text.charAt(position);
3879             if (c < '0' || c > '9') {
3880                 return -1;
3881             }
3882             return c - '0';
3883         }
3884 
3885         @Override
3886         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3887             int pos = position;
3888             int end = text.length();
3889             String gmtText = "GMT";  // TODO: get localized version of 'GMT'
3890             if (!context.subSequenceEquals(text, pos, gmtText, 0, gmtText.length())) {
3891                     return ~position;
3892                 }
3893             pos += gmtText.length();
3894             // parse normal plus/minus offset
3895             int negative = 0;
3896             if (pos == end) {
3897                 return context.setParsedField(OFFSET_SECONDS, 0, position, pos);
3898             }
3899             char sign = text.charAt(pos);  // IOOBE if invalid position
3900             if (sign == '+') {
3901                 negative = 1;
3902             } else if (sign == '-') {
3903                 negative = -1;
3904             } else {
3905                 return context.setParsedField(OFFSET_SECONDS, 0, position, pos);
3906             }
3907             pos++;
3908             int h = 0;
3909             int m = 0;
3910             int s = 0;
3911             if (style == TextStyle.FULL) {
3912                 int h1 = getDigit(text, pos++);
3913                 int h2 = getDigit(text, pos++);
3914                 if (h1 < 0 || h2 < 0 || text.charAt(pos++) != ':') {
3915                     return ~position;
3916                 }
3917                 h = h1 * 10 + h2;
3918                 int m1 = getDigit(text, pos++);
3919                 int m2 = getDigit(text, pos++);
3920                 if (m1 < 0 || m2 < 0) {
3921                     return ~position;
3922                 }
3923                 m = m1 * 10 + m2;
3924                 if (pos + 2 < end && text.charAt(pos) == ':') {
3925                     int s1 = getDigit(text, pos + 1);
3926                     int s2 = getDigit(text, pos + 2);
3927                     if (s1 >= 0 && s2 >= 0) {
3928                         s = s1 * 10 + s2;
3929                         pos += 3;
3930                     }
3931                 }
3932             } else {
3933                 h = getDigit(text, pos++);
3934                 if (h < 0) {
3935                     return ~position;
3936                 }
3937                 if (pos < end) {
3938                     int h2 = getDigit(text, pos);
3939                     if (h2 >=0) {
3940                         h = h * 10 + h2;
3941                         pos++;
3942                     }
3943                     if (pos + 2 < end && text.charAt(pos) == ':') {
3944                         if (pos + 2 < end && text.charAt(pos) == ':') {
3945                             int m1 = getDigit(text, pos + 1);
3946                             int m2 = getDigit(text, pos + 2);
3947                             if (m1 >= 0 && m2 >= 0) {
3948                                 m = m1 * 10 + m2;
3949                                 pos += 3;
3950                                 if (pos + 2 < end && text.charAt(pos) == ':') {
3951                                     int s1 = getDigit(text, pos + 1);
3952                                     int s2 = getDigit(text, pos + 2);
3953                                     if (s1 >= 0 && s2 >= 0) {
3954                                         s = s1 * 10 + s2;
3955                                         pos += 3;
3956                                    }
3957                                 }
3958                             }
3959                         }
3960                     }
3961                 }
3962             }
3963             long offsetSecs = negative * (h * 3600L + m * 60L + s);
3964             return context.setParsedField(OFFSET_SECONDS, offsetSecs, position, pos);
3965         }
3966 
3967         @Override
3968         public String toString() {
3969             return "LocalizedOffset(" + style + ")";
3970         }
3971     }
3972 
3973     //-----------------------------------------------------------------------
3974     /**
3975      * Prints or parses a zone ID.
3976      */
3977     static final class ZoneTextPrinterParser extends ZoneIdPrinterParser {
3978 
3979         /** The text style to output. */
3980         private final TextStyle textStyle;
3981 
3982         /** The preferred zoneid map */
3983         private Set<String> preferredZones;
3984 
3985         /**  Display in generic time-zone format. True in case of pattern letter 'v' */
3986         private final boolean isGeneric;
3987         ZoneTextPrinterParser(TextStyle textStyle, Set<ZoneId> preferredZones, boolean isGeneric) {
3988             super(TemporalQueries.zone(), "ZoneText(" + textStyle + ")");
3989             this.textStyle = Objects.requireNonNull(textStyle, "textStyle");
3990             this.isGeneric = isGeneric;
3991             if (preferredZones != null && preferredZones.size() != 0) {
3992                 this.preferredZones = new HashSet<>();
3993                 for (ZoneId id : preferredZones) {
3994                     this.preferredZones.add(id.getId());
3995                 }
3996             }
3997         }
3998 
3999         private static final int STD = 0;
4000         private static final int DST = 1;
4001         private static final int GENERIC = 2;
4002         private static final Map<String, SoftReference<Map<Locale, String[]>>> cache =
4003             new ConcurrentHashMap<>();
4004 
4005         private String getDisplayName(String id, int type, Locale locale) {
4006             if (textStyle == TextStyle.NARROW) {
4007                 return null;
4008             }
4009             String[] names;
4010             SoftReference<Map<Locale, String[]>> ref = cache.get(id);
4011             Map<Locale, String[]> perLocale = null;
4012             if (ref == null || (perLocale = ref.get()) == null ||
4013                 (names = perLocale.get(locale)) == null) {
4014                 names = TimeZoneNameUtility.retrieveDisplayNames(id, locale);
4015                 if (names == null) {
4016                     return null;
4017                 }
4018                 names = Arrays.copyOfRange(names, 0, 7);
4019                 names[5] =
4020                     TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.LONG, locale);
4021                 if (names[5] == null) {
4022                     names[5] = names[0]; // use the id
4023                 }
4024                 names[6] =
4025                     TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.SHORT, locale);
4026                 if (names[6] == null) {
4027                     names[6] = names[0];
4028                 }
4029                 if (perLocale == null) {
4030                     perLocale = new ConcurrentHashMap<>();
4031                 }
4032                 perLocale.put(locale, names);
4033                 cache.put(id, new SoftReference<>(perLocale));
4034             }
4035             switch (type) {
4036             case STD:
4037                 return names[textStyle.zoneNameStyleIndex() + 1];
4038             case DST:
4039                 return names[textStyle.zoneNameStyleIndex() + 3];
4040             }
4041             return names[textStyle.zoneNameStyleIndex() + 5];
4042         }
4043 
4044         @Override
4045         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4046             ZoneId zone = context.getValue(TemporalQueries.zoneId());
4047             if (zone == null) {
4048                 return false;
4049             }
4050             String zname = zone.getId();
4051             if (!(zone instanceof ZoneOffset)) {
4052                 TemporalAccessor dt = context.getTemporal();
4053                 int type = GENERIC;
4054                 if (!isGeneric) {
4055                     if (dt.isSupported(ChronoField.INSTANT_SECONDS)) {
4056                         type = zone.getRules().isDaylightSavings(Instant.from(dt)) ? DST : STD;
4057                     } else if (dt.isSupported(ChronoField.EPOCH_DAY) &&
4058                                dt.isSupported(ChronoField.NANO_OF_DAY)) {
4059                         LocalDate date = LocalDate.ofEpochDay(dt.getLong(ChronoField.EPOCH_DAY));
4060                         LocalTime time = LocalTime.ofNanoOfDay(dt.getLong(ChronoField.NANO_OF_DAY));
4061                         LocalDateTime ldt = date.atTime(time);
4062                         if (zone.getRules().getTransition(ldt) == null) {
4063                             type = zone.getRules().isDaylightSavings(ldt.atZone(zone).toInstant()) ? DST : STD;
4064                         }
4065                     }
4066                 }
4067                 String name = getDisplayName(zname, type, context.getLocale());
4068                 if (name != null) {
4069                     zname = name;
4070                 }
4071             }
4072             buf.append(zname);
4073             return true;
4074         }
4075 
4076         // cache per instance for now
4077         private final Map<Locale, Entry<Integer, SoftReference<PrefixTree>>>
4078             cachedTree = new HashMap<>();
4079         private final Map<Locale, Entry<Integer, SoftReference<PrefixTree>>>
4080             cachedTreeCI = new HashMap<>();
4081 
4082         @Override
4083         protected PrefixTree getTree(DateTimeParseContext context) {
4084             if (textStyle == TextStyle.NARROW) {
4085                 return super.getTree(context);
4086             }
4087             Locale locale = context.getLocale();
4088             boolean isCaseSensitive = context.isCaseSensitive();
4089             Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
4090             int regionIdsSize = regionIds.size();
4091 
4092             Map<Locale, Entry<Integer, SoftReference<PrefixTree>>> cached =
4093                 isCaseSensitive ? cachedTree : cachedTreeCI;
4094 
4095             Entry<Integer, SoftReference<PrefixTree>> entry = null;
4096             PrefixTree tree = null;
4097             String[][] zoneStrings = null;
4098             if ((entry = cached.get(locale)) == null ||
4099                 (entry.getKey() != regionIdsSize ||
4100                 (tree = entry.getValue().get()) == null)) {
4101                 tree = PrefixTree.newTree(context);
4102                 zoneStrings = TimeZoneNameUtility.getZoneStrings(locale);
4103                 for (String[] names : zoneStrings) {
4104                     String zid = names[0];
4105                     if (!regionIds.contains(zid)) {
4106                         continue;
4107                     }
4108                     tree.add(zid, zid);    // don't convert zid -> metazone
4109                     zid = ZoneName.toZid(zid, locale);
4110                     int i = textStyle == TextStyle.FULL ? 1 : 2;
4111                     for (; i < names.length; i += 2) {
4112                         tree.add(names[i], zid);
4113                     }
4114                 }
4115                 // if we have a set of preferred zones, need a copy and
4116                 // add the preferred zones again to overwrite
4117                 if (preferredZones != null) {
4118                     for (String[] names : zoneStrings) {
4119                         String zid = names[0];
4120                         if (!preferredZones.contains(zid) || !regionIds.contains(zid)) {
4121                             continue;
4122                         }
4123                         int i = textStyle == TextStyle.FULL ? 1 : 2;
4124                         for (; i < names.length; i += 2) {
4125                             tree.add(names[i], zid);
4126                        }
4127                     }
4128                 }
4129                 cached.put(locale, new SimpleImmutableEntry<>(regionIdsSize, new SoftReference<>(tree)));
4130             }
4131             return tree;
4132         }
4133     }
4134 
4135     //-----------------------------------------------------------------------
4136     /**
4137      * Prints or parses a zone ID.
4138      */
4139     static class ZoneIdPrinterParser implements DateTimePrinterParser {
4140         private final TemporalQuery<ZoneId> query;
4141         private final String description;
4142 
4143         ZoneIdPrinterParser(TemporalQuery<ZoneId> query, String description) {
4144             this.query = query;
4145             this.description = description;
4146         }
4147 
4148         @Override
4149         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4150             ZoneId zone = context.getValue(query);
4151             if (zone == null) {
4152                 return false;
4153             }
4154             buf.append(zone.getId());
4155             return true;
4156         }
4157 
4158         /**
4159          * The cached tree to speed up parsing.
4160          */
4161         private static volatile Entry<Integer, PrefixTree> cachedPrefixTree;
4162         private static volatile Entry<Integer, PrefixTree> cachedPrefixTreeCI;
4163 
4164         protected PrefixTree getTree(DateTimeParseContext context) {
4165             // prepare parse tree
4166             Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
4167             final int regionIdsSize = regionIds.size();
4168             Entry<Integer, PrefixTree> cached = context.isCaseSensitive()
4169                                                 ? cachedPrefixTree : cachedPrefixTreeCI;
4170             if (cached == null || cached.getKey() != regionIdsSize) {
4171                 synchronized (this) {
4172                     cached = context.isCaseSensitive() ? cachedPrefixTree : cachedPrefixTreeCI;
4173                     if (cached == null || cached.getKey() != regionIdsSize) {
4174                         cached = new SimpleImmutableEntry<>(regionIdsSize, PrefixTree.newTree(regionIds, context));
4175                         if (context.isCaseSensitive()) {
4176                             cachedPrefixTree = cached;
4177                         } else {
4178                             cachedPrefixTreeCI = cached;
4179                         }
4180                     }
4181                 }
4182             }
4183             return cached.getValue();
4184         }
4185 
4186         /**
4187          * This implementation looks for the longest matching string.
4188          * For example, parsing Etc/GMT-2 will return Etc/GMC-2 rather than just
4189          * Etc/GMC although both are valid.
4190          */
4191         @Override
4192         public int parse(DateTimeParseContext context, CharSequence text, int position) {
4193             int length = text.length();
4194             if (position > length) {
4195                 throw new IndexOutOfBoundsException();
4196             }
4197             if (position == length) {
4198                 return ~position;
4199             }
4200 
4201             // handle fixed time-zone IDs
4202             char nextChar = text.charAt(position);
4203             if (nextChar == '+' || nextChar == '-') {
4204                 return parseOffsetBased(context, text, position, position, OffsetIdPrinterParser.INSTANCE_ID_Z);
4205             } else if (length >= position + 2) {
4206                 char nextNextChar = text.charAt(position + 1);
4207                 if (context.charEquals(nextChar, 'U') && context.charEquals(nextNextChar, 'T')) {
4208                     if (length >= position + 3 && context.charEquals(text.charAt(position + 2), 'C')) {
4209                         return parseOffsetBased(context, text, position, position + 3, OffsetIdPrinterParser.INSTANCE_ID_ZERO);
4210                     }
4211                     return parseOffsetBased(context, text, position, position + 2, OffsetIdPrinterParser.INSTANCE_ID_ZERO);
4212                 } else if (context.charEquals(nextChar, 'G') && length >= position + 3 &&
4213                         context.charEquals(nextNextChar, 'M') && context.charEquals(text.charAt(position + 2), 'T')) {
4214                     if (length >= position + 4 && context.charEquals(text.charAt(position + 3), '0')) {
4215                         context.setParsed(ZoneId.of("GMT0"));
4216                         return position + 4;
4217                     }
4218                     return parseOffsetBased(context, text, position, position + 3, OffsetIdPrinterParser.INSTANCE_ID_ZERO);
4219                 }
4220             }
4221 
4222             // parse
4223             PrefixTree tree = getTree(context);
4224             ParsePosition ppos = new ParsePosition(position);
4225             String parsedZoneId = tree.match(text, ppos);
4226             if (parsedZoneId == null) {
4227                 if (context.charEquals(nextChar, 'Z')) {
4228                     context.setParsed(ZoneOffset.UTC);
4229                     return position + 1;
4230                 }
4231                 return ~position;
4232             }
4233             context.setParsed(ZoneId.of(parsedZoneId));
4234             return ppos.getIndex();
4235         }
4236 
4237         /**
4238          * Parse an offset following a prefix and set the ZoneId if it is valid.
4239          * To matching the parsing of ZoneId.of the values are not normalized
4240          * to ZoneOffsets.
4241          *
4242          * @param context the parse context
4243          * @param text the input text
4244          * @param prefixPos start of the prefix
4245          * @param position start of text after the prefix
4246          * @param parser parser for the value after the prefix
4247          * @return the position after the parse
4248          */
4249         private int parseOffsetBased(DateTimeParseContext context, CharSequence text, int prefixPos, int position, OffsetIdPrinterParser parser) {
4250             String prefix = text.toString().substring(prefixPos, position).toUpperCase();
4251             if (position >= text.length()) {
4252                 context.setParsed(ZoneId.of(prefix));
4253                 return position;
4254             }
4255 
4256             // '0' or 'Z' after prefix is not part of a valid ZoneId; use bare prefix
4257             if (text.charAt(position) == '0' ||
4258                 context.charEquals(text.charAt(position), 'Z')) {
4259                 context.setParsed(ZoneId.of(prefix));
4260                 return position;
4261             }
4262 
4263             DateTimeParseContext newContext = context.copy();
4264             int endPos = parser.parse(newContext, text, position);
4265             try {
4266                 if (endPos < 0) {
4267                     if (parser == OffsetIdPrinterParser.INSTANCE_ID_Z) {
4268                         return ~prefixPos;
4269                     }
4270                     context.setParsed(ZoneId.of(prefix));
4271                     return position;
4272                 }
4273                 int offset = (int) newContext.getParsed(OFFSET_SECONDS).longValue();
4274                 ZoneOffset zoneOffset = ZoneOffset.ofTotalSeconds(offset);
4275                 context.setParsed(ZoneId.ofOffset(prefix, zoneOffset));
4276                 return endPos;
4277             } catch (DateTimeException dte) {
4278                 return ~prefixPos;
4279             }
4280         }
4281 
4282         @Override
4283         public String toString() {
4284             return description;
4285         }
4286     }
4287 
4288     //-----------------------------------------------------------------------
4289     /**
4290      * A String based prefix tree for parsing time-zone names.
4291      */
4292     static class PrefixTree {
4293         protected String key;
4294         protected String value;
4295         protected char c0;    // performance optimization to avoid the
4296                               // boundary check cost of key.charat(0)
4297         protected PrefixTree child;
4298         protected PrefixTree sibling;
4299 
4300         private PrefixTree(String k, String v, PrefixTree child) {
4301             this.key = k;
4302             this.value = v;
4303             this.child = child;
4304             if (k.length() == 0){
4305                 c0 = 0xffff;
4306             } else {
4307                 c0 = key.charAt(0);
4308             }
4309         }
4310 
4311         /**
4312          * Creates a new prefix parsing tree based on parse context.
4313          *
4314          * @param context  the parse context
4315          * @return the tree, not null
4316          */
4317         public static PrefixTree newTree(DateTimeParseContext context) {
4318             //if (!context.isStrict()) {
4319             //    return new LENIENT("", null, null);
4320             //}
4321             if (context.isCaseSensitive()) {
4322                 return new PrefixTree("", null, null);
4323             }
4324             return new CI("", null, null);
4325         }
4326 
4327         /**
4328          * Creates a new prefix parsing tree.
4329          *
4330          * @param keys  a set of strings to build the prefix parsing tree, not null
4331          * @param context  the parse context
4332          * @return the tree, not null
4333          */
4334         public static  PrefixTree newTree(Set<String> keys, DateTimeParseContext context) {
4335             PrefixTree tree = newTree(context);
4336             for (String k : keys) {
4337                 tree.add0(k, k);
4338             }
4339             return tree;
4340         }
4341 
4342         /**
4343          * Clone a copy of this tree
4344          */
4345         public PrefixTree copyTree() {
4346             PrefixTree copy = new PrefixTree(key, value, null);
4347             if (child != null) {
4348                 copy.child = child.copyTree();
4349             }
4350             if (sibling != null) {
4351                 copy.sibling = sibling.copyTree();
4352             }
4353             return copy;
4354         }
4355 
4356 
4357         /**
4358          * Adds a pair of {key, value} into the prefix tree.
4359          *
4360          * @param k  the key, not null
4361          * @param v  the value, not null
4362          * @return  true if the pair is added successfully
4363          */
4364         public boolean add(String k, String v) {
4365             return add0(k, v);
4366         }
4367 
4368         private boolean add0(String k, String v) {
4369             k = toKey(k);
4370             int prefixLen = prefixLength(k);
4371             if (prefixLen == key.length()) {
4372                 if (prefixLen < k.length()) {  // down the tree
4373                     String subKey = k.substring(prefixLen);
4374                     PrefixTree c = child;
4375                     while (c != null) {
4376                         if (isEqual(c.c0, subKey.charAt(0))) {
4377                             return c.add0(subKey, v);
4378                         }
4379                         c = c.sibling;
4380                     }
4381                     // add the node as the child of the current node
4382                     c = newNode(subKey, v, null);
4383                     c.sibling = child;
4384                     child = c;
4385                     return true;
4386                 }
4387                 // have an existing <key, value> already, overwrite it
4388                 // if (value != null) {
4389                 //    return false;
4390                 //}
4391                 value = v;
4392                 return true;
4393             }
4394             // split the existing node
4395             PrefixTree n1 = newNode(key.substring(prefixLen), value, child);
4396             key = k.substring(0, prefixLen);
4397             child = n1;
4398             if (prefixLen < k.length()) {
4399                 PrefixTree n2 = newNode(k.substring(prefixLen), v, null);
4400                 child.sibling = n2;
4401                 value = null;
4402             } else {
4403                 value = v;
4404             }
4405             return true;
4406         }
4407 
4408         /**
4409          * Match text with the prefix tree.
4410          *
4411          * @param text  the input text to parse, not null
4412          * @param off  the offset position to start parsing at
4413          * @param end  the end position to stop parsing
4414          * @return the resulting string, or null if no match found.
4415          */
4416         public String match(CharSequence text, int off, int end) {
4417             if (!prefixOf(text, off, end)){
4418                 return null;
4419             }
4420             if (child != null && (off += key.length()) != end) {
4421                 PrefixTree c = child;
4422                 do {
4423                     if (isEqual(c.c0, text.charAt(off))) {
4424                         String found = c.match(text, off, end);
4425                         if (found != null) {
4426                             return found;
4427                         }
4428                         return value;
4429                     }
4430                     c = c.sibling;
4431                 } while (c != null);
4432             }
4433             return value;
4434         }
4435 
4436         /**
4437          * Match text with the prefix tree.
4438          *
4439          * @param text  the input text to parse, not null
4440          * @param pos  the position to start parsing at, from 0 to the text
4441          *  length. Upon return, position will be updated to the new parse
4442          *  position, or unchanged, if no match found.
4443          * @return the resulting string, or null if no match found.
4444          */
4445         public String match(CharSequence text, ParsePosition pos) {
4446             int off = pos.getIndex();
4447             int end = text.length();
4448             if (!prefixOf(text, off, end)){
4449                 return null;
4450             }
4451             off += key.length();
4452             if (child != null && off != end) {
4453                 PrefixTree c = child;
4454                 do {
4455                     if (isEqual(c.c0, text.charAt(off))) {
4456                         pos.setIndex(off);
4457                         String found = c.match(text, pos);
4458                         if (found != null) {
4459                             return found;
4460                         }
4461                         break;
4462                     }
4463                     c = c.sibling;
4464                 } while (c != null);
4465             }
4466             pos.setIndex(off);
4467             return value;
4468         }
4469 
4470         protected String toKey(String k) {
4471             return k;
4472         }
4473 
4474         protected PrefixTree newNode(String k, String v, PrefixTree child) {
4475             return new PrefixTree(k, v, child);
4476         }
4477 
4478         protected boolean isEqual(char c1, char c2) {
4479             return c1 == c2;
4480         }
4481 
4482         protected boolean prefixOf(CharSequence text, int off, int end) {
4483             if (text instanceof String) {
4484                 return ((String)text).startsWith(key, off);
4485             }
4486             int len = key.length();
4487             if (len > end - off) {
4488                 return false;
4489             }
4490             int off0 = 0;
4491             while (len-- > 0) {
4492                 if (!isEqual(key.charAt(off0++), text.charAt(off++))) {
4493                     return false;
4494                 }
4495             }
4496             return true;
4497         }
4498 
4499         private int prefixLength(String k) {
4500             int off = 0;
4501             while (off < k.length() && off < key.length()) {
4502                 if (!isEqual(k.charAt(off), key.charAt(off))) {
4503                     return off;
4504                 }
4505                 off++;
4506             }
4507             return off;
4508         }
4509 
4510         /**
4511          * Case Insensitive prefix tree.
4512          */
4513         private static class CI extends PrefixTree {
4514 
4515             private CI(String k, String v, PrefixTree child) {
4516                 super(k, v, child);
4517             }
4518 
4519             @Override
4520             protected CI newNode(String k, String v, PrefixTree child) {
4521                 return new CI(k, v, child);
4522             }
4523 
4524             @Override
4525             protected boolean isEqual(char c1, char c2) {
4526                 return DateTimeParseContext.charEqualsIgnoreCase(c1, c2);
4527             }
4528 
4529             @Override
4530             protected boolean prefixOf(CharSequence text, int off, int end) {
4531                 int len = key.length();
4532                 if (len > end - off) {
4533                     return false;
4534                 }
4535                 int off0 = 0;
4536                 while (len-- > 0) {
4537                     if (!isEqual(key.charAt(off0++), text.charAt(off++))) {
4538                         return false;
4539                     }
4540                 }
4541                 return true;
4542             }
4543         }
4544 
4545         /**
4546          * Lenient prefix tree. Case insensitive and ignores characters
4547          * like space, underscore and slash.
4548          */
4549         private static class LENIENT extends CI {
4550 
4551             private LENIENT(String k, String v, PrefixTree child) {
4552                 super(k, v, child);
4553             }
4554 
4555             @Override
4556             protected CI newNode(String k, String v, PrefixTree child) {
4557                 return new LENIENT(k, v, child);
4558             }
4559 
4560             private boolean isLenientChar(char c) {
4561                 return c == ' ' || c == '_' || c == '/';
4562             }
4563 
4564             protected String toKey(String k) {
4565                 for (int i = 0; i < k.length(); i++) {
4566                     if (isLenientChar(k.charAt(i))) {
4567                         StringBuilder sb = new StringBuilder(k.length());
4568                         sb.append(k, 0, i);
4569                         i++;
4570                         while (i < k.length()) {
4571                             if (!isLenientChar(k.charAt(i))) {
4572                                 sb.append(k.charAt(i));
4573                             }
4574                             i++;
4575                         }
4576                         return sb.toString();
4577                     }
4578                 }
4579                 return k;
4580             }
4581 
4582             @Override
4583             public String match(CharSequence text, ParsePosition pos) {
4584                 int off = pos.getIndex();
4585                 int end = text.length();
4586                 int len = key.length();
4587                 int koff = 0;
4588                 while (koff < len && off < end) {
4589                     if (isLenientChar(text.charAt(off))) {
4590                         off++;
4591                         continue;
4592                     }
4593                     if (!isEqual(key.charAt(koff++), text.charAt(off++))) {
4594                         return null;
4595                     }
4596                 }
4597                 if (koff != len) {
4598                     return null;
4599                 }
4600                 if (child != null && off != end) {
4601                     int off0 = off;
4602                     while (off0 < end && isLenientChar(text.charAt(off0))) {
4603                         off0++;
4604                     }
4605                     if (off0 < end) {
4606                         PrefixTree c = child;
4607                         do {
4608                             if (isEqual(c.c0, text.charAt(off0))) {
4609                                 pos.setIndex(off0);
4610                                 String found = c.match(text, pos);
4611                                 if (found != null) {
4612                                     return found;
4613                                 }
4614                                 break;
4615                             }
4616                             c = c.sibling;
4617                         } while (c != null);
4618                     }
4619                 }
4620                 pos.setIndex(off);
4621                 return value;
4622             }
4623         }
4624     }
4625 
4626     //-----------------------------------------------------------------------
4627     /**
4628      * Prints or parses a chronology.
4629      */
4630     static final class ChronoPrinterParser implements DateTimePrinterParser {
4631         /** The text style to output, null means the ID. */
4632         private final TextStyle textStyle;
4633 
4634         ChronoPrinterParser(TextStyle textStyle) {
4635             // validated by caller
4636             this.textStyle = textStyle;
4637         }
4638 
4639         @Override
4640         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4641             Chronology chrono = context.getValue(TemporalQueries.chronology());
4642             if (chrono == null) {
4643                 return false;
4644             }
4645             if (textStyle == null) {
4646                 buf.append(chrono.getId());
4647             } else {
4648                 buf.append(getChronologyName(chrono, context.getLocale()));
4649             }
4650             return true;
4651         }
4652 
4653         @Override
4654         public int parse(DateTimeParseContext context, CharSequence text, int position) {
4655             // simple looping parser to find the chronology
4656             if (position < 0 || position > text.length()) {
4657                 throw new IndexOutOfBoundsException();
4658             }
4659             Set<Chronology> chronos = Chronology.getAvailableChronologies();
4660             Chronology bestMatch = null;
4661             int matchLen = -1;
4662             for (Chronology chrono : chronos) {
4663                 String name;
4664                 if (textStyle == null) {
4665                     name = chrono.getId();
4666                 } else {
4667                     name = getChronologyName(chrono, context.getLocale());
4668                 }
4669                 int nameLen = name.length();
4670                 if (nameLen > matchLen && context.subSequenceEquals(text, position, name, 0, nameLen)) {
4671                     bestMatch = chrono;
4672                     matchLen = nameLen;
4673                 }
4674             }
4675             if (bestMatch == null) {
4676                 return ~position;
4677             }
4678             context.setParsed(bestMatch);
4679             return position + matchLen;
4680         }
4681 
4682         /**
4683          * Returns the chronology name of the given chrono in the given locale
4684          * if available, or the chronology Id otherwise. The regular ResourceBundle
4685          * search path is used for looking up the chronology name.
4686          *
4687          * @param chrono  the chronology, not null
4688          * @param locale  the locale, not null
4689          * @return the chronology name of chrono in locale, or the id if no name is available
4690          * @throws NullPointerException if chrono or locale is null
4691          */
4692         private String getChronologyName(Chronology chrono, Locale locale) {
4693             String key = "calendarname." + chrono.getCalendarType();
4694             String name = DateTimeTextProvider.getLocalizedResource(key, locale);
4695             return Objects.requireNonNullElseGet(name, () -> chrono.getId());
4696         }
4697     }
4698 
4699     //-----------------------------------------------------------------------
4700     /**
4701      * Prints or parses a localized pattern.
4702      */
4703     static final class LocalizedPrinterParser implements DateTimePrinterParser {
4704         /** Cache of formatters. */
4705         private static final ConcurrentMap<String, DateTimeFormatter> FORMATTER_CACHE = new ConcurrentHashMap<>(16, 0.75f, 2);
4706 
4707         private final FormatStyle dateStyle;
4708         private final FormatStyle timeStyle;
4709 
4710         /**
4711          * Constructor.
4712          *
4713          * @param dateStyle  the date style to use, may be null
4714          * @param timeStyle  the time style to use, may be null
4715          */
4716         LocalizedPrinterParser(FormatStyle dateStyle, FormatStyle timeStyle) {
4717             // validated by caller
4718             this.dateStyle = dateStyle;
4719             this.timeStyle = timeStyle;
4720         }
4721 
4722         @Override
4723         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4724             Chronology chrono = Chronology.from(context.getTemporal());
4725             return formatter(context.getLocale(), chrono).toPrinterParser(false).format(context, buf);
4726         }
4727 
4728         @Override
4729         public int parse(DateTimeParseContext context, CharSequence text, int position) {
4730             Chronology chrono = context.getEffectiveChronology();
4731             return formatter(context.getLocale(), chrono).toPrinterParser(false).parse(context, text, position);
4732         }
4733 
4734         /**
4735          * Gets the formatter to use.
4736          * <p>
4737          * The formatter will be the most appropriate to use for the date and time style in the locale.
4738          * For example, some locales will use the month name while others will use the number.
4739          *
4740          * @param locale  the locale to use, not null
4741          * @param chrono  the chronology to use, not null
4742          * @return the formatter, not null
4743          * @throws IllegalArgumentException if the formatter cannot be found
4744          */
4745         private DateTimeFormatter formatter(Locale locale, Chronology chrono) {
4746             String key = chrono.getId() + '|' + locale.toString() + '|' + dateStyle + timeStyle;
4747             DateTimeFormatter formatter = FORMATTER_CACHE.get(key);
4748             if (formatter == null) {
4749                 String pattern = getLocalizedDateTimePattern(dateStyle, timeStyle, chrono, locale);
4750                 formatter = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(locale);
4751                 DateTimeFormatter old = FORMATTER_CACHE.putIfAbsent(key, formatter);
4752                 if (old != null) {
4753                     formatter = old;
4754                 }
4755             }
4756             return formatter;
4757         }
4758 
4759         @Override
4760         public String toString() {
4761             return "Localized(" + (dateStyle != null ? dateStyle : "") + "," +
4762                 (timeStyle != null ? timeStyle : "") + ")";
4763         }
4764     }
4765 
4766     //-----------------------------------------------------------------------
4767     /**
4768      * Prints or parses a localized pattern from a localized field.
4769      * The specific formatter and parameters is not selected until the
4770      * the field is to be printed or parsed.
4771      * The locale is needed to select the proper WeekFields from which
4772      * the field for day-of-week, week-of-month, or week-of-year is selected.
4773      */
4774     static final class WeekBasedFieldPrinterParser implements DateTimePrinterParser {
4775         private char chr;
4776         private int count;
4777 
4778         /**
4779          * Constructor.
4780          *
4781          * @param chr the pattern format letter that added this PrinterParser.
4782          * @param count the repeat count of the format letter
4783          */
4784         WeekBasedFieldPrinterParser(char chr, int count) {
4785             this.chr = chr;
4786             this.count = count;
4787         }
4788 
4789         @Override
4790         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4791             return printerParser(context.getLocale()).format(context, buf);
4792         }
4793 
4794         @Override
4795         public int parse(DateTimeParseContext context, CharSequence text, int position) {
4796             return printerParser(context.getLocale()).parse(context, text, position);
4797         }
4798 
4799         /**
4800          * Gets the printerParser to use based on the field and the locale.
4801          *
4802          * @param locale  the locale to use, not null
4803          * @return the formatter, not null
4804          * @throws IllegalArgumentException if the formatter cannot be found
4805          */
4806         private DateTimePrinterParser printerParser(Locale locale) {
4807             WeekFields weekDef = WeekFields.of(locale);
4808             TemporalField field = null;
4809             switch (chr) {
4810                 case 'Y':
4811                     field = weekDef.weekBasedYear();
4812                     if (count == 2) {
4813                         return new ReducedPrinterParser(field, 2, 2, 0, ReducedPrinterParser.BASE_DATE, 0);
4814                     } else {
4815                         return new NumberPrinterParser(field, count, 19,
4816                                 (count < 4) ? SignStyle.NORMAL : SignStyle.EXCEEDS_PAD, -1);
4817                     }
4818                 case 'e':
4819                 case 'c':
4820                     field = weekDef.dayOfWeek();
4821                     break;
4822                 case 'w':
4823                     field = weekDef.weekOfWeekBasedYear();
4824                     break;
4825                 case 'W':
4826                     field = weekDef.weekOfMonth();
4827                     break;
4828                 default:
4829                     throw new IllegalStateException("unreachable");
4830             }
4831             return new NumberPrinterParser(field, (count == 2 ? 2 : 1), 2, SignStyle.NOT_NEGATIVE);
4832         }
4833 
4834         @Override
4835         public String toString() {
4836             StringBuilder sb = new StringBuilder(30);
4837             sb.append("Localized(");
4838             if (chr == 'Y') {
4839                 if (count == 1) {
4840                     sb.append("WeekBasedYear");
4841                 } else if (count == 2) {
4842                     sb.append("ReducedValue(WeekBasedYear,2,2,2000-01-01)");
4843                 } else {
4844                     sb.append("WeekBasedYear,").append(count).append(",")
4845                             .append(19).append(",")
4846                             .append((count < 4) ? SignStyle.NORMAL : SignStyle.EXCEEDS_PAD);
4847                 }
4848             } else {
4849                 switch (chr) {
4850                     case 'c':
4851                     case 'e':
4852                         sb.append("DayOfWeek");
4853                         break;
4854                     case 'w':
4855                         sb.append("WeekOfWeekBasedYear");
4856                         break;
4857                     case 'W':
4858                         sb.append("WeekOfMonth");
4859                         break;
4860                     default:
4861                         break;
4862                 }
4863                 sb.append(",");
4864                 sb.append(count);
4865             }
4866             sb.append(")");
4867             return sb.toString();
4868         }
4869     }
4870 
4871     //-------------------------------------------------------------------------
4872     /**
4873      * Length comparator.
4874      */
4875     static final Comparator<String> LENGTH_SORT = new Comparator<String>() {
4876         @Override
4877         public int compare(String str1, String str2) {
4878             return str1.length() == str2.length() ? str1.compareTo(str2) : str1.length() - str2.length();
4879         }
4880     };
4881 }