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