1 /*
   2  * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 /*
  27  * This file is available under and governed by the GNU General Public
  28  * License version 2 only, as published by the Free Software Foundation.
  29  * However, the following notice accompanied the original version of this
  30  * file:
  31  *
  32  * Copyright (c) 2008-2012, Stephen Colebourne & Michael Nascimento Santos
  33  *
  34  * All rights reserved.
  35  *
  36  * Redistribution and use in source and binary forms, with or without
  37  * modification, are permitted provided that the following conditions are met:
  38  *
  39  *  * Redistributions of source code must retain the above copyright notice,
  40  *    this list of conditions and the following disclaimer.
  41  *
  42  *  * Redistributions in binary form must reproduce the above copyright notice,
  43  *    this list of conditions and the following disclaimer in the documentation
  44  *    and/or other materials provided with the distribution.
  45  *
  46  *  * Neither the name of JSR-310 nor the names of its contributors
  47  *    may be used to endorse or promote products derived from this software
  48  *    without specific prior written permission.
  49  *
  50  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  51  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  52  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  53  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  54  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  55  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  56  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  57  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  58  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  59  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  60  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  61  */
  62 package java.time.format;
  63 
  64 import static java.time.temporal.ChronoField.DAY_OF_MONTH;
  65 import static java.time.temporal.ChronoField.HOUR_OF_DAY;
  66 import static java.time.temporal.ChronoField.INSTANT_SECONDS;
  67 import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
  68 import static java.time.temporal.ChronoField.MONTH_OF_YEAR;
  69 import static java.time.temporal.ChronoField.NANO_OF_SECOND;
  70 import static java.time.temporal.ChronoField.OFFSET_SECONDS;
  71 import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
  72 import static java.time.temporal.ChronoField.YEAR;
  73 import static java.time.temporal.ChronoField.ERA;
  74 
  75 import java.lang.ref.SoftReference;
  76 import java.math.BigDecimal;
  77 import java.math.BigInteger;
  78 import java.math.RoundingMode;
  79 import java.text.ParsePosition;
  80 import java.time.DateTimeException;
  81 import java.time.Instant;
  82 import java.time.LocalDate;
  83 import java.time.LocalDateTime;
  84 import java.time.LocalTime;
  85 import java.time.ZoneId;
  86 import java.time.ZoneOffset;
  87 import java.time.chrono.ChronoLocalDate;
  88 import java.time.chrono.ChronoLocalDateTime;
  89 import java.time.chrono.Chronology;
  90 import java.time.chrono.Era;
  91 import java.time.chrono.IsoChronology;
  92 import java.time.format.DateTimeTextProvider.LocaleStore;
  93 import java.time.temporal.ChronoField;
  94 import java.time.temporal.IsoFields;
  95 import java.time.temporal.JulianFields;
  96 import java.time.temporal.TemporalAccessor;
  97 import java.time.temporal.TemporalField;
  98 import java.time.temporal.TemporalQueries;
  99 import java.time.temporal.TemporalQuery;
 100 import java.time.temporal.ValueRange;
 101 import java.time.temporal.WeekFields;
 102 import java.time.zone.ZoneRulesProvider;
 103 import java.util.AbstractMap.SimpleImmutableEntry;
 104 import java.util.ArrayList;
 105 import java.util.Arrays;
 106 import java.util.Collections;
 107 import java.util.Comparator;
 108 import java.util.HashMap;
 109 import java.util.HashSet;
 110 import java.util.Iterator;
 111 import java.util.LinkedHashMap;
 112 import java.util.List;
 113 import java.util.Locale;
 114 import java.util.Map;
 115 import java.util.Map.Entry;
 116 import java.util.Objects;
 117 import java.util.Set;
 118 import java.util.TimeZone;
 119 import java.util.concurrent.ConcurrentHashMap;
 120 import java.util.concurrent.ConcurrentMap;
 121 
 122 import sun.text.spi.JavaTimeDateTimePatternProvider;
 123 import sun.util.locale.provider.LocaleProviderAdapter;
 124 import sun.util.locale.provider.LocaleResources;
 125 import sun.util.locale.provider.TimeZoneNameUtility;
 126 
 127 /**
 128  * Builder to create date-time formatters.
 129  * <p>
 130  * This allows a {@code DateTimeFormatter} to be created.
 131  * All date-time formatters are created ultimately using this builder.
 132  * <p>
 133  * The basic elements of date-time can all be added:
 134  * <ul>
 135  * <li>Value - a numeric value</li>
 136  * <li>Fraction - a fractional value including the decimal place. Always use this when
 137  * outputting fractions to ensure that the fraction is parsed correctly</li>
 138  * <li>Text - the textual equivalent for the value</li>
 139  * <li>OffsetId/Offset - the {@linkplain ZoneOffset zone offset}</li>
 140  * <li>ZoneId - the {@linkplain ZoneId time-zone} id</li>
 141  * <li>ZoneText - the name of the time-zone</li>
 142  * <li>ChronologyId - the {@linkplain Chronology chronology} id</li>
 143  * <li>ChronologyText - the name of the chronology</li>
 144  * <li>Literal - a text literal</li>
 145  * <li>Nested and Optional - formats can be nested or made optional</li>
 146  * </ul>
 147  * In addition, any of the elements may be decorated by padding, either with spaces or any other character.
 148  * <p>
 149  * Finally, a shorthand pattern, mostly compatible with {@code java.text.SimpleDateFormat SimpleDateFormat}
 150  * can be used, see {@link #appendPattern(String)}.
 151  * In practice, this simply parses the pattern and calls other methods on the builder.
 152  *
 153  * @implSpec
 154  * This class is a mutable builder intended for use from a single thread.
 155  *
 156  * @since 1.8
 157  */
 158 public final class DateTimeFormatterBuilder {
 159 
 160     /**
 161      * Query for a time-zone that is region-only.
 162      */
 163     private static final TemporalQuery<ZoneId> QUERY_REGION_ONLY = (temporal) -> {
 164         ZoneId zone = temporal.query(TemporalQueries.zoneId());
 165         return (zone != null && zone instanceof ZoneOffset == false ? zone : null);
 166     };
 167 
 168     /**
 169      * The currently active builder, used by the outermost builder.
 170      */
 171     private DateTimeFormatterBuilder active = this;
 172     /**
 173      * The parent builder, null for the outermost builder.
 174      */
 175     private final DateTimeFormatterBuilder parent;
 176     /**
 177      * The list of printers that will be used.
 178      */
 179     private final List<DateTimePrinterParser> printerParsers = new ArrayList<>();
 180     /**
 181      * Whether this builder produces an optional formatter.
 182      */
 183     private final boolean optional;
 184     /**
 185      * The width to pad the next field to.
 186      */
 187     private int padNextWidth;
 188     /**
 189      * The character to pad the next field with.
 190      */
 191     private char padNextChar;
 192     /**
 193      * The index of the last variable width value parser.
 194      */
 195     private int valueParserIndex = -1;
 196 
 197     /**
 198      * Gets the formatting pattern for date and time styles for a locale and chronology.
 199      * The locale and chronology are used to lookup the locale specific format
 200      * for the requested dateStyle and/or timeStyle.
 201      *
 202      * @param dateStyle  the FormatStyle for the date, null for time-only pattern
 203      * @param timeStyle  the FormatStyle for the time, null for date-only pattern
 204      * @param chrono  the Chronology, non-null
 205      * @param locale  the locale, non-null
 206      * @return the locale and Chronology specific formatting pattern
 207      * @throws IllegalArgumentException if both dateStyle and timeStyle are null
 208      */
 209     public static String getLocalizedDateTimePattern(FormatStyle dateStyle, FormatStyle timeStyle,
 210             Chronology chrono, Locale locale) {
 211         Objects.requireNonNull(locale, "locale");
 212         Objects.requireNonNull(chrono, "chrono");
 213         if (dateStyle == null && timeStyle == null) {
 214             throw new IllegalArgumentException("Either dateStyle or timeStyle must be non-null");
 215         }
 216         LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(JavaTimeDateTimePatternProvider.class, locale);
 217         JavaTimeDateTimePatternProvider provider = adapter.getJavaTimeDateTimePatternProvider();
 218         String pattern = provider.getJavaTimeDateTimePattern(convertStyle(timeStyle),
 219                          convertStyle(dateStyle), chrono.getCalendarType(), locale);
 220         return pattern;
 221     }
 222 
 223     /**
 224      * Converts the given FormatStyle to the java.text.DateFormat style.
 225      *
 226      * @param style  the FormatStyle style
 227      * @return the int style, or -1 if style is null, indicating un-required
 228      */
 229     private static int convertStyle(FormatStyle style) {
 230         if (style == null) {
 231             return -1;
 232         }
 233         return style.ordinal();  // indices happen to align
 234     }
 235 
 236     /**
 237      * Constructs a new instance of the builder.
 238      */
 239     public DateTimeFormatterBuilder() {
 240         super();
 241         parent = null;
 242         optional = false;
 243     }
 244 
 245     /**
 246      * Constructs a new instance of the builder.
 247      *
 248      * @param parent  the parent builder, not null
 249      * @param optional  whether the formatter is optional, not null
 250      */
 251     private DateTimeFormatterBuilder(DateTimeFormatterBuilder parent, boolean optional) {
 252         super();
 253         this.parent = parent;
 254         this.optional = optional;
 255     }
 256 
 257     //-----------------------------------------------------------------------
 258     /**
 259      * Changes the parse style to be case sensitive for the remainder of the formatter.
 260      * <p>
 261      * Parsing can be case sensitive or insensitive - by default it is case sensitive.
 262      * This method allows the case sensitivity setting of parsing to be changed.
 263      * <p>
 264      * Calling this method changes the state of the builder such that all
 265      * subsequent builder method calls will parse text in case sensitive mode.
 266      * See {@link #parseCaseInsensitive} for the opposite setting.
 267      * The parse case sensitive/insensitive methods may be called at any point
 268      * in the builder, thus the parser can swap between case parsing modes
 269      * multiple times during the parse.
 270      * <p>
 271      * Since the default is case sensitive, this method should only be used after
 272      * a previous call to {@code #parseCaseInsensitive}.
 273      *
 274      * @return this, for chaining, not null
 275      */
 276     public DateTimeFormatterBuilder parseCaseSensitive() {
 277         appendInternal(SettingsParser.SENSITIVE);
 278         return this;
 279     }
 280 
 281     /**
 282      * Changes the parse style to be case insensitive for the remainder of the formatter.
 283      * <p>
 284      * Parsing can be case sensitive or insensitive - by default it is case sensitive.
 285      * This method allows the case sensitivity setting of parsing to be changed.
 286      * <p>
 287      * Calling this method changes the state of the builder such that all
 288      * subsequent builder method calls will parse text in case insensitive mode.
 289      * See {@link #parseCaseSensitive()} for the opposite setting.
 290      * The parse case sensitive/insensitive methods may be called at any point
 291      * in the builder, thus the parser can swap between case parsing modes
 292      * multiple times during the parse.
 293      *
 294      * @return this, for chaining, not null
 295      */
 296     public DateTimeFormatterBuilder parseCaseInsensitive() {
 297         appendInternal(SettingsParser.INSENSITIVE);
 298         return this;
 299     }
 300 
 301     //-----------------------------------------------------------------------
 302     /**
 303      * Changes the parse style to be strict for the remainder of the formatter.
 304      * <p>
 305      * Parsing can be strict or lenient - by default its strict.
 306      * This controls the degree of flexibility in matching the text and sign styles.
 307      * <p>
 308      * When used, this method changes the parsing to be strict from this point onwards.
 309      * As strict is the default, this is normally only needed after calling {@link #parseLenient()}.
 310      * The change will remain in force until the end of the formatter that is eventually
 311      * constructed or until {@code parseLenient} is called.
 312      *
 313      * @return this, for chaining, not null
 314      */
 315     public DateTimeFormatterBuilder parseStrict() {
 316         appendInternal(SettingsParser.STRICT);
 317         return this;
 318     }
 319 
 320     /**
 321      * Changes the parse style to be lenient for the remainder of the formatter.
 322      * Note that case sensitivity is set separately to this method.
 323      * <p>
 324      * Parsing can be strict or lenient - by default its strict.
 325      * This controls the degree of flexibility in matching the text and sign styles.
 326      * Applications calling this method should typically also call {@link #parseCaseInsensitive()}.
 327      * <p>
 328      * When used, this method changes the parsing to be lenient from this point onwards.
 329      * The change will remain in force until the end of the formatter that is eventually
 330      * constructed or until {@code parseStrict} is called.
 331      *
 332      * @return this, for chaining, not null
 333      */
 334     public DateTimeFormatterBuilder parseLenient() {
 335         appendInternal(SettingsParser.LENIENT);
 336         return this;
 337     }
 338 
 339     //-----------------------------------------------------------------------
 340     /**
 341      * Appends a default value for a field to the formatter for use in parsing.
 342      * <p>
 343      * This appends an instruction to the builder to inject a default value
 344      * into the parsed result. This is especially useful in conjunction with
 345      * optional parts of the formatter.
 346      * <p>
 347      * For example, consider a formatter that parses the year, followed by
 348      * an optional month, with a further optional day-of-month. Using such a
 349      * formatter would require the calling code to check whether a full date,
 350      * year-month or just a year had been parsed. This method can be used to
 351      * default the month and day-of-month to a sensible value, such as the
 352      * first of the month, allowing the calling code to always get a date.
 353      * <p>
 354      * During formatting, this method has no effect.
 355      * <p>
 356      * During parsing, the current state of the parse is inspected.
 357      * If the specified field has no associated value, because it has not been
 358      * parsed successfully at that point, then the specified value is injected
 359      * into the parse result. Injection is immediate, thus the field-value pair
 360      * will be visible to any subsequent elements in the formatter.
 361      * As such, this method is normally called at the end of the builder.
 362      *
 363      * @param field  the field to default the value of, not null
 364      * @param value  the value to default the field to
 365      * @return this, for chaining, not null
 366      */
 367     public DateTimeFormatterBuilder parseDefaulting(TemporalField field, long value) {
 368         Objects.requireNonNull(field, "field");
 369         appendInternal(new DefaultValueParser(field, value));
 370         return this;
 371     }
 372 
 373     //-----------------------------------------------------------------------
 374     /**
 375      * Appends the value of a date-time field to the formatter using a normal
 376      * output style.
 377      * <p>
 378      * The value of the field will be output during a format.
 379      * If the value cannot be obtained then an exception will be thrown.
 380      * <p>
 381      * The value will be printed as per the normal format of an integer value.
 382      * Only negative numbers will be signed. No padding will be added.
 383      * <p>
 384      * The parser for a variable width value such as this normally behaves greedily,
 385      * requiring one digit, but accepting as many digits as possible.
 386      * This behavior can be affected by 'adjacent value parsing'.
 387      * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details.
 388      *
 389      * @param field  the field to append, not null
 390      * @return this, for chaining, not null
 391      */
 392     public DateTimeFormatterBuilder appendValue(TemporalField field) {
 393         Objects.requireNonNull(field, "field");
 394         appendValue(new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL));
 395         return this;
 396     }
 397 
 398     /**
 399      * Appends the value of a date-time field to the formatter using a fixed
 400      * width, zero-padded approach.
 401      * <p>
 402      * The value of the field will be output during a format.
 403      * If the value cannot be obtained then an exception will be thrown.
 404      * <p>
 405      * The value will be zero-padded on the left. If the size of the value
 406      * means that it cannot be printed within the width then an exception is thrown.
 407      * If the value of the field is negative then an exception is thrown during formatting.
 408      * <p>
 409      * This method supports a special technique of parsing known as 'adjacent value parsing'.
 410      * This technique solves the problem where a value, variable or fixed width, is followed by one or more
 411      * fixed length values. The standard parser is greedy, and thus it would normally
 412      * steal the digits that are needed by the fixed width value parsers that follow the
 413      * variable width one.
 414      * <p>
 415      * No action is required to initiate 'adjacent value parsing'.
 416      * When a call to {@code appendValue} is made, the builder
 417      * enters adjacent value parsing setup mode. If the immediately subsequent method
 418      * call or calls on the same builder are for a fixed width value, then the parser will reserve
 419      * space so that the fixed width values can be parsed.
 420      * <p>
 421      * For example, consider {@code builder.appendValue(YEAR).appendValue(MONTH_OF_YEAR, 2);}
 422      * The year is a variable width parse of between 1 and 19 digits.
 423      * The month is a fixed width parse of 2 digits.
 424      * Because these were appended to the same builder immediately after one another,
 425      * the year parser will reserve two digits for the month to parse.
 426      * Thus, the text '201106' will correctly parse to a year of 2011 and a month of 6.
 427      * Without adjacent value parsing, the year would greedily parse all six digits and leave
 428      * nothing for the month.
 429      * <p>
 430      * Adjacent value parsing applies to each set of fixed width not-negative values in the parser
 431      * that immediately follow any kind of value, variable or fixed width.
 432      * Calling any other append method will end the setup of adjacent value parsing.
 433      * Thus, in the unlikely event that you need to avoid adjacent value parsing behavior,
 434      * simply add the {@code appendValue} to another {@code DateTimeFormatterBuilder}
 435      * and add that to this builder.
 436      * <p>
 437      * If adjacent parsing is active, then parsing must match exactly the specified
 438      * number of digits in both strict and lenient modes.
 439      * In addition, no positive or negative sign is permitted.
 440      *
 441      * @param field  the field to append, not null
 442      * @param width  the width of the printed field, from 1 to 19
 443      * @return this, for chaining, not null
 444      * @throws IllegalArgumentException if the width is invalid
 445      */
 446     public DateTimeFormatterBuilder appendValue(TemporalField field, int width) {
 447         Objects.requireNonNull(field, "field");
 448         if (width < 1 || width > 19) {
 449             throw new IllegalArgumentException("The width must be from 1 to 19 inclusive but was " + width);
 450         }
 451         NumberPrinterParser pp = new NumberPrinterParser(field, width, width, SignStyle.NOT_NEGATIVE);
 452         appendValue(pp);
 453         return this;
 454     }
 455 
 456     /**
 457      * Appends the value of a date-time field to the formatter providing full
 458      * control over formatting.
 459      * <p>
 460      * The value of the field will be output during a format.
 461      * If the value cannot be obtained then an exception will be thrown.
 462      * <p>
 463      * This method provides full control of the numeric formatting, including
 464      * zero-padding and the positive/negative sign.
 465      * <p>
 466      * The parser for a variable width value such as this normally behaves greedily,
 467      * accepting as many digits as possible.
 468      * This behavior can be affected by 'adjacent value parsing'.
 469      * See {@link #appendValue(java.time.temporal.TemporalField, int)} for full details.
 470      * <p>
 471      * In strict parsing mode, the minimum number of parsed digits is {@code minWidth}
 472      * and the maximum is {@code maxWidth}.
 473      * In lenient parsing mode, the minimum number of parsed digits is one
 474      * and the maximum is 19 (except as limited by adjacent value parsing).
 475      * <p>
 476      * If this method is invoked with equal minimum and maximum widths and a sign style of
 477      * {@code NOT_NEGATIVE} then it delegates to {@code appendValue(TemporalField,int)}.
 478      * In this scenario, the formatting and parsing behavior described there occur.
 479      *
 480      * @param field  the field to append, not null
 481      * @param minWidth  the minimum field width of the printed field, from 1 to 19
 482      * @param maxWidth  the maximum field width of the printed field, from 1 to 19
 483      * @param signStyle  the positive/negative output style, not null
 484      * @return this, for chaining, not null
 485      * @throws IllegalArgumentException if the widths are invalid
 486      */
 487     public DateTimeFormatterBuilder appendValue(
 488             TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) {
 489         if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) {
 490             return appendValue(field, maxWidth);
 491         }
 492         Objects.requireNonNull(field, "field");
 493         Objects.requireNonNull(signStyle, "signStyle");
 494         if (minWidth < 1 || minWidth > 19) {
 495             throw new IllegalArgumentException("The minimum width must be from 1 to 19 inclusive but was " + minWidth);
 496         }
 497         if (maxWidth < 1 || maxWidth > 19) {
 498             throw new IllegalArgumentException("The maximum width must be from 1 to 19 inclusive but was " + maxWidth);
 499         }
 500         if (maxWidth < minWidth) {
 501             throw new IllegalArgumentException("The maximum width must exceed or equal the minimum width but " +
 502                     maxWidth + " < " + minWidth);
 503         }
 504         NumberPrinterParser pp = new NumberPrinterParser(field, minWidth, maxWidth, signStyle);
 505         appendValue(pp);
 506         return this;
 507     }
 508 
 509     //-----------------------------------------------------------------------
 510     /**
 511      * Appends the reduced value of a date-time field to the formatter.
 512      * <p>
 513      * Since fields such as year vary by chronology, it is recommended to use the
 514      * {@link #appendValueReduced(TemporalField, int, int, ChronoLocalDate)} date}
 515      * variant of this method in most cases. This variant is suitable for
 516      * simple fields or working with only the ISO chronology.
 517      * <p>
 518      * For formatting, the {@code width} and {@code maxWidth} are used to
 519      * determine the number of characters to format.
 520      * If they are equal then the format is fixed width.
 521      * If the value of the field is within the range of the {@code baseValue} using
 522      * {@code width} characters then the reduced value is formatted otherwise the value is
 523      * truncated to fit {@code maxWidth}.
 524      * The rightmost characters are output to match the width, left padding with zero.
 525      * <p>
 526      * For strict parsing, the number of characters allowed by {@code width} to {@code maxWidth} are parsed.
 527      * For lenient parsing, the number of characters must be at least 1 and less than 10.
 528      * If the number of digits parsed is equal to {@code width} and the value is positive,
 529      * the value of the field is computed to be the first number greater than
 530      * or equal to the {@code baseValue} with the same least significant characters,
 531      * otherwise the value parsed is the field value.
 532      * This allows a reduced value to be entered for values in range of the baseValue
 533      * and width and absolute values can be entered for values outside the range.
 534      * <p>
 535      * For example, a base value of {@code 1980} and a width of {@code 2} will have
 536      * valid values from {@code 1980} to {@code 2079}.
 537      * During parsing, the text {@code "12"} will result in the value {@code 2012} as that
 538      * is the value within the range where the last two characters are "12".
 539      * By contrast, parsing the text {@code "1915"} will result in the value {@code 1915}.
 540      *
 541      * @param field  the field to append, not null
 542      * @param width  the field width of the printed and parsed field, from 1 to 10
 543      * @param maxWidth  the maximum field width of the printed field, from 1 to 10
 544      * @param baseValue  the base value of the range of valid values
 545      * @return this, for chaining, not null
 546      * @throws IllegalArgumentException if the width or base value is invalid
 547      */
 548     public DateTimeFormatterBuilder appendValueReduced(TemporalField field,
 549             int width, int maxWidth, int baseValue) {
 550         Objects.requireNonNull(field, "field");
 551         ReducedPrinterParser pp = new ReducedPrinterParser(field, width, maxWidth, baseValue, null);
 552         appendValue(pp);
 553         return this;
 554     }
 555 
 556     /**
 557      * Appends the reduced value of a date-time field to the formatter.
 558      * <p>
 559      * This is typically used for formatting and parsing a two digit year.
 560      * <p>
 561      * The base date is used to calculate the full value during parsing.
 562      * For example, if the base date is 1950-01-01 then parsed values for
 563      * a two digit year parse will be in the range 1950-01-01 to 2049-12-31.
 564      * Only the year would be extracted from the date, thus a base date of
 565      * 1950-08-25 would also parse to the range 1950-01-01 to 2049-12-31.
 566      * This behavior is necessary to support fields such as week-based-year
 567      * or other calendar systems where the parsed value does not align with
 568      * standard ISO years.
 569      * <p>
 570      * The exact behavior is as follows. Parse the full set of fields and
 571      * determine the effective chronology using the last chronology if
 572      * it appears more than once. Then convert the base date to the
 573      * effective chronology. Then extract the specified field from the
 574      * chronology-specific base date and use it to determine the
 575      * {@code baseValue} used below.
 576      * <p>
 577      * For formatting, the {@code width} and {@code maxWidth} are used to
 578      * determine the number of characters to format.
 579      * If they are equal then the format is fixed width.
 580      * If the value of the field is within the range of the {@code baseValue} using
 581      * {@code width} characters then the reduced value is formatted otherwise the value is
 582      * truncated to fit {@code maxWidth}.
 583      * The rightmost characters are output to match the width, left padding with zero.
 584      * <p>
 585      * For strict parsing, the number of characters allowed by {@code width} to {@code maxWidth} are parsed.
 586      * For lenient parsing, the number of characters must be at least 1 and less than 10.
 587      * If the number of digits parsed is equal to {@code width} and the value is positive,
 588      * the value of the field is computed to be the first number greater than
 589      * or equal to the {@code baseValue} with the same least significant characters,
 590      * otherwise the value parsed is the field value.
 591      * This allows a reduced value to be entered for values in range of the baseValue
 592      * and width and absolute values can be entered for values outside the range.
 593      * <p>
 594      * For example, a base value of {@code 1980} and a width of {@code 2} will have
 595      * valid values from {@code 1980} to {@code 2079}.
 596      * During parsing, the text {@code "12"} will result in the value {@code 2012} as that
 597      * is the value within the range where the last two characters are "12".
 598      * By contrast, parsing the text {@code "1915"} will result in the value {@code 1915}.
 599      *
 600      * @param field  the field to append, not null
 601      * @param width  the field width of the printed and parsed field, from 1 to 10
 602      * @param maxWidth  the maximum field width of the printed field, from 1 to 10
 603      * @param baseDate  the base date used to calculate the base value for the range
 604      *  of valid values in the parsed chronology, not null
 605      * @return this, for chaining, not null
 606      * @throws IllegalArgumentException if the width or base value is invalid
 607      */
 608     public DateTimeFormatterBuilder appendValueReduced(
 609             TemporalField field, int width, int maxWidth, ChronoLocalDate baseDate) {
 610         Objects.requireNonNull(field, "field");
 611         Objects.requireNonNull(baseDate, "baseDate");
 612         ReducedPrinterParser pp = new ReducedPrinterParser(field, width, maxWidth, 0, baseDate);
 613         appendValue(pp);
 614         return this;
 615     }
 616 
 617     /**
 618      * Appends a fixed or variable width printer-parser handling adjacent value mode.
 619      * If a PrinterParser is not active then the new PrinterParser becomes
 620      * the active PrinterParser.
 621      * Otherwise, the active PrinterParser is modified depending on the new PrinterParser.
 622      * If the new PrinterParser is fixed width and has sign style {@code NOT_NEGATIVE}
 623      * then its width is added to the active PP and
 624      * the new PrinterParser is forced to be fixed width.
 625      * If the new PrinterParser is variable width, the active PrinterParser is changed
 626      * to be fixed width and the new PrinterParser becomes the active PP.
 627      *
 628      * @param pp  the printer-parser, not null
 629      * @return this, for chaining, not null
 630      */
 631     private DateTimeFormatterBuilder appendValue(NumberPrinterParser pp) {
 632         if (active.valueParserIndex >= 0) {
 633             final int activeValueParser = active.valueParserIndex;
 634 
 635             // adjacent parsing mode, update setting in previous parsers
 636             NumberPrinterParser basePP = (NumberPrinterParser) active.printerParsers.get(activeValueParser);
 637             if (pp.minWidth == pp.maxWidth && pp.signStyle == SignStyle.NOT_NEGATIVE) {
 638                 // Append the width to the subsequentWidth of the active parser
 639                 basePP = basePP.withSubsequentWidth(pp.maxWidth);
 640                 // Append the new parser as a fixed width
 641                 appendInternal(pp.withFixedWidth());
 642                 // Retain the previous active parser
 643                 active.valueParserIndex = activeValueParser;
 644             } else {
 645                 // Modify the active parser to be fixed width
 646                 basePP = basePP.withFixedWidth();
 647                 // The new parser becomes the mew active parser
 648                 active.valueParserIndex = appendInternal(pp);
 649             }
 650             // Replace the modified parser with the updated one
 651             active.printerParsers.set(activeValueParser, basePP);
 652         } else {
 653             // The new Parser becomes the active parser
 654             active.valueParserIndex = appendInternal(pp);
 655         }
 656         return this;
 657     }
 658 
 659     //-----------------------------------------------------------------------
 660     /**
 661      * Appends the fractional value of a date-time field to the formatter.
 662      * <p>
 663      * The fractional value of the field will be output including the
 664      * preceding decimal point. The preceding value is not output.
 665      * For example, the second-of-minute value of 15 would be output as {@code .25}.
 666      * <p>
 667      * The width of the printed fraction can be controlled. Setting the
 668      * minimum width to zero will cause no output to be generated.
 669      * The printed fraction will have the minimum width necessary between
 670      * the minimum and maximum widths - trailing zeroes are omitted.
 671      * No rounding occurs due to the maximum width - digits are simply dropped.
 672      * <p>
 673      * When parsing in strict mode, the number of parsed digits must be between
 674      * the minimum and maximum width. In strict mode, if the minimum and maximum widths
 675      * are equal and there is no decimal point then the parser will
 676      * participate in adjacent value parsing, see
 677      * {@link appendValue(java.time.temporal.TemporalField, int)}. When parsing in lenient mode,
 678      * the minimum width is considered to be zero and the maximum is nine.
 679      * <p>
 680      * If the value cannot be obtained then an exception will be thrown.
 681      * If the value is negative an exception will be thrown.
 682      * If the field does not have a fixed set of valid values then an
 683      * exception will be thrown.
 684      * If the field value in the date-time to be printed is invalid it
 685      * cannot be printed and an exception will be thrown.
 686      *
 687      * @param field  the field to append, not null
 688      * @param minWidth  the minimum width of the field excluding the decimal point, from 0 to 9
 689      * @param maxWidth  the maximum width of the field excluding the decimal point, from 1 to 9
 690      * @param decimalPoint  whether to output the localized decimal point symbol
 691      * @return this, for chaining, not null
 692      * @throws IllegalArgumentException if the field has a variable set of valid values or
 693      *  either width is invalid
 694      */
 695     public DateTimeFormatterBuilder appendFraction(
 696             TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) {
 697         if (minWidth == maxWidth && decimalPoint == false) {
 698             // adjacent parsing
 699             appendValue(new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint));
 700         } else {
 701             appendInternal(new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint));
 702         }
 703         return this;
 704     }
 705 
 706     //-----------------------------------------------------------------------
 707     /**
 708      * Appends the text of a date-time field to the formatter using the full
 709      * text style.
 710      * <p>
 711      * The text of the field will be output during a format.
 712      * The value must be within the valid range of the field.
 713      * If the value cannot be obtained then an exception will be thrown.
 714      * If the field has no textual representation, then the numeric value will be used.
 715      * <p>
 716      * The value will be printed as per the normal format of an integer value.
 717      * Only negative numbers will be signed. No padding will be added.
 718      *
 719      * @param field  the field to append, not null
 720      * @return this, for chaining, not null
 721      */
 722     public DateTimeFormatterBuilder appendText(TemporalField field) {
 723         return appendText(field, TextStyle.FULL);
 724     }
 725 
 726     /**
 727      * Appends the text of a date-time field to the formatter.
 728      * <p>
 729      * The text of the field will be output during a format.
 730      * The value must be within the valid range of the field.
 731      * If the value cannot be obtained then an exception will be thrown.
 732      * If the field has no textual representation, then the numeric value will be used.
 733      * <p>
 734      * The value will be printed as per the normal format of an integer value.
 735      * Only negative numbers will be signed. No padding will be added.
 736      *
 737      * @param field  the field to append, not null
 738      * @param textStyle  the text style to use, not null
 739      * @return this, for chaining, not null
 740      */
 741     public DateTimeFormatterBuilder appendText(TemporalField field, TextStyle textStyle) {
 742         Objects.requireNonNull(field, "field");
 743         Objects.requireNonNull(textStyle, "textStyle");
 744         appendInternal(new TextPrinterParser(field, textStyle, DateTimeTextProvider.getInstance()));
 745         return this;
 746     }
 747 
 748     /**
 749      * Appends the text of a date-time field to the formatter using the specified
 750      * map to supply the text.
 751      * <p>
 752      * The standard text outputting methods use the localized text in the JDK.
 753      * This method allows that text to be specified directly.
 754      * The supplied map is not validated by the builder to ensure that formatting or
 755      * parsing is possible, thus an invalid map may throw an error during later use.
 756      * <p>
 757      * Supplying the map of text provides considerable flexibility in formatting and parsing.
 758      * For example, a legacy application might require or supply the months of the
 759      * year as "JNY", "FBY", "MCH" etc. These do not match the standard set of text
 760      * for localized month names. Using this method, a map can be created which
 761      * defines the connection between each value and the text:
 762      * <pre>
 763      * Map&lt;Long, String&gt; map = new HashMap&lt;&gt;();
 764      * map.put(1L, "JNY");
 765      * map.put(2L, "FBY");
 766      * map.put(3L, "MCH");
 767      * ...
 768      * builder.appendText(MONTH_OF_YEAR, map);
 769      * </pre>
 770      * <p>
 771      * Other uses might be to output the value with a suffix, such as "1st", "2nd", "3rd",
 772      * or as Roman numerals "I", "II", "III", "IV".
 773      * <p>
 774      * During formatting, the value is obtained and checked that it is in the valid range.
 775      * If text is not available for the value then it is output as a number.
 776      * During parsing, the parser will match against the map of text and numeric values.
 777      *
 778      * @param field  the field to append, not null
 779      * @param textLookup  the map from the value to the text
 780      * @return this, for chaining, not null
 781      */
 782     public DateTimeFormatterBuilder appendText(TemporalField field, Map<Long, String> textLookup) {
 783         Objects.requireNonNull(field, "field");
 784         Objects.requireNonNull(textLookup, "textLookup");
 785         Map<Long, String> copy = new LinkedHashMap<>(textLookup);
 786         Map<TextStyle, Map<Long, String>> map = Collections.singletonMap(TextStyle.FULL, copy);
 787         final LocaleStore store = new LocaleStore(map);
 788         DateTimeTextProvider provider = new DateTimeTextProvider() {
 789             @Override
 790             public String getText(TemporalField field, long value, TextStyle style, Locale locale) {
 791                 return store.getText(value, style);
 792             }
 793             @Override
 794             public Iterator<Entry<String, Long>> getTextIterator(TemporalField field, TextStyle style, Locale locale) {
 795                 return store.getTextIterator(style);
 796             }
 797         };
 798         appendInternal(new TextPrinterParser(field, TextStyle.FULL, provider));
 799         return this;
 800     }
 801 
 802     //-----------------------------------------------------------------------
 803     /**
 804      * Appends an instant using ISO-8601 to the formatter, formatting fractional
 805      * digits in groups of three.
 806      * <p>
 807      * Instants have a fixed output format.
 808      * They are converted to a date-time with a zone-offset of UTC and formatted
 809      * using the standard ISO-8601 format.
 810      * With this method, formatting nano-of-second outputs zero, three, six
 811      * or nine digits as necessary.
 812      * The localized decimal style is not used.
 813      * <p>
 814      * The instant is obtained using {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
 815      * and optionally {@code NANO_OF_SECOND}. The value of {@code INSTANT_SECONDS}
 816      * may be outside the maximum range of {@code LocalDateTime}.
 817      * <p>
 818      * The {@linkplain ResolverStyle resolver style} has no effect on instant parsing.
 819      * The end-of-day time of '24:00' is handled as midnight at the start of the following day.
 820      * The leap-second time of '23:59:59' is handled to some degree, see
 821      * {@link DateTimeFormatter#parsedLeapSecond()} for full details.
 822      * <p>
 823      * An alternative to this method is to format/parse the instant as a single
 824      * epoch-seconds value. That is achieved using {@code appendValue(INSTANT_SECONDS)}.
 825      *
 826      * @return this, for chaining, not null
 827      */
 828     public DateTimeFormatterBuilder appendInstant() {
 829         appendInternal(new InstantPrinterParser(-2));
 830         return this;
 831     }
 832 
 833     /**
 834      * Appends an instant using ISO-8601 to the formatter with control over
 835      * the number of fractional digits.
 836      * <p>
 837      * Instants have a fixed output format, although this method provides some
 838      * control over the fractional digits. They are converted to a date-time
 839      * with a zone-offset of UTC and printed using the standard ISO-8601 format.
 840      * The localized decimal style is not used.
 841      * <p>
 842      * The {@code fractionalDigits} parameter allows the output of the fractional
 843      * second to be controlled. Specifying zero will cause no fractional digits
 844      * to be output. From 1 to 9 will output an increasing number of digits, using
 845      * zero right-padding if necessary. The special value -1 is used to output as
 846      * many digits as necessary to avoid any trailing zeroes.
 847      * <p>
 848      * When parsing in strict mode, the number of parsed digits must match the
 849      * fractional digits. When parsing in lenient mode, any number of fractional
 850      * digits from zero to nine are accepted.
 851      * <p>
 852      * The instant is obtained using {@link ChronoField#INSTANT_SECONDS INSTANT_SECONDS}
 853      * and optionally {@code NANO_OF_SECOND}. The value of {@code INSTANT_SECONDS}
 854      * may be outside the maximum range of {@code LocalDateTime}.
 855      * <p>
 856      * The {@linkplain ResolverStyle resolver style} has no effect on instant parsing.
 857      * The end-of-day time of '24:00' is handled as midnight at the start of the following day.
 858      * The leap-second time of '23:59:60' is handled to some degree, see
 859      * {@link DateTimeFormatter#parsedLeapSecond()} for full details.
 860      * <p>
 861      * An alternative to this method is to format/parse the instant as a single
 862      * epoch-seconds value. That is achieved using {@code appendValue(INSTANT_SECONDS)}.
 863      *
 864      * @param fractionalDigits  the number of fractional second digits to format with,
 865      *  from 0 to 9, or -1 to use as many digits as necessary
 866      * @return this, for chaining, not null
 867      * @throws IllegalArgumentException if the number of fractional digits is invalid
 868      */
 869     public DateTimeFormatterBuilder appendInstant(int fractionalDigits) {
 870         if (fractionalDigits < -1 || fractionalDigits > 9) {
 871             throw new IllegalArgumentException("The fractional digits must be from -1 to 9 inclusive but was " + fractionalDigits);
 872         }
 873         appendInternal(new InstantPrinterParser(fractionalDigits));
 874         return this;
 875     }
 876 
 877     //-----------------------------------------------------------------------
 878     /**
 879      * Appends the zone offset, such as '+01:00', to the formatter.
 880      * <p>
 881      * This appends an instruction to format/parse the offset ID to the builder.
 882      * This is equivalent to calling {@code appendOffset("+HH:mm:ss", "Z")}.
 883      * See {@link #appendOffset(String, String)} for details on formatting
 884      * and parsing.
 885      *
 886      * @return this, for chaining, not null
 887      */
 888     public DateTimeFormatterBuilder appendOffsetId() {
 889         appendInternal(OffsetIdPrinterParser.INSTANCE_ID_Z);
 890         return this;
 891     }
 892 
 893     /**
 894      * Appends the zone offset, such as '+01:00', to the formatter.
 895      * <p>
 896      * This appends an instruction to format/parse the offset ID to the builder.
 897      * <p>
 898      * During formatting, the offset is obtained using a mechanism equivalent
 899      * to querying the temporal with {@link TemporalQueries#offset()}.
 900      * It will be printed using the format defined below.
 901      * If the offset cannot be obtained then an exception is thrown unless the
 902      * section of the formatter is optional.
 903      * <p>
 904      * When parsing in strict mode, the input must contain the mandatory
 905      * and optional elements are defined by the specified pattern.
 906      * If the offset cannot be parsed then an exception is thrown unless
 907      * the section of the formatter is optional.
 908      * <p>
 909      * When parsing in lenient mode, only the hours are mandatory - minutes
 910      * and seconds are optional. The colons are required if the specified
 911      * pattern contains a colon. If the specified pattern is "+HH", the
 912      * presence of colons is determined by whether the character after the
 913      * hour digits is a colon or not.
 914      * If the offset cannot be parsed then an exception is thrown unless
 915      * the section of the formatter is optional.
 916      * <p>
 917      * The format of the offset is controlled by a pattern which must be one
 918      * of the following:
 919      * <ul>
 920      * <li>{@code +HH} - hour only, ignoring minute and second
 921      * <li>{@code +HHmm} - hour, with minute if non-zero, ignoring second, no colon
 922      * <li>{@code +HH:mm} - hour, with minute if non-zero, ignoring second, with colon
 923      * <li>{@code +HHMM} - hour and minute, ignoring second, no colon
 924      * <li>{@code +HH:MM} - hour and minute, ignoring second, with colon
 925      * <li>{@code +HHMMss} - hour and minute, with second if non-zero, no colon
 926      * <li>{@code +HH:MM:ss} - hour and minute, with second if non-zero, with colon
 927      * <li>{@code +HHMMSS} - hour, minute and second, no colon
 928      * <li>{@code +HH:MM:SS} - hour, minute and second, with colon
 929      * <li>{@code +HHmmss} - hour, with minute if non-zero or with minute and
 930      * second if non-zero, no colon
 931      * <li>{@code +HH:mm:ss} - hour, with minute if non-zero or with minute and
 932      * second if non-zero, with colon
 933      * <li>{@code +H} - hour only, ignoring minute and second
 934      * <li>{@code +Hmm} - hour, with minute if non-zero, ignoring second, no colon
 935      * <li>{@code +H:mm} - hour, with minute if non-zero, ignoring second, with colon
 936      * <li>{@code +HMM} - hour and minute, ignoring second, no colon
 937      * <li>{@code +H:MM} - hour and minute, ignoring second, with colon
 938      * <li>{@code +HMMss} - hour and minute, with second if non-zero, no colon
 939      * <li>{@code +H:MM:ss} - hour and minute, with second if non-zero, with colon
 940      * <li>{@code +HMMSS} - hour, minute and second, no colon
 941      * <li>{@code +H:MM:SS} - hour, minute and second, with colon
 942      * <li>{@code +Hmmss} - hour, with minute if non-zero or with minute and
 943      * second if non-zero, no colon
 944      * <li>{@code +H:mm:ss} - hour, with minute if non-zero or with minute and
 945      * second if non-zero, with colon
 946      * </ul>
 947      * Patterns containing "HH" will format and parse a two digit hour,
 948      * zero-padded if necessary. Patterns containing "H" will format with no
 949      * zero-padding, and parse either one or two digits.
 950      * In lenient mode, the parser will be greedy and parse the maximum digits possible.
 951      * The "no offset" text controls what text is printed when the total amount of
 952      * the offset fields to be output is zero.
 953      * Example values would be 'Z', '+00:00', 'UTC' or 'GMT'.
 954      * Three formats are accepted for parsing UTC - the "no offset" text, and the
 955      * plus and minus versions of zero defined by the pattern.
 956      *
 957      * @param pattern  the pattern to use, not null
 958      * @param noOffsetText  the text to use when the offset is zero, not null
 959      * @return this, for chaining, not null
 960      * @throws IllegalArgumentException if the pattern is invalid
 961      */
 962     public DateTimeFormatterBuilder appendOffset(String pattern, String noOffsetText) {
 963         appendInternal(new OffsetIdPrinterParser(pattern, noOffsetText));
 964         return this;
 965     }
 966 
 967     /**
 968      * Appends the localized zone offset, such as 'GMT+01:00', to the formatter.
 969      * <p>
 970      * This appends a localized zone offset to the builder, the format of the
 971      * localized offset is controlled by the specified {@link FormatStyle style}
 972      * to this method:
 973      * <ul>
 974      * <li>{@link TextStyle#FULL full} - formats with localized offset text, such
 975      * as 'GMT, 2-digit hour and minute field, optional second field if non-zero,
 976      * and colon.
 977      * <li>{@link TextStyle#SHORT short} - formats with localized offset text,
 978      * such as 'GMT, hour without leading zero, optional 2-digit minute and
 979      * second if non-zero, and colon.
 980      * </ul>
 981      * <p>
 982      * During formatting, the offset is obtained using a mechanism equivalent
 983      * to querying the temporal with {@link TemporalQueries#offset()}.
 984      * If the offset cannot be obtained then an exception is thrown unless the
 985      * section of the formatter is optional.
 986      * <p>
 987      * During parsing, the offset is parsed using the format defined above.
 988      * If the offset cannot be parsed then an exception is thrown unless the
 989      * section of the formatter is optional.
 990      *
 991      * @param style  the format style to use, not null
 992      * @return this, for chaining, not null
 993      * @throws IllegalArgumentException if style is neither {@link TextStyle#FULL
 994      * full} nor {@link TextStyle#SHORT short}
 995      */
 996     public DateTimeFormatterBuilder appendLocalizedOffset(TextStyle style) {
 997         Objects.requireNonNull(style, "style");
 998         if (style != TextStyle.FULL && style != TextStyle.SHORT) {
 999             throw new IllegalArgumentException("Style must be either full or short");
1000         }
1001         appendInternal(new LocalizedOffsetIdPrinterParser(style));
1002         return this;
1003     }
1004 
1005     //-----------------------------------------------------------------------
1006     /**
1007      * Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to the formatter.
1008      * <p>
1009      * This appends an instruction to format/parse the zone ID to the builder.
1010      * The zone ID is obtained in a strict manner suitable for {@code ZonedDateTime}.
1011      * By contrast, {@code OffsetDateTime} does not have a zone ID suitable
1012      * for use with this method, see {@link #appendZoneOrOffsetId()}.
1013      * <p>
1014      * During formatting, the zone is obtained using a mechanism equivalent
1015      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1016      * It will be printed using the result of {@link ZoneId#getId()}.
1017      * If the zone cannot be obtained then an exception is thrown unless the
1018      * section of the formatter is optional.
1019      * <p>
1020      * During parsing, the text must match a known zone or offset.
1021      * There are two types of zone ID, offset-based, such as '+01:30' and
1022      * region-based, such as 'Europe/London'. These are parsed differently.
1023      * If the parse starts with '+', '-', 'UT', 'UTC' or 'GMT', then the parser
1024      * expects an offset-based zone and will not match region-based zones.
1025      * The offset ID, such as '+02:30', may be at the start of the parse,
1026      * or prefixed by  'UT', 'UTC' or 'GMT'. The offset ID parsing is
1027      * equivalent to using {@link #appendOffset(String, String)} using the
1028      * arguments 'HH:MM:ss' and the no offset string '0'.
1029      * If the parse starts with 'UT', 'UTC' or 'GMT', and the parser cannot
1030      * match a following offset ID, then {@link ZoneOffset#UTC} is selected.
1031      * In all other cases, the list of known region-based zones is used to
1032      * find the longest available match. If no match is found, and the parse
1033      * starts with 'Z', then {@code ZoneOffset.UTC} is selected.
1034      * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
1035      * <p>
1036      * For example, the following will parse:
1037      * <pre>
1038      *   "Europe/London"           -- ZoneId.of("Europe/London")
1039      *   "Z"                       -- ZoneOffset.UTC
1040      *   "UT"                      -- ZoneId.of("UT")
1041      *   "UTC"                     -- ZoneId.of("UTC")
1042      *   "GMT"                     -- ZoneId.of("GMT")
1043      *   "+01:30"                  -- ZoneOffset.of("+01:30")
1044      *   "UT+01:30"                -- ZoneOffset.of("+01:30")
1045      *   "UTC+01:30"               -- ZoneOffset.of("+01:30")
1046      *   "GMT+01:30"               -- ZoneOffset.of("+01:30")
1047      * </pre>
1048      *
1049      * @return this, for chaining, not null
1050      * @see #appendZoneRegionId()
1051      */
1052     public DateTimeFormatterBuilder appendZoneId() {
1053         appendInternal(new ZoneIdPrinterParser(TemporalQueries.zoneId(), "ZoneId()"));
1054         return this;
1055     }
1056 
1057     /**
1058      * Appends the time-zone region ID, such as 'Europe/Paris', to the formatter,
1059      * rejecting the zone ID if it is a {@code ZoneOffset}.
1060      * <p>
1061      * This appends an instruction to format/parse the zone ID to the builder
1062      * only if it is a region-based ID.
1063      * <p>
1064      * During formatting, the zone is obtained using a mechanism equivalent
1065      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1066      * If the zone is a {@code ZoneOffset} or it cannot be obtained then
1067      * an exception is thrown unless the section of the formatter is optional.
1068      * If the zone is not an offset, then the zone will be printed using
1069      * the zone ID from {@link ZoneId#getId()}.
1070      * <p>
1071      * During parsing, the text must match a known zone or offset.
1072      * There are two types of zone ID, offset-based, such as '+01:30' and
1073      * region-based, such as 'Europe/London'. These are parsed differently.
1074      * If the parse starts with '+', '-', 'UT', 'UTC' or 'GMT', then the parser
1075      * expects an offset-based zone and will not match region-based zones.
1076      * The offset ID, such as '+02:30', may be at the start of the parse,
1077      * or prefixed by  'UT', 'UTC' or 'GMT'. The offset ID parsing is
1078      * equivalent to using {@link #appendOffset(String, String)} using the
1079      * arguments 'HH:MM:ss' and the no offset string '0'.
1080      * If the parse starts with 'UT', 'UTC' or 'GMT', and the parser cannot
1081      * match a following offset ID, then {@link ZoneOffset#UTC} is selected.
1082      * In all other cases, the list of known region-based zones is used to
1083      * find the longest available match. If no match is found, and the parse
1084      * starts with 'Z', then {@code ZoneOffset.UTC} is selected.
1085      * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
1086      * <p>
1087      * For example, the following will parse:
1088      * <pre>
1089      *   "Europe/London"           -- ZoneId.of("Europe/London")
1090      *   "Z"                       -- ZoneOffset.UTC
1091      *   "UT"                      -- ZoneId.of("UT")
1092      *   "UTC"                     -- ZoneId.of("UTC")
1093      *   "GMT"                     -- ZoneId.of("GMT")
1094      *   "+01:30"                  -- ZoneOffset.of("+01:30")
1095      *   "UT+01:30"                -- ZoneOffset.of("+01:30")
1096      *   "UTC+01:30"               -- ZoneOffset.of("+01:30")
1097      *   "GMT+01:30"               -- ZoneOffset.of("+01:30")
1098      * </pre>
1099      * <p>
1100      * Note that this method is identical to {@code appendZoneId()} except
1101      * in the mechanism used to obtain the zone.
1102      * Note also that parsing accepts offsets, whereas formatting will never
1103      * produce one.
1104      *
1105      * @return this, for chaining, not null
1106      * @see #appendZoneId()
1107      */
1108     public DateTimeFormatterBuilder appendZoneRegionId() {
1109         appendInternal(new ZoneIdPrinterParser(QUERY_REGION_ONLY, "ZoneRegionId()"));
1110         return this;
1111     }
1112 
1113     /**
1114      * Appends the time-zone ID, such as 'Europe/Paris' or '+02:00', to
1115      * the formatter, using the best available zone ID.
1116      * <p>
1117      * This appends an instruction to format/parse the best available
1118      * zone or offset ID to the builder.
1119      * The zone ID is obtained in a lenient manner that first attempts to
1120      * find a true zone ID, such as that on {@code ZonedDateTime}, and
1121      * then attempts to find an offset, such as that on {@code OffsetDateTime}.
1122      * <p>
1123      * During formatting, the zone is obtained using a mechanism equivalent
1124      * to querying the temporal with {@link TemporalQueries#zone()}.
1125      * It will be printed using the result of {@link ZoneId#getId()}.
1126      * If the zone cannot be obtained then an exception is thrown unless the
1127      * section of the formatter is optional.
1128      * <p>
1129      * During parsing, the text must match a known zone or offset.
1130      * There are two types of zone ID, offset-based, such as '+01:30' and
1131      * region-based, such as 'Europe/London'. These are parsed differently.
1132      * If the parse starts with '+', '-', 'UT', 'UTC' or 'GMT', then the parser
1133      * expects an offset-based zone and will not match region-based zones.
1134      * The offset ID, such as '+02:30', may be at the start of the parse,
1135      * or prefixed by  'UT', 'UTC' or 'GMT'. The offset ID parsing is
1136      * equivalent to using {@link #appendOffset(String, String)} using the
1137      * arguments 'HH:MM:ss' and the no offset string '0'.
1138      * If the parse starts with 'UT', 'UTC' or 'GMT', and the parser cannot
1139      * match a following offset ID, then {@link ZoneOffset#UTC} is selected.
1140      * In all other cases, the list of known region-based zones is used to
1141      * find the longest available match. If no match is found, and the parse
1142      * starts with 'Z', then {@code ZoneOffset.UTC} is selected.
1143      * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
1144      * <p>
1145      * For example, the following will parse:
1146      * <pre>
1147      *   "Europe/London"           -- ZoneId.of("Europe/London")
1148      *   "Z"                       -- ZoneOffset.UTC
1149      *   "UT"                      -- ZoneId.of("UT")
1150      *   "UTC"                     -- ZoneId.of("UTC")
1151      *   "GMT"                     -- ZoneId.of("GMT")
1152      *   "+01:30"                  -- ZoneOffset.of("+01:30")
1153      *   "UT+01:30"                -- ZoneOffset.of("UT+01:30")
1154      *   "UTC+01:30"               -- ZoneOffset.of("UTC+01:30")
1155      *   "GMT+01:30"               -- ZoneOffset.of("GMT+01:30")
1156      * </pre>
1157      * <p>
1158      * Note that this method is identical to {@code appendZoneId()} except
1159      * in the mechanism used to obtain the zone.
1160      *
1161      * @return this, for chaining, not null
1162      * @see #appendZoneId()
1163      */
1164     public DateTimeFormatterBuilder appendZoneOrOffsetId() {
1165         appendInternal(new ZoneIdPrinterParser(TemporalQueries.zone(), "ZoneOrOffsetId()"));
1166         return this;
1167     }
1168 
1169     /**
1170      * Appends the time-zone name, such as 'British Summer Time', to the formatter.
1171      * <p>
1172      * This appends an instruction to format/parse the textual name of the zone to
1173      * the builder.
1174      * <p>
1175      * During formatting, the zone is obtained using a mechanism equivalent
1176      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1177      * If the zone is a {@code ZoneOffset} it will be printed using the
1178      * result of {@link ZoneOffset#getId()}.
1179      * If the zone is not an offset, the textual name will be looked up
1180      * for the locale set in the {@link DateTimeFormatter}.
1181      * If the temporal object being printed represents an instant, or if it is a
1182      * local date-time that is not in a daylight saving gap or overlap then
1183      * the text will be the summer or winter time text as appropriate.
1184      * If the lookup for text does not find any suitable result, then the
1185      * {@link ZoneId#getId() ID} will be printed.
1186      * If the zone cannot be obtained then an exception is thrown unless the
1187      * section of the formatter is optional.
1188      * <p>
1189      * During parsing, either the textual zone name, the zone ID or the offset
1190      * is accepted. Many textual zone names are not unique, such as CST can be
1191      * for both "Central Standard Time" and "China Standard Time". In this
1192      * situation, the zone id will be determined by the region information from
1193      * formatter's  {@link DateTimeFormatter#getLocale() locale} and the standard
1194      * zone id for that area, for example, America/New_York for the America Eastern
1195      * zone. The {@link #appendZoneText(TextStyle, Set)} may be used
1196      * to specify a set of preferred {@link ZoneId} in this situation.
1197      *
1198      * @param textStyle  the text style to use, not null
1199      * @return this, for chaining, not null
1200      */
1201     public DateTimeFormatterBuilder appendZoneText(TextStyle textStyle) {
1202         appendInternal(new ZoneTextPrinterParser(textStyle, null, false));
1203         return this;
1204     }
1205 
1206     /**
1207      * Appends the time-zone name, such as 'British Summer Time', to the formatter.
1208      * <p>
1209      * This appends an instruction to format/parse the textual name of the zone to
1210      * the builder.
1211      * <p>
1212      * During formatting, the zone is obtained using a mechanism equivalent
1213      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1214      * If the zone is a {@code ZoneOffset} it will be printed using the
1215      * result of {@link ZoneOffset#getId()}.
1216      * If the zone is not an offset, the textual name will be looked up
1217      * for the locale set in the {@link DateTimeFormatter}.
1218      * If the temporal object being printed represents an instant, or if it is a
1219      * local date-time that is not in a daylight saving gap or overlap, then the text
1220      * will be the summer or winter time text as appropriate.
1221      * If the lookup for text does not find any suitable result, then the
1222      * {@link ZoneId#getId() ID} will be printed.
1223      * If the zone cannot be obtained then an exception is thrown unless the
1224      * section of the formatter is optional.
1225      * <p>
1226      * During parsing, either the textual zone name, the zone ID or the offset
1227      * is accepted. Many textual zone names are not unique, such as CST can be
1228      * for both "Central Standard Time" and "China Standard Time". In this
1229      * situation, the zone id will be determined by the region information from
1230      * formatter's  {@link DateTimeFormatter#getLocale() locale} and the standard
1231      * zone id for that area, for example, America/New_York for the America Eastern
1232      * zone. This method also allows a set of preferred {@link ZoneId} to be
1233      * specified for parsing. The matched preferred zone id will be used if the
1234      * textural zone name being parsed is not unique.
1235      * <p>
1236      * If the zone cannot be parsed then an exception is thrown unless the
1237      * section of the formatter is optional.
1238      *
1239      * @param textStyle  the text style to use, not null
1240      * @param preferredZones  the set of preferred zone ids, not null
1241      * @return this, for chaining, not null
1242      */
1243     public DateTimeFormatterBuilder appendZoneText(TextStyle textStyle,
1244                                                    Set<ZoneId> preferredZones) {
1245         Objects.requireNonNull(preferredZones, "preferredZones");
1246         appendInternal(new ZoneTextPrinterParser(textStyle, preferredZones, false));
1247         return this;
1248     }
1249     //----------------------------------------------------------------------
1250     /**
1251      * Appends the generic time-zone name, such as 'Pacific Time', to the formatter.
1252      * <p>
1253      * This appends an instruction to format/parse the generic textual
1254      * name of the zone to the builder. The generic name is the same throughout the whole
1255      * year, ignoring any daylight saving changes. For example, 'Pacific Time' is the
1256      * generic name, whereas 'Pacific Standard Time' and 'Pacific Daylight Time' are the
1257      * specific names, see {@link #appendZoneText(TextStyle)}.
1258      * <p>
1259      * During formatting, the zone is obtained using a mechanism equivalent
1260      * to querying the temporal with {@link TemporalQueries#zoneId()}.
1261      * If the zone is a {@code ZoneOffset} it will be printed using the
1262      * result of {@link ZoneOffset#getId()}.
1263      * If the zone is not an offset, the textual name will be looked up
1264      * for the locale set in the {@link DateTimeFormatter}.
1265      * If the lookup for text does not find any suitable result, then the
1266      * {@link ZoneId#getId() ID} will be printed.
1267      * If the zone cannot be obtained then an exception is thrown unless the
1268      * section of the formatter is optional.
1269      * <p>
1270      * During parsing, either the textual zone name, the zone ID or the offset
1271      * is accepted. Many textual zone names are not unique, such as CST can be
1272      * for both "Central Standard Time" and "China Standard Time". In this
1273      * situation, the zone id will be determined by the region information from
1274      * formatter's  {@link DateTimeFormatter#getLocale() locale} and the standard
1275      * zone id for that area, for example, America/New_York for the America Eastern zone.
1276      * The {@link #appendGenericZoneText(TextStyle, Set)} may be used
1277      * to specify a set of preferred {@link ZoneId} in this situation.
1278      *
1279      * @param textStyle  the text style to use, not null
1280      * @return this, for chaining, not null

1281      */
1282     public DateTimeFormatterBuilder appendGenericZoneText(TextStyle textStyle) {
1283         appendInternal(new ZoneTextPrinterParser(textStyle, null, true));
1284         return this;
1285     }
1286 
1287     /**
1288      * Appends the generic time-zone name, such as 'Pacific Time', to the formatter.
1289      * <p>
1290      * This appends an instruction to format/parse the generic textual
1291      * name of the zone to the builder. The generic name is the same throughout the whole
1292      * year, ignoring any daylight saving changes. For example, 'Pacific Time' is the
1293      * generic name, whereas 'Pacific Standard Time' and 'Pacific Daylight Time' are the
1294      * specific names, see {@link #appendZoneText(TextStyle)}.
1295      * <p>
1296      * This method also allows a set of preferred {@link ZoneId} to be
1297      * specified for parsing. The matched preferred zone id will be used if the
1298      * textural zone name being parsed is not unique.
1299      * <p>
1300      * See {@link #appendGenericZoneText(TextStyle)} for details about
1301      * formatting and parsing.
1302      *
1303      * @param textStyle  the text style to use, not null
1304      * @param preferredZones  the set of preferred zone ids, not null
1305      * @return this, for chaining, not null

1306      */
1307     public DateTimeFormatterBuilder appendGenericZoneText(TextStyle textStyle,
1308                                                           Set<ZoneId> preferredZones) {
1309         appendInternal(new ZoneTextPrinterParser(textStyle, preferredZones, true));
1310         return this;
1311     }
1312 
1313     //-----------------------------------------------------------------------
1314     /**
1315      * Appends the chronology ID, such as 'ISO' or 'ThaiBuddhist', to the formatter.
1316      * <p>
1317      * This appends an instruction to format/parse the chronology ID to the builder.
1318      * <p>
1319      * During formatting, the chronology is obtained using a mechanism equivalent
1320      * to querying the temporal with {@link TemporalQueries#chronology()}.
1321      * It will be printed using the result of {@link Chronology#getId()}.
1322      * If the chronology cannot be obtained then an exception is thrown unless the
1323      * section of the formatter is optional.
1324      * <p>
1325      * During parsing, the chronology is parsed and must match one of the chronologies
1326      * in {@link Chronology#getAvailableChronologies()}.
1327      * If the chronology cannot be parsed then an exception is thrown unless the
1328      * section of the formatter is optional.
1329      * The parser uses the {@linkplain #parseCaseInsensitive() case sensitive} setting.
1330      *
1331      * @return this, for chaining, not null
1332      */
1333     public DateTimeFormatterBuilder appendChronologyId() {
1334         appendInternal(new ChronoPrinterParser(null));
1335         return this;
1336     }
1337 
1338     /**
1339      * Appends the chronology name to the formatter.
1340      * <p>
1341      * The calendar system name will be output during a format.
1342      * If the chronology cannot be obtained then an exception will be thrown.
1343      *
1344      * @param textStyle  the text style to use, not null
1345      * @return this, for chaining, not null
1346      */
1347     public DateTimeFormatterBuilder appendChronologyText(TextStyle textStyle) {
1348         Objects.requireNonNull(textStyle, "textStyle");
1349         appendInternal(new ChronoPrinterParser(textStyle));
1350         return this;
1351     }
1352 
1353     //-----------------------------------------------------------------------
1354     /**
1355      * Appends a localized date-time pattern to the formatter.
1356      * <p>
1357      * This appends a localized section to the builder, suitable for outputting
1358      * a date, time or date-time combination. The format of the localized
1359      * section is lazily looked up based on four items:
1360      * <ul>
1361      * <li>the {@code dateStyle} specified to this method
1362      * <li>the {@code timeStyle} specified to this method
1363      * <li>the {@code Locale} of the {@code DateTimeFormatter}
1364      * <li>the {@code Chronology}, selecting the best available
1365      * </ul>
1366      * During formatting, the chronology is obtained from the temporal object
1367      * being formatted, which may have been overridden by
1368      * {@link DateTimeFormatter#withChronology(Chronology)}.
1369      * The {@code FULL} and {@code LONG} styles typically require a time-zone.
1370      * When formatting using these styles, a {@code ZoneId} must be available,
1371      * either by using {@code ZonedDateTime} or {@link DateTimeFormatter#withZone}.
1372      * <p>
1373      * During parsing, if a chronology has already been parsed, then it is used.
1374      * Otherwise the default from {@code DateTimeFormatter.withChronology(Chronology)}
1375      * is used, with {@code IsoChronology} as the fallback.
1376      * <p>
1377      * Note that this method provides similar functionality to methods on
1378      * {@code DateFormat} such as {@link java.text.DateFormat#getDateTimeInstance(int, int)}.
1379      *
1380      * @param dateStyle  the date style to use, null means no date required
1381      * @param timeStyle  the time style to use, null means no time required
1382      * @return this, for chaining, not null
1383      * @throws IllegalArgumentException if both the date and time styles are null
1384      */
1385     public DateTimeFormatterBuilder appendLocalized(FormatStyle dateStyle, FormatStyle timeStyle) {
1386         if (dateStyle == null && timeStyle == null) {
1387             throw new IllegalArgumentException("Either the date or time style must be non-null");
1388         }
1389         appendInternal(new LocalizedPrinterParser(dateStyle, timeStyle));
1390         return this;
1391     }
1392 
1393     //-----------------------------------------------------------------------
1394     /**
1395      * Appends a character literal to the formatter.
1396      * <p>
1397      * This character will be output during a format.
1398      *
1399      * @param literal  the literal to append, not null
1400      * @return this, for chaining, not null
1401      */
1402     public DateTimeFormatterBuilder appendLiteral(char literal) {
1403         appendInternal(new CharLiteralPrinterParser(literal));
1404         return this;
1405     }
1406 
1407     /**
1408      * Appends a string literal to the formatter.
1409      * <p>
1410      * This string will be output during a format.
1411      * <p>
1412      * If the literal is empty, nothing is added to the formatter.
1413      *
1414      * @param literal  the literal to append, not null
1415      * @return this, for chaining, not null
1416      */
1417     public DateTimeFormatterBuilder appendLiteral(String literal) {
1418         Objects.requireNonNull(literal, "literal");
1419         if (literal.length() > 0) {
1420             if (literal.length() == 1) {
1421                 appendInternal(new CharLiteralPrinterParser(literal.charAt(0)));
1422             } else {
1423                 appendInternal(new StringLiteralPrinterParser(literal));
1424             }
1425         }
1426         return this;
1427     }
1428 
1429     //-----------------------------------------------------------------------
1430     /**
1431      * Appends all the elements of a formatter to the builder.
1432      * <p>
1433      * This method has the same effect as appending each of the constituent
1434      * parts of the formatter directly to this builder.
1435      *
1436      * @param formatter  the formatter to add, not null
1437      * @return this, for chaining, not null
1438      */
1439     public DateTimeFormatterBuilder append(DateTimeFormatter formatter) {
1440         Objects.requireNonNull(formatter, "formatter");
1441         appendInternal(formatter.toPrinterParser(false));
1442         return this;
1443     }
1444 
1445     /**
1446      * Appends a formatter to the builder which will optionally format/parse.
1447      * <p>
1448      * This method has the same effect as appending each of the constituent
1449      * parts directly to this builder surrounded by an {@link #optionalStart()} and
1450      * {@link #optionalEnd()}.
1451      * <p>
1452      * The formatter will format if data is available for all the fields contained within it.
1453      * The formatter will parse if the string matches, otherwise no error is returned.
1454      *
1455      * @param formatter  the formatter to add, not null
1456      * @return this, for chaining, not null
1457      */
1458     public DateTimeFormatterBuilder appendOptional(DateTimeFormatter formatter) {
1459         Objects.requireNonNull(formatter, "formatter");
1460         appendInternal(formatter.toPrinterParser(true));
1461         return this;
1462     }
1463 
1464     //-----------------------------------------------------------------------
1465     /**
1466      * Appends the elements defined by the specified pattern to the builder.
1467      * <p>
1468      * All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters.
1469      * The characters '#', '{' and '}' are reserved for future use.
1470      * The characters '[' and ']' indicate optional patterns.
1471      * The following pattern letters are defined:
1472      * <pre>
1473      *  Symbol  Meaning                     Presentation      Examples
1474      *  ------  -------                     ------------      -------
1475      *   G       era                         text              AD; Anno Domini; A
1476      *   u       year                        year              2004; 04
1477      *   y       year-of-era                 year              2004; 04
1478      *   D       day-of-year                 number            189
1479      *   M/L     month-of-year               number/text       7; 07; Jul; July; J
1480      *   d       day-of-month                number            10
1481      *   g       modified-julian-day         number            2451334
1482      *
1483      *   Q/q     quarter-of-year             number/text       3; 03; Q3; 3rd quarter
1484      *   Y       week-based-year             year              1996; 96
1485      *   w       week-of-week-based-year     number            27
1486      *   W       week-of-month               number            4
1487      *   E       day-of-week                 text              Tue; Tuesday; T
1488      *   e/c     localized day-of-week       number/text       2; 02; Tue; Tuesday; T
1489      *   F       day-of-week-in-month        number            3
1490      *
1491      *   a       am-pm-of-day                text              PM
1492      *   h       clock-hour-of-am-pm (1-12)  number            12
1493      *   K       hour-of-am-pm (0-11)        number            0
1494      *   k       clock-hour-of-day (1-24)    number            24
1495      *
1496      *   H       hour-of-day (0-23)          number            0
1497      *   m       minute-of-hour              number            30
1498      *   s       second-of-minute            number            55
1499      *   S       fraction-of-second          fraction          978
1500      *   A       milli-of-day                number            1234
1501      *   n       nano-of-second              number            987654321
1502      *   N       nano-of-day                 number            1234000000
1503      *
1504      *   V       time-zone ID                zone-id           America/Los_Angeles; Z; -08:30
1505      *   v       generic time-zone name      zone-name         PT, Pacific Time
1506      *   z       time-zone name              zone-name         Pacific Standard Time; PST
1507      *   O       localized zone-offset       offset-O          GMT+8; GMT+08:00; UTC-08:00;
1508      *   X       zone-offset 'Z' for zero    offset-X          Z; -08; -0830; -08:30; -083015; -08:30:15
1509      *   x       zone-offset                 offset-x          +0000; -08; -0830; -08:30; -083015; -08:30:15
1510      *   Z       zone-offset                 offset-Z          +0000; -0800; -08:00
1511      *
1512      *   p       pad next                    pad modifier      1
1513      *
1514      *   '       escape for text             delimiter
1515      *   ''      single quote                literal           '
1516      *   [       optional section start
1517      *   ]       optional section end
1518      *   #       reserved for future use
1519      *   {       reserved for future use
1520      *   }       reserved for future use
1521      * </pre>
1522      * <p>
1523      * The count of pattern letters determine the format.
1524      * See <a href="DateTimeFormatter.html#patterns">DateTimeFormatter</a> for a user-focused description of the patterns.
1525      * The following tables define how the pattern letters map to the builder.
1526      * <p>
1527      * <b>Date fields</b>: Pattern letters to output a date.
1528      * <pre>
1529      *  Pattern  Count  Equivalent builder methods
1530      *  -------  -----  --------------------------
1531      *    G       1      appendText(ChronoField.ERA, TextStyle.SHORT)
1532      *    GG      2      appendText(ChronoField.ERA, TextStyle.SHORT)
1533      *    GGG     3      appendText(ChronoField.ERA, TextStyle.SHORT)
1534      *    GGGG    4      appendText(ChronoField.ERA, TextStyle.FULL)
1535      *    GGGGG   5      appendText(ChronoField.ERA, TextStyle.NARROW)
1536      *
1537      *    u       1      appendValue(ChronoField.YEAR, 1, 19, SignStyle.NORMAL)
1538      *    uu      2      appendValueReduced(ChronoField.YEAR, 2, 2000)
1539      *    uuu     3      appendValue(ChronoField.YEAR, 3, 19, SignStyle.NORMAL)
1540      *    u..u    4..n   appendValue(ChronoField.YEAR, n, 19, SignStyle.EXCEEDS_PAD)
1541      *    y       1      appendValue(ChronoField.YEAR_OF_ERA, 1, 19, SignStyle.NORMAL)
1542      *    yy      2      appendValueReduced(ChronoField.YEAR_OF_ERA, 2, 2000)
1543      *    yyy     3      appendValue(ChronoField.YEAR_OF_ERA, 3, 19, SignStyle.NORMAL)
1544      *    y..y    4..n   appendValue(ChronoField.YEAR_OF_ERA, n, 19, SignStyle.EXCEEDS_PAD)
1545      *    Y       1      append special localized WeekFields element for numeric week-based-year
1546      *    YY      2      append special localized WeekFields element for reduced numeric week-based-year 2 digits
1547      *    YYY     3      append special localized WeekFields element for numeric week-based-year (3, 19, SignStyle.NORMAL)
1548      *    Y..Y    4..n   append special localized WeekFields element for numeric week-based-year (n, 19, SignStyle.EXCEEDS_PAD)
1549      *
1550      *    Q       1      appendValue(IsoFields.QUARTER_OF_YEAR)
1551      *    QQ      2      appendValue(IsoFields.QUARTER_OF_YEAR, 2)
1552      *    QQQ     3      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.SHORT)
1553      *    QQQQ    4      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.FULL)
1554      *    QQQQQ   5      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.NARROW)
1555      *    q       1      appendValue(IsoFields.QUARTER_OF_YEAR)
1556      *    qq      2      appendValue(IsoFields.QUARTER_OF_YEAR, 2)
1557      *    qqq     3      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.SHORT_STANDALONE)
1558      *    qqqq    4      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.FULL_STANDALONE)
1559      *    qqqqq   5      appendText(IsoFields.QUARTER_OF_YEAR, TextStyle.NARROW_STANDALONE)
1560      *
1561      *    M       1      appendValue(ChronoField.MONTH_OF_YEAR)
1562      *    MM      2      appendValue(ChronoField.MONTH_OF_YEAR, 2)
1563      *    MMM     3      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT)
1564      *    MMMM    4      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.FULL)
1565      *    MMMMM   5      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.NARROW)
1566      *    L       1      appendValue(ChronoField.MONTH_OF_YEAR)
1567      *    LL      2      appendValue(ChronoField.MONTH_OF_YEAR, 2)
1568      *    LLL     3      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT_STANDALONE)
1569      *    LLLL    4      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.FULL_STANDALONE)
1570      *    LLLLL   5      appendText(ChronoField.MONTH_OF_YEAR, TextStyle.NARROW_STANDALONE)
1571      *
1572      *    w       1      append special localized WeekFields element for numeric week-of-year
1573      *    ww      2      append special localized WeekFields element for numeric week-of-year, zero-padded
1574      *    W       1      append special localized WeekFields element for numeric week-of-month
1575      *    d       1      appendValue(ChronoField.DAY_OF_MONTH)
1576      *    dd      2      appendValue(ChronoField.DAY_OF_MONTH, 2)
1577      *    D       1      appendValue(ChronoField.DAY_OF_YEAR)
1578      *    DD      2      appendValue(ChronoField.DAY_OF_YEAR, 2, 3, SignStyle.NOT_NEGATIVE)
1579      *    DDD     3      appendValue(ChronoField.DAY_OF_YEAR, 3)
1580      *    F       1      appendValue(ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH)
1581      *    g..g    1..n   appendValue(JulianFields.MODIFIED_JULIAN_DAY, n, 19, SignStyle.NORMAL)
1582      *    E       1      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
1583      *    EE      2      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
1584      *    EEE     3      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
1585      *    EEEE    4      appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL)
1586      *    EEEEE   5      appendText(ChronoField.DAY_OF_WEEK, TextStyle.NARROW)
1587      *    e       1      append special localized WeekFields element for numeric day-of-week
1588      *    ee      2      append special localized WeekFields element for numeric day-of-week, zero-padded
1589      *    eee     3      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT)
1590      *    eeee    4      appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL)
1591      *    eeeee   5      appendText(ChronoField.DAY_OF_WEEK, TextStyle.NARROW)
1592      *    c       1      append special localized WeekFields element for numeric day-of-week
1593      *    ccc     3      appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT_STANDALONE)
1594      *    cccc    4      appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL_STANDALONE)
1595      *    ccccc   5      appendText(ChronoField.DAY_OF_WEEK, TextStyle.NARROW_STANDALONE)
1596      * </pre>
1597      * <p>
1598      * <b>Time fields</b>: Pattern letters to output a time.
1599      * <pre>
1600      *  Pattern  Count  Equivalent builder methods
1601      *  -------  -----  --------------------------
1602      *    a       1      appendText(ChronoField.AMPM_OF_DAY, TextStyle.SHORT)
1603      *    h       1      appendValue(ChronoField.CLOCK_HOUR_OF_AMPM)
1604      *    hh      2      appendValue(ChronoField.CLOCK_HOUR_OF_AMPM, 2)
1605      *    H       1      appendValue(ChronoField.HOUR_OF_DAY)
1606      *    HH      2      appendValue(ChronoField.HOUR_OF_DAY, 2)
1607      *    k       1      appendValue(ChronoField.CLOCK_HOUR_OF_DAY)
1608      *    kk      2      appendValue(ChronoField.CLOCK_HOUR_OF_DAY, 2)
1609      *    K       1      appendValue(ChronoField.HOUR_OF_AMPM)
1610      *    KK      2      appendValue(ChronoField.HOUR_OF_AMPM, 2)
1611      *    m       1      appendValue(ChronoField.MINUTE_OF_HOUR)
1612      *    mm      2      appendValue(ChronoField.MINUTE_OF_HOUR, 2)
1613      *    s       1      appendValue(ChronoField.SECOND_OF_MINUTE)
1614      *    ss      2      appendValue(ChronoField.SECOND_OF_MINUTE, 2)
1615      *
1616      *    S..S    1..n   appendFraction(ChronoField.NANO_OF_SECOND, n, n, false)
1617      *    A..A    1..n   appendValue(ChronoField.MILLI_OF_DAY, n, 19, SignStyle.NOT_NEGATIVE)
1618      *    n..n    1..n   appendValue(ChronoField.NANO_OF_SECOND, n, 19, SignStyle.NOT_NEGATIVE)
1619      *    N..N    1..n   appendValue(ChronoField.NANO_OF_DAY, n, 19, SignStyle.NOT_NEGATIVE)
1620      * </pre>
1621      * <p>
1622      * <b>Zone ID</b>: Pattern letters to output {@code ZoneId}.
1623      * <pre>
1624      *  Pattern  Count  Equivalent builder methods
1625      *  -------  -----  --------------------------
1626      *    VV      2      appendZoneId()
1627      *    v       1      appendGenericZoneText(TextStyle.SHORT)
1628      *    vvvv    4      appendGenericZoneText(TextStyle.FULL)
1629      *    z       1      appendZoneText(TextStyle.SHORT)
1630      *    zz      2      appendZoneText(TextStyle.SHORT)
1631      *    zzz     3      appendZoneText(TextStyle.SHORT)
1632      *    zzzz    4      appendZoneText(TextStyle.FULL)
1633      * </pre>
1634      * <p>
1635      * <b>Zone offset</b>: Pattern letters to output {@code ZoneOffset}.
1636      * <pre>
1637      *  Pattern  Count  Equivalent builder methods
1638      *  -------  -----  --------------------------
1639      *    O       1      appendLocalizedOffset(TextStyle.SHORT)
1640      *    OOOO    4      appendLocalizedOffset(TextStyle.FULL)
1641      *    X       1      appendOffset("+HHmm","Z")
1642      *    XX      2      appendOffset("+HHMM","Z")
1643      *    XXX     3      appendOffset("+HH:MM","Z")
1644      *    XXXX    4      appendOffset("+HHMMss","Z")
1645      *    XXXXX   5      appendOffset("+HH:MM:ss","Z")
1646      *    x       1      appendOffset("+HHmm","+00")
1647      *    xx      2      appendOffset("+HHMM","+0000")
1648      *    xxx     3      appendOffset("+HH:MM","+00:00")
1649      *    xxxx    4      appendOffset("+HHMMss","+0000")
1650      *    xxxxx   5      appendOffset("+HH:MM:ss","+00:00")
1651      *    Z       1      appendOffset("+HHMM","+0000")
1652      *    ZZ      2      appendOffset("+HHMM","+0000")
1653      *    ZZZ     3      appendOffset("+HHMM","+0000")
1654      *    ZZZZ    4      appendLocalizedOffset(TextStyle.FULL)
1655      *    ZZZZZ   5      appendOffset("+HH:MM:ss","Z")
1656      * </pre>
1657      * <p>
1658      * <b>Modifiers</b>: Pattern letters that modify the rest of the pattern:
1659      * <pre>
1660      *  Pattern  Count  Equivalent builder methods
1661      *  -------  -----  --------------------------
1662      *    [       1      optionalStart()
1663      *    ]       1      optionalEnd()
1664      *    p..p    1..n   padNext(n)
1665      * </pre>
1666      * <p>
1667      * Any sequence of letters not specified above, unrecognized letter or
1668      * reserved character will throw an exception.
1669      * Future versions may add to the set of patterns.
1670      * It is recommended to use single quotes around all characters that you want
1671      * to output directly to ensure that future changes do not break your application.
1672      * <p>
1673      * Note that the pattern string is similar, but not identical, to
1674      * {@link java.text.SimpleDateFormat SimpleDateFormat}.
1675      * The pattern string is also similar, but not identical, to that defined by the
1676      * Unicode Common Locale Data Repository (CLDR/LDML).
1677      * Pattern letters 'X' and 'u' are aligned with Unicode CLDR/LDML.
1678      * By contrast, {@code SimpleDateFormat} uses 'u' for the numeric day of week.
1679      * Pattern letters 'y' and 'Y' parse years of two digits and more than 4 digits differently.
1680      * Pattern letters 'n', 'A', 'N', and 'p' are added.
1681      * Number types will reject large numbers.
1682      *
1683      * @param pattern  the pattern to add, not null
1684      * @return this, for chaining, not null
1685      * @throws IllegalArgumentException if the pattern is invalid
1686      */
1687     public DateTimeFormatterBuilder appendPattern(String pattern) {
1688         Objects.requireNonNull(pattern, "pattern");
1689         parsePattern(pattern);
1690         return this;
1691     }
1692 
1693     private void parsePattern(String pattern) {
1694         for (int pos = 0; pos < pattern.length(); pos++) {
1695             char cur = pattern.charAt(pos);
1696             if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) {
1697                 int start = pos++;
1698                 for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++);  // short loop
1699                 int count = pos - start;
1700                 // padding
1701                 if (cur == 'p') {
1702                     int pad = 0;
1703                     if (pos < pattern.length()) {
1704                         cur = pattern.charAt(pos);
1705                         if ((cur >= 'A' && cur <= 'Z') || (cur >= 'a' && cur <= 'z')) {
1706                             pad = count;
1707                             start = pos++;
1708                             for ( ; pos < pattern.length() && pattern.charAt(pos) == cur; pos++);  // short loop
1709                             count = pos - start;
1710                         }
1711                     }
1712                     if (pad == 0) {
1713                         throw new IllegalArgumentException(
1714                                 "Pad letter 'p' must be followed by valid pad pattern: " + pattern);
1715                     }
1716                     padNext(pad); // pad and continue parsing
1717                 }
1718                 // main rules
1719                 TemporalField field = FIELD_MAP.get(cur);
1720                 if (field != null) {
1721                     parseField(cur, count, field);
1722                 } else if (cur == 'z') {
1723                     if (count > 4) {
1724                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1725                     } else if (count == 4) {
1726                         appendZoneText(TextStyle.FULL);
1727                     } else {
1728                         appendZoneText(TextStyle.SHORT);
1729                     }
1730                 } else if (cur == 'V') {
1731                     if (count != 2) {
1732                         throw new IllegalArgumentException("Pattern letter count must be 2: " + cur);
1733                     }
1734                     appendZoneId();
1735                 } else if (cur == 'v') {
1736                     if (count == 1) {
1737                         appendGenericZoneText(TextStyle.SHORT);
1738                     } else if (count == 4) {
1739                         appendGenericZoneText(TextStyle.FULL);
1740                     } else {
1741                         throw new IllegalArgumentException("Wrong number of  pattern letters: " + cur);
1742                     }
1743                 } else if (cur == 'Z') {
1744                     if (count < 4) {
1745                         appendOffset("+HHMM", "+0000");
1746                     } else if (count == 4) {
1747                         appendLocalizedOffset(TextStyle.FULL);
1748                     } else if (count == 5) {
1749                         appendOffset("+HH:MM:ss","Z");
1750                     } else {
1751                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1752                     }
1753                 } else if (cur == 'O') {
1754                     if (count == 1) {
1755                         appendLocalizedOffset(TextStyle.SHORT);
1756                     } else if (count == 4) {
1757                         appendLocalizedOffset(TextStyle.FULL);
1758                     } else {
1759                         throw new IllegalArgumentException("Pattern letter count must be 1 or 4: " + cur);
1760                     }
1761                 } else if (cur == 'X') {
1762                     if (count > 5) {
1763                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1764                     }
1765                     appendOffset(OffsetIdPrinterParser.PATTERNS[count + (count == 1 ? 0 : 1)], "Z");
1766                 } else if (cur == 'x') {
1767                     if (count > 5) {
1768                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1769                     }
1770                     String zero = (count == 1 ? "+00" : (count % 2 == 0 ? "+0000" : "+00:00"));
1771                     appendOffset(OffsetIdPrinterParser.PATTERNS[count + (count == 1 ? 0 : 1)], zero);
1772                 } else if (cur == 'W') {
1773                     // Fields defined by Locale
1774                     if (count > 1) {
1775                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1776                     }
1777                     appendValue(new WeekBasedFieldPrinterParser(cur, count, count, count));
1778                 } else if (cur == 'w') {
1779                     // Fields defined by Locale
1780                     if (count > 2) {
1781                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1782                     }
1783                     appendValue(new WeekBasedFieldPrinterParser(cur, count, count, 2));
1784                 } else if (cur == 'Y') {
1785                     // Fields defined by Locale
1786                     if (count == 2) {
1787                         appendValue(new WeekBasedFieldPrinterParser(cur, count, count, 2));
1788                     } else {
1789                         appendValue(new WeekBasedFieldPrinterParser(cur, count, count, 19));
1790                     }
1791                 } else {
1792                     throw new IllegalArgumentException("Unknown pattern letter: " + cur);
1793                 }
1794                 pos--;
1795 
1796             } else if (cur == '\'') {
1797                 // parse literals
1798                 int start = pos++;
1799                 for ( ; pos < pattern.length(); pos++) {
1800                     if (pattern.charAt(pos) == '\'') {
1801                         if (pos + 1 < pattern.length() && pattern.charAt(pos + 1) == '\'') {
1802                             pos++;
1803                         } else {
1804                             break;  // end of literal
1805                         }
1806                     }
1807                 }
1808                 if (pos >= pattern.length()) {
1809                     throw new IllegalArgumentException("Pattern ends with an incomplete string literal: " + pattern);
1810                 }
1811                 String str = pattern.substring(start + 1, pos);
1812                 if (str.length() == 0) {
1813                     appendLiteral('\'');
1814                 } else {
1815                     appendLiteral(str.replace("''", "'"));
1816                 }
1817 
1818             } else if (cur == '[') {
1819                 optionalStart();
1820 
1821             } else if (cur == ']') {
1822                 if (active.parent == null) {
1823                     throw new IllegalArgumentException("Pattern invalid as it contains ] without previous [");
1824                 }
1825                 optionalEnd();
1826 
1827             } else if (cur == '{' || cur == '}' || cur == '#') {
1828                 throw new IllegalArgumentException("Pattern includes reserved character: '" + cur + "'");
1829             } else {
1830                 appendLiteral(cur);
1831             }
1832         }
1833     }
1834 
1835     @SuppressWarnings("fallthrough")
1836     private void parseField(char cur, int count, TemporalField field) {
1837         boolean standalone = false;
1838         switch (cur) {
1839             case 'u':
1840             case 'y':
1841                 if (count == 2) {
1842                     appendValueReduced(field, 2, 2, ReducedPrinterParser.BASE_DATE);
1843                 } else if (count < 4) {
1844                     appendValue(field, count, 19, SignStyle.NORMAL);
1845                 } else {
1846                     appendValue(field, count, 19, SignStyle.EXCEEDS_PAD);
1847                 }
1848                 break;
1849             case 'c':
1850                 if (count == 1) {
1851                     appendValue(new WeekBasedFieldPrinterParser(cur, count, count, count));
1852                     break;
1853                 } else if (count == 2) {
1854                     throw new IllegalArgumentException("Invalid pattern \"cc\"");
1855                 }
1856                 /*fallthrough*/
1857             case 'L':
1858             case 'q':
1859                 standalone = true;
1860                 /*fallthrough*/
1861             case 'M':
1862             case 'Q':
1863             case 'E':
1864             case 'e':
1865                 switch (count) {
1866                     case 1:
1867                     case 2:
1868                         if (cur == 'e') {
1869                             appendValue(new WeekBasedFieldPrinterParser(cur, count, count, count));
1870                         } else if (cur == 'E') {
1871                             appendText(field, TextStyle.SHORT);
1872                         } else {
1873                             if (count == 1) {
1874                                 appendValue(field);
1875                             } else {
1876                                 appendValue(field, 2);
1877                             }
1878                         }
1879                         break;
1880                     case 3:
1881                         appendText(field, standalone ? TextStyle.SHORT_STANDALONE : TextStyle.SHORT);
1882                         break;
1883                     case 4:
1884                         appendText(field, standalone ? TextStyle.FULL_STANDALONE : TextStyle.FULL);
1885                         break;
1886                     case 5:
1887                         appendText(field, standalone ? TextStyle.NARROW_STANDALONE : TextStyle.NARROW);
1888                         break;
1889                     default:
1890                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1891                 }
1892                 break;
1893             case 'a':
1894                 if (count == 1) {
1895                     appendText(field, TextStyle.SHORT);
1896                 } else {
1897                     throw new IllegalArgumentException("Too many pattern letters: " + cur);
1898                 }
1899                 break;
1900             case 'G':
1901                 switch (count) {
1902                     case 1:
1903                     case 2:
1904                     case 3:
1905                         appendText(field, TextStyle.SHORT);
1906                         break;
1907                     case 4:
1908                         appendText(field, TextStyle.FULL);
1909                         break;
1910                     case 5:
1911                         appendText(field, TextStyle.NARROW);
1912                         break;
1913                     default:
1914                         throw new IllegalArgumentException("Too many pattern letters: " + cur);
1915                 }
1916                 break;
1917             case 'S':
1918                 appendFraction(NANO_OF_SECOND, count, count, false);
1919                 break;
1920             case 'F':
1921                 if (count == 1) {
1922                     appendValue(field);
1923                 } else {
1924                     throw new IllegalArgumentException("Too many pattern letters: " + cur);
1925                 }
1926                 break;
1927             case 'd':
1928             case 'h':
1929             case 'H':
1930             case 'k':
1931             case 'K':
1932             case 'm':
1933             case 's':
1934                 if (count == 1) {
1935                     appendValue(field);
1936                 } else if (count == 2) {
1937                     appendValue(field, count);
1938                 } else {
1939                     throw new IllegalArgumentException("Too many pattern letters: " + cur);
1940                 }
1941                 break;
1942             case 'D':
1943                 if (count == 1) {
1944                     appendValue(field);
1945                 } else if (count == 2 || count == 3) {
1946                     appendValue(field, count, 3, SignStyle.NOT_NEGATIVE);
1947                 } else {
1948                     throw new IllegalArgumentException("Too many pattern letters: " + cur);
1949                 }
1950                 break;
1951             case 'g':
1952                 appendValue(field, count, 19, SignStyle.NORMAL);
1953                 break;
1954             case 'A':
1955             case 'n':
1956             case 'N':
1957                 appendValue(field, count, 19, SignStyle.NOT_NEGATIVE);
1958                 break;
1959             default:
1960                 if (count == 1) {
1961                     appendValue(field);
1962                 } else {
1963                     appendValue(field, count);
1964                 }
1965                 break;
1966         }
1967     }
1968 
1969     /** Map of letters to fields. */
1970     private static final Map<Character, TemporalField> FIELD_MAP = new HashMap<>();
1971     static {
1972         // SDF = SimpleDateFormat
1973         FIELD_MAP.put('G', ChronoField.ERA);                       // SDF, LDML (different to both for 1/2 chars)
1974         FIELD_MAP.put('y', ChronoField.YEAR_OF_ERA);               // SDF, LDML
1975         FIELD_MAP.put('u', ChronoField.YEAR);                      // LDML (different in SDF)
1976         FIELD_MAP.put('Q', IsoFields.QUARTER_OF_YEAR);             // LDML (removed quarter from 310)
1977         FIELD_MAP.put('q', IsoFields.QUARTER_OF_YEAR);             // LDML (stand-alone)
1978         FIELD_MAP.put('M', ChronoField.MONTH_OF_YEAR);             // SDF, LDML
1979         FIELD_MAP.put('L', ChronoField.MONTH_OF_YEAR);             // SDF, LDML (stand-alone)
1980         FIELD_MAP.put('D', ChronoField.DAY_OF_YEAR);               // SDF, LDML
1981         FIELD_MAP.put('d', ChronoField.DAY_OF_MONTH);              // SDF, LDML
1982         FIELD_MAP.put('F', ChronoField.ALIGNED_DAY_OF_WEEK_IN_MONTH);  // SDF, LDML
1983         FIELD_MAP.put('E', ChronoField.DAY_OF_WEEK);               // SDF, LDML (different to both for 1/2 chars)
1984         FIELD_MAP.put('c', ChronoField.DAY_OF_WEEK);               // LDML (stand-alone)
1985         FIELD_MAP.put('e', ChronoField.DAY_OF_WEEK);               // LDML (needs localized week number)
1986         FIELD_MAP.put('a', ChronoField.AMPM_OF_DAY);               // SDF, LDML
1987         FIELD_MAP.put('H', ChronoField.HOUR_OF_DAY);               // SDF, LDML
1988         FIELD_MAP.put('k', ChronoField.CLOCK_HOUR_OF_DAY);         // SDF, LDML
1989         FIELD_MAP.put('K', ChronoField.HOUR_OF_AMPM);              // SDF, LDML
1990         FIELD_MAP.put('h', ChronoField.CLOCK_HOUR_OF_AMPM);        // SDF, LDML
1991         FIELD_MAP.put('m', ChronoField.MINUTE_OF_HOUR);            // SDF, LDML
1992         FIELD_MAP.put('s', ChronoField.SECOND_OF_MINUTE);          // SDF, LDML
1993         FIELD_MAP.put('S', ChronoField.NANO_OF_SECOND);            // LDML (SDF uses milli-of-second number)
1994         FIELD_MAP.put('A', ChronoField.MILLI_OF_DAY);              // LDML
1995         FIELD_MAP.put('n', ChronoField.NANO_OF_SECOND);            // 310 (proposed for LDML)
1996         FIELD_MAP.put('N', ChronoField.NANO_OF_DAY);               // 310 (proposed for LDML)
1997         FIELD_MAP.put('g', JulianFields.MODIFIED_JULIAN_DAY);
1998         // 310 - z - time-zone names, matches LDML and SimpleDateFormat 1 to 4
1999         // 310 - Z - matches SimpleDateFormat and LDML
2000         // 310 - V - time-zone id, matches LDML
2001         // 310 - v - general timezone names, not matching exactly with LDML because LDML specify to fall back
2002         //           to 'VVVV' if general-nonlocation unavailable but here it's not falling back because of lack of data
2003         // 310 - p - prefix for padding
2004         // 310 - X - matches LDML, almost matches SDF for 1, exact match 2&3, extended 4&5
2005         // 310 - x - matches LDML
2006         // 310 - w, W, and Y are localized forms matching LDML
2007         // LDML - U - cycle year name, not supported by 310 yet
2008         // LDML - l - deprecated
2009         // LDML - j - not relevant
2010     }
2011 
2012     //-----------------------------------------------------------------------
2013     /**
2014      * Causes the next added printer/parser to pad to a fixed width using a space.
2015      * <p>
2016      * This padding will pad to a fixed width using spaces.
2017      * <p>
2018      * During formatting, the decorated element will be output and then padded
2019      * to the specified width. An exception will be thrown during formatting if
2020      * the pad width is exceeded.
2021      * <p>
2022      * During parsing, the padding and decorated element are parsed.
2023      * If parsing is lenient, then the pad width is treated as a maximum.
2024      * The padding is parsed greedily. Thus, if the decorated element starts with
2025      * the pad character, it will not be parsed.
2026      *
2027      * @param padWidth  the pad width, 1 or greater
2028      * @return this, for chaining, not null
2029      * @throws IllegalArgumentException if pad width is too small
2030      */
2031     public DateTimeFormatterBuilder padNext(int padWidth) {
2032         return padNext(padWidth, ' ');
2033     }
2034 
2035     /**
2036      * Causes the next added printer/parser to pad to a fixed width.
2037      * <p>
2038      * This padding is intended for padding other than zero-padding.
2039      * Zero-padding should be achieved using the appendValue methods.
2040      * <p>
2041      * During formatting, the decorated element will be output and then padded
2042      * to the specified width. An exception will be thrown during formatting if
2043      * the pad width is exceeded.
2044      * <p>
2045      * During parsing, the padding and decorated element are parsed.
2046      * If parsing is lenient, then the pad width is treated as a maximum.
2047      * If parsing is case insensitive, then the pad character is matched ignoring case.
2048      * The padding is parsed greedily. Thus, if the decorated element starts with
2049      * the pad character, it will not be parsed.
2050      *
2051      * @param padWidth  the pad width, 1 or greater
2052      * @param padChar  the pad character
2053      * @return this, for chaining, not null
2054      * @throws IllegalArgumentException if pad width is too small
2055      */
2056     public DateTimeFormatterBuilder padNext(int padWidth, char padChar) {
2057         if (padWidth < 1) {
2058             throw new IllegalArgumentException("The pad width must be at least one but was " + padWidth);
2059         }
2060         active.padNextWidth = padWidth;
2061         active.padNextChar = padChar;
2062         active.valueParserIndex = -1;
2063         return this;
2064     }
2065 
2066     //-----------------------------------------------------------------------
2067     /**
2068      * Mark the start of an optional section.
2069      * <p>
2070      * The output of formatting can include optional sections, which may be nested.
2071      * An optional section is started by calling this method and ended by calling
2072      * {@link #optionalEnd()} or by ending the build process.
2073      * <p>
2074      * All elements in the optional section are treated as optional.
2075      * During formatting, the section is only output if data is available in the
2076      * {@code TemporalAccessor} for all the elements in the section.
2077      * During parsing, the whole section may be missing from the parsed string.
2078      * <p>
2079      * For example, consider a builder setup as
2080      * {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2)}.
2081      * The optional section ends automatically at the end of the builder.
2082      * During formatting, the minute will only be output if its value can be obtained from the date-time.
2083      * During parsing, the input will be successfully parsed whether the minute is present or not.
2084      *
2085      * @return this, for chaining, not null
2086      */
2087     public DateTimeFormatterBuilder optionalStart() {
2088         active.valueParserIndex = -1;
2089         active = new DateTimeFormatterBuilder(active, true);
2090         return this;
2091     }
2092 
2093     /**
2094      * Ends an optional section.
2095      * <p>
2096      * The output of formatting can include optional sections, which may be nested.
2097      * An optional section is started by calling {@link #optionalStart()} and ended
2098      * using this method (or at the end of the builder).
2099      * <p>
2100      * Calling this method without having previously called {@code optionalStart}
2101      * will throw an exception.
2102      * Calling this method immediately after calling {@code optionalStart} has no effect
2103      * on the formatter other than ending the (empty) optional section.
2104      * <p>
2105      * All elements in the optional section are treated as optional.
2106      * During formatting, the section is only output if data is available in the
2107      * {@code TemporalAccessor} for all the elements in the section.
2108      * During parsing, the whole section may be missing from the parsed string.
2109      * <p>
2110      * For example, consider a builder setup as
2111      * {@code builder.appendValue(HOUR_OF_DAY,2).optionalStart().appendValue(MINUTE_OF_HOUR,2).optionalEnd()}.
2112      * During formatting, the minute will only be output if its value can be obtained from the date-time.
2113      * During parsing, the input will be successfully parsed whether the minute is present or not.
2114      *
2115      * @return this, for chaining, not null
2116      * @throws IllegalStateException if there was no previous call to {@code optionalStart}
2117      */
2118     public DateTimeFormatterBuilder optionalEnd() {
2119         if (active.parent == null) {
2120             throw new IllegalStateException("Cannot call optionalEnd() as there was no previous call to optionalStart()");
2121         }
2122         if (active.printerParsers.size() > 0) {
2123             CompositePrinterParser cpp = new CompositePrinterParser(active.printerParsers, active.optional);
2124             active = active.parent;
2125             appendInternal(cpp);
2126         } else {
2127             active = active.parent;
2128         }
2129         return this;
2130     }
2131 
2132     //-----------------------------------------------------------------------
2133     /**
2134      * Appends a printer and/or parser to the internal list handling padding.
2135      *
2136      * @param pp  the printer-parser to add, not null
2137      * @return the index into the active parsers list
2138      */
2139     private int appendInternal(DateTimePrinterParser pp) {
2140         Objects.requireNonNull(pp, "pp");
2141         if (active.padNextWidth > 0) {
2142             if (pp != null) {
2143                 pp = new PadPrinterParserDecorator(pp, active.padNextWidth, active.padNextChar);
2144             }
2145             active.padNextWidth = 0;
2146             active.padNextChar = 0;
2147         }
2148         active.printerParsers.add(pp);
2149         active.valueParserIndex = -1;
2150         return active.printerParsers.size() - 1;
2151     }
2152 
2153     //-----------------------------------------------------------------------
2154     /**
2155      * Completes this builder by creating the {@code DateTimeFormatter}
2156      * using the default locale.
2157      * <p>
2158      * This will create a formatter with the {@linkplain Locale#getDefault(Locale.Category) default FORMAT locale}.
2159      * Numbers will be printed and parsed using the standard DecimalStyle.
2160      * The resolver style will be {@link ResolverStyle#SMART SMART}.
2161      * <p>
2162      * Calling this method will end any open optional sections by repeatedly
2163      * calling {@link #optionalEnd()} before creating the formatter.
2164      * <p>
2165      * This builder can still be used after creating the formatter if desired,
2166      * although the state may have been changed by calls to {@code optionalEnd}.
2167      *
2168      * @return the created formatter, not null
2169      */
2170     public DateTimeFormatter toFormatter() {
2171         return toFormatter(Locale.getDefault(Locale.Category.FORMAT));
2172     }
2173 
2174     /**
2175      * Completes this builder by creating the {@code DateTimeFormatter}
2176      * using the specified locale.
2177      * <p>
2178      * This will create a formatter with the specified locale.
2179      * Numbers will be printed and parsed using the standard DecimalStyle.
2180      * The resolver style will be {@link ResolverStyle#SMART SMART}.
2181      * <p>
2182      * Calling this method will end any open optional sections by repeatedly
2183      * calling {@link #optionalEnd()} before creating the formatter.
2184      * <p>
2185      * This builder can still be used after creating the formatter if desired,
2186      * although the state may have been changed by calls to {@code optionalEnd}.
2187      *
2188      * @param locale  the locale to use for formatting, not null
2189      * @return the created formatter, not null
2190      */
2191     public DateTimeFormatter toFormatter(Locale locale) {
2192         return toFormatter(locale, ResolverStyle.SMART, null);
2193     }
2194 
2195     /**
2196      * Completes this builder by creating the formatter.
2197      * This uses the default locale.
2198      *
2199      * @param resolverStyle  the resolver style to use, not null
2200      * @return the created formatter, not null
2201      */
2202     DateTimeFormatter toFormatter(ResolverStyle resolverStyle, Chronology chrono) {
2203         return toFormatter(Locale.getDefault(Locale.Category.FORMAT), resolverStyle, chrono);
2204     }
2205 
2206     /**
2207      * Completes this builder by creating the formatter.
2208      *
2209      * @param locale  the locale to use for formatting, not null
2210      * @param chrono  the chronology to use, may be null
2211      * @return the created formatter, not null
2212      */
2213     private DateTimeFormatter toFormatter(Locale locale, ResolverStyle resolverStyle, Chronology chrono) {
2214         Objects.requireNonNull(locale, "locale");
2215         while (active.parent != null) {
2216             optionalEnd();
2217         }
2218         CompositePrinterParser pp = new CompositePrinterParser(printerParsers, false);
2219         return new DateTimeFormatter(pp, locale, DecimalStyle.STANDARD,
2220                 resolverStyle, null, chrono, null);
2221     }
2222 
2223     //-----------------------------------------------------------------------
2224     /**
2225      * Strategy for formatting/parsing date-time information.
2226      * <p>
2227      * The printer may format any part, or the whole, of the input date-time object.
2228      * Typically, a complete format is constructed from a number of smaller
2229      * units, each outputting a single field.
2230      * <p>
2231      * The parser may parse any piece of text from the input, storing the result
2232      * in the context. Typically, each individual parser will just parse one
2233      * field, such as the day-of-month, storing the value in the context.
2234      * Once the parse is complete, the caller will then resolve the parsed values
2235      * to create the desired object, such as a {@code LocalDate}.
2236      * <p>
2237      * The parse position will be updated during the parse. Parsing will start at
2238      * the specified index and the return value specifies the new parse position
2239      * for the next parser. If an error occurs, the returned index will be negative
2240      * and will have the error position encoded using the complement operator.
2241      *
2242      * @implSpec
2243      * This interface must be implemented with care to ensure other classes operate correctly.
2244      * All implementations that can be instantiated must be final, immutable and thread-safe.
2245      * <p>
2246      * The context is not a thread-safe object and a new instance will be created
2247      * for each format that occurs. The context must not be stored in an instance
2248      * variable or shared with any other threads.
2249      */
2250     interface DateTimePrinterParser {
2251 
2252         /**
2253          * Prints the date-time object to the buffer.
2254          * <p>
2255          * The context holds information to use during the format.
2256          * It also contains the date-time information to be printed.
2257          * <p>
2258          * The buffer must not be mutated beyond the content controlled by the implementation.
2259          *
2260          * @param context  the context to format using, not null
2261          * @param buf  the buffer to append to, not null
2262          * @return false if unable to query the value from the date-time, true otherwise
2263          * @throws DateTimeException if the date-time cannot be printed successfully
2264          */
2265         boolean format(DateTimePrintContext context, StringBuilder buf);
2266 
2267         /**
2268          * Parses text into date-time information.
2269          * <p>
2270          * The context holds information to use during the parse.
2271          * It is also used to store the parsed date-time information.
2272          *
2273          * @param context  the context to use and parse into, not null
2274          * @param text  the input text to parse, not null
2275          * @param position  the position to start parsing at, from 0 to the text length
2276          * @return the new parse position, where negative means an error with the
2277          *  error position encoded using the complement ~ operator
2278          * @throws NullPointerException if the context or text is null
2279          * @throws IndexOutOfBoundsException if the position is invalid
2280          */
2281         int parse(DateTimeParseContext context, CharSequence text, int position);
2282     }
2283 
2284     //-----------------------------------------------------------------------
2285     /**
2286      * Composite printer and parser.
2287      */
2288     static final class CompositePrinterParser implements DateTimePrinterParser {
2289         private final DateTimePrinterParser[] printerParsers;
2290         private final boolean optional;
2291 
2292         CompositePrinterParser(List<DateTimePrinterParser> printerParsers, boolean optional) {
2293             this(printerParsers.toArray(new DateTimePrinterParser[printerParsers.size()]), optional);
2294         }
2295 
2296         CompositePrinterParser(DateTimePrinterParser[] printerParsers, boolean optional) {
2297             this.printerParsers = printerParsers;
2298             this.optional = optional;
2299         }
2300 
2301         /**
2302          * Returns a copy of this printer-parser with the optional flag changed.
2303          *
2304          * @param optional  the optional flag to set in the copy
2305          * @return the new printer-parser, not null
2306          */
2307         public CompositePrinterParser withOptional(boolean optional) {
2308             if (optional == this.optional) {
2309                 return this;
2310             }
2311             return new CompositePrinterParser(printerParsers, optional);
2312         }
2313 
2314         @Override
2315         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2316             int length = buf.length();
2317             if (optional) {
2318                 context.startOptional();
2319             }
2320             try {
2321                 for (DateTimePrinterParser pp : printerParsers) {
2322                     if (pp.format(context, buf) == false) {
2323                         buf.setLength(length);  // reset buffer
2324                         return true;
2325                     }
2326                 }
2327             } finally {
2328                 if (optional) {
2329                     context.endOptional();
2330                 }
2331             }
2332             return true;
2333         }
2334 
2335         @Override
2336         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2337             if (optional) {
2338                 context.startOptional();
2339                 int pos = position;
2340                 for (DateTimePrinterParser pp : printerParsers) {
2341                     pos = pp.parse(context, text, pos);
2342                     if (pos < 0) {
2343                         context.endOptional(false);
2344                         return position;  // return original position
2345                     }
2346                 }
2347                 context.endOptional(true);
2348                 return pos;
2349             } else {
2350                 for (DateTimePrinterParser pp : printerParsers) {
2351                     position = pp.parse(context, text, position);
2352                     if (position < 0) {
2353                         break;
2354                     }
2355                 }
2356                 return position;
2357             }
2358         }
2359 
2360         @Override
2361         public String toString() {
2362             StringBuilder buf = new StringBuilder();
2363             if (printerParsers != null) {
2364                 buf.append(optional ? "[" : "(");
2365                 for (DateTimePrinterParser pp : printerParsers) {
2366                     buf.append(pp);
2367                 }
2368                 buf.append(optional ? "]" : ")");
2369             }
2370             return buf.toString();
2371         }
2372     }
2373 
2374     //-----------------------------------------------------------------------
2375     /**
2376      * Pads the output to a fixed width.
2377      */
2378     static final class PadPrinterParserDecorator implements DateTimePrinterParser {
2379         private final DateTimePrinterParser printerParser;
2380         private final int padWidth;
2381         private final char padChar;
2382 
2383         /**
2384          * Constructor.
2385          *
2386          * @param printerParser  the printer, not null
2387          * @param padWidth  the width to pad to, 1 or greater
2388          * @param padChar  the pad character
2389          */
2390         PadPrinterParserDecorator(DateTimePrinterParser printerParser, int padWidth, char padChar) {
2391             // input checked by DateTimeFormatterBuilder
2392             this.printerParser = printerParser;
2393             this.padWidth = padWidth;
2394             this.padChar = padChar;
2395         }
2396 
2397         @Override
2398         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2399             int preLen = buf.length();
2400             if (printerParser.format(context, buf) == false) {
2401                 return false;
2402             }
2403             int len = buf.length() - preLen;
2404             if (len > padWidth) {
2405                 throw new DateTimeException(
2406                     "Cannot print as output of " + len + " characters exceeds pad width of " + padWidth);
2407             }
2408             for (int i = 0; i < padWidth - len; i++) {
2409                 buf.insert(preLen, padChar);
2410             }
2411             return true;
2412         }
2413 
2414         @Override
2415         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2416             // cache context before changed by decorated parser
2417             final boolean strict = context.isStrict();
2418             // parse
2419             if (position > text.length()) {
2420                 throw new IndexOutOfBoundsException();
2421             }
2422             if (position == text.length()) {
2423                 return ~position;  // no more characters in the string
2424             }
2425             int endPos = position + padWidth;
2426             if (endPos > text.length()) {
2427                 if (strict) {
2428                     return ~position;  // not enough characters in the string to meet the parse width
2429                 }
2430                 endPos = text.length();
2431             }
2432             int pos = position;
2433             while (pos < endPos && context.charEquals(text.charAt(pos), padChar)) {
2434                 pos++;
2435             }
2436             text = text.subSequence(0, endPos);
2437             int resultPos = printerParser.parse(context, text, pos);
2438             if (resultPos != endPos && strict) {
2439                 return ~(position + pos);  // parse of decorated field didn't parse to the end
2440             }
2441             return resultPos;
2442         }
2443 
2444         @Override
2445         public String toString() {
2446             return "Pad(" + printerParser + "," + padWidth + (padChar == ' ' ? ")" : ",'" + padChar + "')");
2447         }
2448     }
2449 
2450     //-----------------------------------------------------------------------
2451     /**
2452      * Enumeration to apply simple parse settings.
2453      */
2454     static enum SettingsParser implements DateTimePrinterParser {
2455         SENSITIVE,
2456         INSENSITIVE,
2457         STRICT,
2458         LENIENT;
2459 
2460         @Override
2461         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2462             return true;  // nothing to do here
2463         }
2464 
2465         @Override
2466         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2467             // using ordinals to avoid javac synthetic inner class
2468             switch (ordinal()) {
2469                 case 0: context.setCaseSensitive(true); break;
2470                 case 1: context.setCaseSensitive(false); break;
2471                 case 2: context.setStrict(true); break;
2472                 case 3: context.setStrict(false); break;
2473             }
2474             return position;
2475         }
2476 
2477         @Override
2478         public String toString() {
2479             // using ordinals to avoid javac synthetic inner class
2480             switch (ordinal()) {
2481                 case 0: return "ParseCaseSensitive(true)";
2482                 case 1: return "ParseCaseSensitive(false)";
2483                 case 2: return "ParseStrict(true)";
2484                 case 3: return "ParseStrict(false)";
2485             }
2486             throw new IllegalStateException("Unreachable");
2487         }
2488     }
2489 
2490     //-----------------------------------------------------------------------
2491     /**
2492      * Defaults a value into the parse if not currently present.
2493      */
2494     static class DefaultValueParser implements DateTimePrinterParser {
2495         private final TemporalField field;
2496         private final long value;
2497 
2498         DefaultValueParser(TemporalField field, long value) {
2499             this.field = field;
2500             this.value = value;
2501         }
2502 
2503         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2504             return true;
2505         }
2506 
2507         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2508             if (context.getParsed(field) == null) {
2509                 context.setParsedField(field, value, position, position);
2510             }
2511             return position;
2512         }
2513     }
2514 
2515     //-----------------------------------------------------------------------
2516     /**
2517      * Prints or parses a character literal.
2518      */
2519     static final class CharLiteralPrinterParser implements DateTimePrinterParser {
2520         private final char literal;
2521 
2522         CharLiteralPrinterParser(char literal) {
2523             this.literal = literal;
2524         }
2525 
2526         @Override
2527         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2528             buf.append(literal);
2529             return true;
2530         }
2531 
2532         @Override
2533         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2534             int length = text.length();
2535             if (position == length) {
2536                 return ~position;
2537             }
2538             char ch = text.charAt(position);
2539             if (ch != literal) {
2540                 if (context.isCaseSensitive() ||
2541                         (Character.toUpperCase(ch) != Character.toUpperCase(literal) &&
2542                          Character.toLowerCase(ch) != Character.toLowerCase(literal))) {
2543                     return ~position;
2544                 }
2545             }
2546             return position + 1;
2547         }
2548 
2549         @Override
2550         public String toString() {
2551             if (literal == '\'') {
2552                 return "''";
2553             }
2554             return "'" + literal + "'";
2555         }
2556     }
2557 
2558     //-----------------------------------------------------------------------
2559     /**
2560      * Prints or parses a string literal.
2561      */
2562     static final class StringLiteralPrinterParser implements DateTimePrinterParser {
2563         private final String literal;
2564 
2565         StringLiteralPrinterParser(String literal) {
2566             this.literal = literal;  // validated by caller
2567         }
2568 
2569         @Override
2570         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2571             buf.append(literal);
2572             return true;
2573         }
2574 
2575         @Override
2576         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2577             int length = text.length();
2578             if (position > length || position < 0) {
2579                 throw new IndexOutOfBoundsException();
2580             }
2581             if (context.subSequenceEquals(text, position, literal, 0, literal.length()) == false) {
2582                 return ~position;
2583             }
2584             return position + literal.length();
2585         }
2586 
2587         @Override
2588         public String toString() {
2589             String converted = literal.replace("'", "''");
2590             return "'" + converted + "'";
2591         }
2592     }
2593 
2594     //-----------------------------------------------------------------------
2595     /**
2596      * Prints and parses a numeric date-time field with optional padding.
2597      */
2598     static class NumberPrinterParser implements DateTimePrinterParser {
2599 
2600         /**
2601          * Array of 10 to the power of n.
2602          */
2603         static final long[] EXCEED_POINTS = new long[] {
2604             0L,
2605             10L,
2606             100L,
2607             1000L,
2608             10000L,
2609             100000L,
2610             1000000L,
2611             10000000L,
2612             100000000L,
2613             1000000000L,
2614             10000000000L,
2615         };
2616 
2617         final TemporalField field;
2618         final int minWidth;
2619         final int maxWidth;
2620         private final SignStyle signStyle;
2621         final int subsequentWidth;
2622 
2623         /**
2624          * Constructor.
2625          *
2626          * @param field  the field to format, not null
2627          * @param minWidth  the minimum field width, from 1 to 19
2628          * @param maxWidth  the maximum field width, from minWidth to 19
2629          * @param signStyle  the positive/negative sign style, not null
2630          */
2631         NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle) {
2632             // validated by caller
2633             this.field = field;
2634             this.minWidth = minWidth;
2635             this.maxWidth = maxWidth;
2636             this.signStyle = signStyle;
2637             this.subsequentWidth = 0;
2638         }
2639 
2640         /**
2641          * Constructor.
2642          *
2643          * @param field  the field to format, not null
2644          * @param minWidth  the minimum field width, from 1 to 19
2645          * @param maxWidth  the maximum field width, from minWidth to 19
2646          * @param signStyle  the positive/negative sign style, not null
2647          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater,
2648          *  -1 if fixed width due to active adjacent parsing
2649          */
2650         protected NumberPrinterParser(TemporalField field, int minWidth, int maxWidth, SignStyle signStyle, int subsequentWidth) {
2651             // validated by caller
2652             this.field = field;
2653             this.minWidth = minWidth;
2654             this.maxWidth = maxWidth;
2655             this.signStyle = signStyle;
2656             this.subsequentWidth = subsequentWidth;
2657         }
2658 
2659         /**
2660          * Returns a new instance with fixed width flag set.
2661          *
2662          * @return a new updated printer-parser, not null
2663          */
2664         NumberPrinterParser withFixedWidth() {
2665             if (subsequentWidth == -1) {
2666                 return this;
2667             }
2668             return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, -1);
2669         }
2670 
2671         /**
2672          * Returns a new instance with an updated subsequent width.
2673          *
2674          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater
2675          * @return a new updated printer-parser, not null
2676          */
2677         NumberPrinterParser withSubsequentWidth(int subsequentWidth) {
2678             return new NumberPrinterParser(field, minWidth, maxWidth, signStyle, this.subsequentWidth + subsequentWidth);
2679         }
2680 
2681         @Override
2682         public boolean format(DateTimePrintContext context, StringBuilder buf) {
2683             Long valueLong = context.getValue(field);
2684             if (valueLong == null) {
2685                 return false;
2686             }
2687             long value = getValue(context, valueLong);
2688             DecimalStyle decimalStyle = context.getDecimalStyle();
2689             String str = (value == Long.MIN_VALUE ? "9223372036854775808" : Long.toString(Math.abs(value)));
2690             if (str.length() > maxWidth) {
2691                 throw new DateTimeException("Field " + field +
2692                     " cannot be printed as the value " + value +
2693                     " exceeds the maximum print width of " + maxWidth);
2694             }
2695             str = decimalStyle.convertNumberToI18N(str);
2696 
2697             if (value >= 0) {
2698                 switch (signStyle) {
2699                     case EXCEEDS_PAD:
2700                         if (minWidth < 19 && value >= EXCEED_POINTS[minWidth]) {
2701                             buf.append(decimalStyle.getPositiveSign());
2702                         }
2703                         break;
2704                     case ALWAYS:
2705                         buf.append(decimalStyle.getPositiveSign());
2706                         break;
2707                 }
2708             } else {
2709                 switch (signStyle) {
2710                     case NORMAL:
2711                     case EXCEEDS_PAD:
2712                     case ALWAYS:
2713                         buf.append(decimalStyle.getNegativeSign());
2714                         break;
2715                     case NOT_NEGATIVE:
2716                         throw new DateTimeException("Field " + field +
2717                             " cannot be printed as the value " + value +
2718                             " cannot be negative according to the SignStyle");
2719                 }
2720             }
2721             for (int i = 0; i < minWidth - str.length(); i++) {
2722                 buf.append(decimalStyle.getZeroDigit());
2723             }
2724             buf.append(str);
2725             return true;
2726         }
2727 
2728         /**
2729          * Gets the value to output.
2730          *
2731          * @param context  the context
2732          * @param value  the value of the field, not null
2733          * @return the value
2734          */
2735         long getValue(DateTimePrintContext context, long value) {
2736             return value;
2737         }
2738 
2739         /**
2740          * For NumberPrinterParser, the width is fixed depending on the
2741          * minWidth, maxWidth, signStyle and whether subsequent fields are fixed.
2742          * @param context the context
2743          * @return true if the field is fixed width
2744          * @see DateTimeFormatterBuilder#appendValue(java.time.temporal.TemporalField, int)
2745          */
2746         boolean isFixedWidth(DateTimeParseContext context) {
2747             return subsequentWidth == -1 ||
2748                 (subsequentWidth > 0 && minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE);
2749         }
2750 
2751         @Override
2752         public int parse(DateTimeParseContext context, CharSequence text, int position) {
2753             int length = text.length();
2754             if (position == length) {
2755                 return ~position;
2756             }
2757             char sign = text.charAt(position);  // IOOBE if invalid position
2758             boolean negative = false;
2759             boolean positive = false;
2760             if (sign == context.getDecimalStyle().getPositiveSign()) {
2761                 if (signStyle.parse(true, context.isStrict(), minWidth == maxWidth) == false) {
2762                     return ~position;
2763                 }
2764                 positive = true;
2765                 position++;
2766             } else if (sign == context.getDecimalStyle().getNegativeSign()) {
2767                 if (signStyle.parse(false, context.isStrict(), minWidth == maxWidth) == false) {
2768                     return ~position;
2769                 }
2770                 negative = true;
2771                 position++;
2772             } else {
2773                 if (signStyle == SignStyle.ALWAYS && context.isStrict()) {
2774                     return ~position;
2775                 }
2776             }
2777             int effMinWidth = (context.isStrict() || isFixedWidth(context) ? minWidth : 1);
2778             int minEndPos = position + effMinWidth;
2779             if (minEndPos > length) {
2780                 return ~position;
2781             }
2782             int effMaxWidth = (context.isStrict() || isFixedWidth(context) ? maxWidth : 9) + Math.max(subsequentWidth, 0);
2783             long total = 0;
2784             BigInteger totalBig = null;
2785             int pos = position;
2786             for (int pass = 0; pass < 2; pass++) {
2787                 int maxEndPos = Math.min(pos + effMaxWidth, length);
2788                 while (pos < maxEndPos) {
2789                     char ch = text.charAt(pos++);
2790                     int digit = context.getDecimalStyle().convertToDigit(ch);
2791                     if (digit < 0) {
2792                         pos--;
2793                         if (pos < minEndPos) {
2794                             return ~position;  // need at least min width digits
2795                         }
2796                         break;
2797                     }
2798                     if ((pos - position) > 18) {
2799                         if (totalBig == null) {
2800                             totalBig = BigInteger.valueOf(total);
2801                         }
2802                         totalBig = totalBig.multiply(BigInteger.TEN).add(BigInteger.valueOf(digit));
2803                     } else {
2804                         total = total * 10 + digit;
2805                     }
2806                 }
2807                 if (subsequentWidth > 0 && pass == 0) {
2808                     // re-parse now we know the correct width
2809                     int parseLen = pos - position;
2810                     effMaxWidth = Math.max(effMinWidth, parseLen - subsequentWidth);
2811                     pos = position;
2812                     total = 0;
2813                     totalBig = null;
2814                 } else {
2815                     break;
2816                 }
2817             }
2818             if (negative) {
2819                 if (totalBig != null) {
2820                     if (totalBig.equals(BigInteger.ZERO) && context.isStrict()) {
2821                         return ~(position - 1);  // minus zero not allowed
2822                     }
2823                     totalBig = totalBig.negate();
2824                 } else {
2825                     if (total == 0 && context.isStrict()) {
2826                         return ~(position - 1);  // minus zero not allowed
2827                     }
2828                     total = -total;
2829                 }
2830             } else if (signStyle == SignStyle.EXCEEDS_PAD && context.isStrict()) {
2831                 int parseLen = pos - position;
2832                 if (positive) {
2833                     if (parseLen <= minWidth) {
2834                         return ~(position - 1);  // '+' only parsed if minWidth exceeded
2835                     }
2836                 } else {
2837                     if (parseLen > minWidth) {
2838                         return ~position;  // '+' must be parsed if minWidth exceeded
2839                     }
2840                 }
2841             }
2842             if (totalBig != null) {
2843                 if (totalBig.bitLength() > 63) {
2844                     // overflow, parse 1 less digit
2845                     totalBig = totalBig.divide(BigInteger.TEN);
2846                     pos--;
2847                 }
2848                 return setValue(context, totalBig.longValue(), position, pos);
2849             }
2850             return setValue(context, total, position, pos);
2851         }
2852 
2853         /**
2854          * Stores the value.
2855          *
2856          * @param context  the context to store into, not null
2857          * @param value  the value
2858          * @param errorPos  the position of the field being parsed
2859          * @param successPos  the position after the field being parsed
2860          * @return the new position
2861          */
2862         int setValue(DateTimeParseContext context, long value, int errorPos, int successPos) {
2863             return context.setParsedField(field, value, errorPos, successPos);
2864         }
2865 
2866         @Override
2867         public String toString() {
2868             if (minWidth == 1 && maxWidth == 19 && signStyle == SignStyle.NORMAL) {
2869                 return "Value(" + field + ")";
2870             }
2871             if (minWidth == maxWidth && signStyle == SignStyle.NOT_NEGATIVE) {
2872                 return "Value(" + field + "," + minWidth + ")";
2873             }
2874             return "Value(" + field + "," + minWidth + "," + maxWidth + "," + signStyle + ")";
2875         }
2876     }
2877 
2878     //-----------------------------------------------------------------------
2879     /**
2880      * Prints and parses a reduced numeric date-time field.
2881      */
2882     static final class ReducedPrinterParser extends NumberPrinterParser {
2883         /**
2884          * The base date for reduced value parsing.
2885          */
2886         static final LocalDate BASE_DATE = LocalDate.of(2000, 1, 1);
2887 
2888         private final int baseValue;
2889         private final ChronoLocalDate baseDate;
2890 
2891         /**
2892          * Constructor.
2893          *
2894          * @param field  the field to format, validated not null
2895          * @param minWidth  the minimum field width, from 1 to 10
2896          * @param maxWidth  the maximum field width, from 1 to 10
2897          * @param baseValue  the base value
2898          * @param baseDate  the base date
2899          */
2900         ReducedPrinterParser(TemporalField field, int minWidth, int maxWidth,
2901                 int baseValue, ChronoLocalDate baseDate) {
2902             this(field, minWidth, maxWidth, baseValue, baseDate, 0);
2903             if (minWidth < 1 || minWidth > 10) {
2904                 throw new IllegalArgumentException("The minWidth must be from 1 to 10 inclusive but was " + minWidth);
2905             }
2906             if (maxWidth < 1 || maxWidth > 10) {
2907                 throw new IllegalArgumentException("The maxWidth must be from 1 to 10 inclusive but was " + minWidth);
2908             }
2909             if (maxWidth < minWidth) {
2910                 throw new IllegalArgumentException("Maximum width must exceed or equal the minimum width but " +
2911                         maxWidth + " < " + minWidth);
2912             }
2913             if (baseDate == null) {
2914                 if (field.range().isValidValue(baseValue) == false) {
2915                     throw new IllegalArgumentException("The base value must be within the range of the field");
2916                 }
2917                 if ((((long) baseValue) + EXCEED_POINTS[maxWidth]) > Integer.MAX_VALUE) {
2918                     throw new DateTimeException("Unable to add printer-parser as the range exceeds the capacity of an int");
2919                 }
2920             }
2921         }
2922 
2923         /**
2924          * Constructor.
2925          * The arguments have already been checked.
2926          *
2927          * @param field  the field to format, validated not null
2928          * @param minWidth  the minimum field width, from 1 to 10
2929          * @param maxWidth  the maximum field width, from 1 to 10
2930          * @param baseValue  the base value
2931          * @param baseDate  the base date
2932          * @param subsequentWidth the subsequentWidth for this instance
2933          */
2934         private ReducedPrinterParser(TemporalField field, int minWidth, int maxWidth,
2935                 int baseValue, ChronoLocalDate baseDate, int subsequentWidth) {
2936             super(field, minWidth, maxWidth, SignStyle.NOT_NEGATIVE, subsequentWidth);
2937             this.baseValue = baseValue;
2938             this.baseDate = baseDate;
2939         }
2940 
2941         @Override
2942         long getValue(DateTimePrintContext context, long value) {
2943             long absValue = Math.abs(value);
2944             int baseValue = this.baseValue;
2945             if (baseDate != null) {
2946                 Chronology chrono = Chronology.from(context.getTemporal());
2947                 baseValue = chrono.date(baseDate).get(field);
2948             }
2949             if (value >= baseValue && value < baseValue + EXCEED_POINTS[minWidth]) {
2950                 // Use the reduced value if it fits in minWidth
2951                 return absValue % EXCEED_POINTS[minWidth];
2952             }
2953             // Otherwise truncate to fit in maxWidth
2954             return absValue % EXCEED_POINTS[maxWidth];
2955         }
2956 
2957         @Override
2958         int setValue(DateTimeParseContext context, long value, int errorPos, int successPos) {
2959             int baseValue = this.baseValue;
2960             if (baseDate != null) {
2961                 Chronology chrono = context.getEffectiveChronology();
2962                 baseValue = chrono.date(baseDate).get(field);
2963 
2964                 // In case the Chronology is changed later, add a callback when/if it changes
2965                 final long initialValue = value;
2966                 context.addChronoChangedListener(
2967                         (_unused) ->  {
2968                             /* Repeat the set of the field using the current Chronology
2969                              * The success/error position is ignored because the value is
2970                              * intentionally being overwritten.
2971                              */
2972                             setValue(context, initialValue, errorPos, successPos);
2973                         });
2974             }
2975             int parseLen = successPos - errorPos;
2976             if (parseLen == minWidth && value >= 0) {
2977                 long range = EXCEED_POINTS[minWidth];
2978                 long lastPart = baseValue % range;
2979                 long basePart = baseValue - lastPart;
2980                 if (baseValue > 0) {
2981                     value = basePart + value;
2982                 } else {
2983                     value = basePart - value;
2984                 }
2985                 if (value < baseValue) {
2986                     value += range;
2987                 }
2988             }
2989             return context.setParsedField(field, value, errorPos, successPos);
2990         }
2991 
2992         /**
2993          * Returns a new instance with fixed width flag set.
2994          *
2995          * @return a new updated printer-parser, not null
2996          */
2997         @Override
2998         ReducedPrinterParser withFixedWidth() {
2999             if (subsequentWidth == -1) {
3000                 return this;
3001             }
3002             return new ReducedPrinterParser(field, minWidth, maxWidth, baseValue, baseDate, -1);
3003         }
3004 
3005         /**
3006          * Returns a new instance with an updated subsequent width.
3007          *
3008          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater
3009          * @return a new updated printer-parser, not null
3010          */
3011         @Override
3012         ReducedPrinterParser withSubsequentWidth(int subsequentWidth) {
3013             return new ReducedPrinterParser(field, minWidth, maxWidth, baseValue, baseDate,
3014                     this.subsequentWidth + subsequentWidth);
3015         }
3016 
3017         /**
3018          * For a ReducedPrinterParser, fixed width is false if the mode is strict,
3019          * otherwise it is set as for NumberPrinterParser.
3020          * @param context the context
3021          * @return if the field is fixed width
3022          * @see DateTimeFormatterBuilder#appendValueReduced(java.time.temporal.TemporalField, int, int, int)
3023          */
3024         @Override
3025         boolean isFixedWidth(DateTimeParseContext context) {
3026            if (context.isStrict() == false) {
3027                return false;
3028            }
3029            return super.isFixedWidth(context);
3030         }
3031 
3032         @Override
3033         public String toString() {
3034             return "ReducedValue(" + field + "," + minWidth + "," + maxWidth +
3035                     "," + Objects.requireNonNullElse(baseDate, baseValue) + ")";
3036         }
3037     }
3038 
3039     //-----------------------------------------------------------------------
3040     /**
3041      * Prints and parses a numeric date-time field with optional padding.
3042      */
3043     static final class FractionPrinterParser extends NumberPrinterParser {
3044        private final boolean decimalPoint;
3045 
3046         /**
3047          * Constructor.
3048          *
3049          * @param field  the field to output, not null
3050          * @param minWidth  the minimum width to output, from 0 to 9
3051          * @param maxWidth  the maximum width to output, from 0 to 9
3052          * @param decimalPoint  whether to output the localized decimal point symbol
3053          */
3054         FractionPrinterParser(TemporalField field, int minWidth, int maxWidth, boolean decimalPoint) {
3055             this(field, minWidth, maxWidth, decimalPoint, 0);
3056             Objects.requireNonNull(field, "field");
3057             if (field.range().isFixed() == false) {
3058                 throw new IllegalArgumentException("Field must have a fixed set of values: " + field);
3059             }
3060             if (minWidth < 0 || minWidth > 9) {
3061                 throw new IllegalArgumentException("Minimum width must be from 0 to 9 inclusive but was " + minWidth);
3062             }
3063             if (maxWidth < 1 || maxWidth > 9) {
3064                 throw new IllegalArgumentException("Maximum width must be from 1 to 9 inclusive but was " + maxWidth);
3065             }
3066             if (maxWidth < minWidth) {
3067                 throw new IllegalArgumentException("Maximum width must exceed or equal the minimum width but " +
3068                         maxWidth + " < " + minWidth);
3069             }
3070         }
3071 
3072         /**
3073          * Constructor.
3074          *
3075          * @param field  the field to output, not null
3076          * @param minWidth  the minimum width to output, from 0 to 9
3077          * @param maxWidth  the maximum width to output, from 0 to 9
3078          * @param decimalPoint  whether to output the localized decimal point symbol
3079          * @param subsequentWidth the subsequentWidth for this instance
3080          */
3081         FractionPrinterParser(TemporalField field, int minWidth, int maxWidth, boolean decimalPoint, int subsequentWidth) {
3082             super(field, minWidth, maxWidth, SignStyle.NOT_NEGATIVE, subsequentWidth);
3083             this.decimalPoint = decimalPoint;
3084         }
3085 
3086         /**
3087          * Returns a new instance with fixed width flag set.
3088          *
3089          * @return a new updated printer-parser, not null
3090          */
3091         @Override
3092         FractionPrinterParser withFixedWidth() {
3093             if (subsequentWidth == -1) {
3094                 return this;
3095             }
3096             return new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint, -1);
3097         }
3098 
3099         /**
3100          * Returns a new instance with an updated subsequent width.
3101          *
3102          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater
3103          * @return a new updated printer-parser, not null
3104          */
3105         @Override
3106         FractionPrinterParser withSubsequentWidth(int subsequentWidth) {
3107             return new FractionPrinterParser(field, minWidth, maxWidth, decimalPoint, this.subsequentWidth + subsequentWidth);
3108         }
3109 
3110         /**
3111          * For FractionPrinterPrinterParser, the width is fixed if context is sttrict,
3112          * minWidth equal to maxWidth and decimalpoint is absent.
3113          * @param context the context
3114          * @return if the field is fixed width
3115          * @see DateTimeFormatterBuilder#appendValueFraction(java.time.temporal.TemporalField, int, int, boolean)
3116          */
3117         @Override
3118         boolean isFixedWidth(DateTimeParseContext context) {
3119             if (context.isStrict() && minWidth == maxWidth && decimalPoint == false) {
3120                 return true;
3121             }
3122             return false;
3123         }
3124 
3125         @Override
3126         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3127             Long value = context.getValue(field);
3128             if (value == null) {
3129                 return false;
3130             }
3131             DecimalStyle decimalStyle = context.getDecimalStyle();
3132             BigDecimal fraction = convertToFraction(value);
3133             if (fraction.scale() == 0) {  // scale is zero if value is zero
3134                 if (minWidth > 0) {
3135                     if (decimalPoint) {
3136                         buf.append(decimalStyle.getDecimalSeparator());
3137                     }
3138                     for (int i = 0; i < minWidth; i++) {
3139                         buf.append(decimalStyle.getZeroDigit());
3140                     }
3141                 }
3142             } else {
3143                 int outputScale = Math.min(Math.max(fraction.scale(), minWidth), maxWidth);
3144                 fraction = fraction.setScale(outputScale, RoundingMode.FLOOR);
3145                 String str = fraction.toPlainString().substring(2);
3146                 str = decimalStyle.convertNumberToI18N(str);
3147                 if (decimalPoint) {
3148                     buf.append(decimalStyle.getDecimalSeparator());
3149                 }
3150                 buf.append(str);
3151             }
3152             return true;
3153         }
3154 
3155         @Override
3156         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3157             int effectiveMin = (context.isStrict() || isFixedWidth(context) ? minWidth : 0);
3158             int effectiveMax = (context.isStrict() || isFixedWidth(context) ? maxWidth : 9);
3159             int length = text.length();
3160             if (position == length) {
3161                 // valid if whole field is optional, invalid if minimum width
3162                 return (effectiveMin > 0 ? ~position : position);
3163             }
3164             if (decimalPoint) {
3165                 if (text.charAt(position) != context.getDecimalStyle().getDecimalSeparator()) {
3166                     // valid if whole field is optional, invalid if minimum width
3167                     return (effectiveMin > 0 ? ~position : position);
3168                 }
3169                 position++;
3170             }
3171             int minEndPos = position + effectiveMin;
3172             if (minEndPos > length) {
3173                 return ~position;  // need at least min width digits
3174             }
3175             int maxEndPos = Math.min(position + effectiveMax, length);
3176             int total = 0;  // can use int because we are only parsing up to 9 digits
3177             int pos = position;
3178             while (pos < maxEndPos) {
3179                 char ch = text.charAt(pos++);
3180                 int digit = context.getDecimalStyle().convertToDigit(ch);
3181                 if (digit < 0) {
3182                     if (pos < minEndPos) {
3183                         return ~position;  // need at least min width digits
3184                     }
3185                     pos--;
3186                     break;
3187                 }
3188                 total = total * 10 + digit;
3189             }
3190             BigDecimal fraction = new BigDecimal(total).movePointLeft(pos - position);
3191             long value = convertFromFraction(fraction);
3192             return context.setParsedField(field, value, position, pos);
3193         }
3194 
3195         /**
3196          * Converts a value for this field to a fraction between 0 and 1.
3197          * <p>
3198          * The fractional value is between 0 (inclusive) and 1 (exclusive).
3199          * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
3200          * The fraction is obtained by calculation from the field range using 9 decimal
3201          * places and a rounding mode of {@link RoundingMode#FLOOR FLOOR}.
3202          * The calculation is inaccurate if the values do not run continuously from smallest to largest.
3203          * <p>
3204          * For example, the second-of-minute value of 15 would be returned as 0.25,
3205          * assuming the standard definition of 60 seconds in a minute.
3206          *
3207          * @param value  the value to convert, must be valid for this rule
3208          * @return the value as a fraction within the range, from 0 to 1, not null
3209          * @throws DateTimeException if the value cannot be converted to a fraction
3210          */
3211         private BigDecimal convertToFraction(long value) {
3212             ValueRange range = field.range();
3213             range.checkValidValue(value, field);
3214             BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
3215             BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
3216             BigDecimal valueBD = BigDecimal.valueOf(value).subtract(minBD);
3217             BigDecimal fraction = valueBD.divide(rangeBD, 9, RoundingMode.FLOOR);
3218             // stripTrailingZeros bug
3219             return fraction.compareTo(BigDecimal.ZERO) == 0 ? BigDecimal.ZERO : fraction.stripTrailingZeros();
3220         }
3221 
3222         /**
3223          * Converts a fraction from 0 to 1 for this field to a value.
3224          * <p>
3225          * The fractional value must be between 0 (inclusive) and 1 (exclusive).
3226          * It can only be returned if the {@link java.time.temporal.TemporalField#range() value range} is fixed.
3227          * The value is obtained by calculation from the field range and a rounding
3228          * mode of {@link RoundingMode#FLOOR FLOOR}.
3229          * The calculation is inaccurate if the values do not run continuously from smallest to largest.
3230          * <p>
3231          * For example, the fractional second-of-minute of 0.25 would be converted to 15,
3232          * assuming the standard definition of 60 seconds in a minute.
3233          *
3234          * @param fraction  the fraction to convert, not null
3235          * @return the value of the field, valid for this rule
3236          * @throws DateTimeException if the value cannot be converted
3237          */
3238         private long convertFromFraction(BigDecimal fraction) {
3239             ValueRange range = field.range();
3240             BigDecimal minBD = BigDecimal.valueOf(range.getMinimum());
3241             BigDecimal rangeBD = BigDecimal.valueOf(range.getMaximum()).subtract(minBD).add(BigDecimal.ONE);
3242             BigDecimal valueBD = fraction.multiply(rangeBD).setScale(0, RoundingMode.FLOOR).add(minBD);
3243             return valueBD.longValueExact();
3244         }
3245 
3246         @Override
3247         public String toString() {
3248             String decimal = (decimalPoint ? ",DecimalPoint" : "");
3249             return "Fraction(" + field + "," + minWidth + "," + maxWidth + decimal + ")";
3250         }
3251     }
3252 
3253     //-----------------------------------------------------------------------
3254     /**
3255      * Prints or parses field text.
3256      */
3257     static final class TextPrinterParser implements DateTimePrinterParser {
3258         private final TemporalField field;
3259         private final TextStyle textStyle;
3260         private final DateTimeTextProvider provider;
3261         /**
3262          * The cached number printer parser.
3263          * Immutable and volatile, so no synchronization needed.
3264          */
3265         private volatile NumberPrinterParser numberPrinterParser;
3266 
3267         /**
3268          * Constructor.
3269          *
3270          * @param field  the field to output, not null
3271          * @param textStyle  the text style, not null
3272          * @param provider  the text provider, not null
3273          */
3274         TextPrinterParser(TemporalField field, TextStyle textStyle, DateTimeTextProvider provider) {
3275             // validated by caller
3276             this.field = field;
3277             this.textStyle = textStyle;
3278             this.provider = provider;
3279         }
3280 
3281         @Override
3282         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3283             Long value = context.getValue(field);
3284             if (value == null) {
3285                 return false;
3286             }
3287             String text;
3288             Chronology chrono = context.getTemporal().query(TemporalQueries.chronology());
3289             if (chrono == null || chrono == IsoChronology.INSTANCE) {
3290                 text = provider.getText(field, value, textStyle, context.getLocale());
3291             } else {
3292                 text = provider.getText(chrono, field, value, textStyle, context.getLocale());
3293             }
3294             if (text == null) {
3295                 return numberPrinterParser().format(context, buf);
3296             }
3297             buf.append(text);
3298             return true;
3299         }
3300 
3301         @Override
3302         public int parse(DateTimeParseContext context, CharSequence parseText, int position) {
3303             int length = parseText.length();
3304             if (position < 0 || position > length) {
3305                 throw new IndexOutOfBoundsException();
3306             }
3307             TextStyle style = (context.isStrict() ? textStyle : null);
3308             Chronology chrono = context.getEffectiveChronology();
3309             Iterator<Entry<String, Long>> it;
3310             if (chrono == null || chrono == IsoChronology.INSTANCE) {
3311                 it = provider.getTextIterator(field, style, context.getLocale());
3312             } else {
3313                 it = provider.getTextIterator(chrono, field, style, context.getLocale());
3314             }
3315             if (it != null) {
3316                 while (it.hasNext()) {
3317                     Entry<String, Long> entry = it.next();
3318                     String itText = entry.getKey();
3319                     if (context.subSequenceEquals(itText, 0, parseText, position, itText.length())) {
3320                         return context.setParsedField(field, entry.getValue(), position, position + itText.length());
3321                     }
3322                 }
3323                 if (field == ERA && !context.isStrict()) {
3324                     // parse the possible era name from era.toString()
3325                     List<Era> eras = chrono.eras();
3326                     for (Era era : eras) {
3327                         String name = era.toString();
3328                         if (context.subSequenceEquals(name, 0, parseText, position, name.length())) {
3329                             return context.setParsedField(field, era.getValue(), position, position + name.length());
3330                         }
3331                     }
3332                 }
3333                 if (context.isStrict()) {
3334                     return ~position;
3335                 }
3336             }
3337             return numberPrinterParser().parse(context, parseText, position);
3338         }
3339 
3340         /**
3341          * Create and cache a number printer parser.
3342          * @return the number printer parser for this field, not null
3343          */
3344         private NumberPrinterParser numberPrinterParser() {
3345             if (numberPrinterParser == null) {
3346                 numberPrinterParser = new NumberPrinterParser(field, 1, 19, SignStyle.NORMAL);
3347             }
3348             return numberPrinterParser;
3349         }
3350 
3351         @Override
3352         public String toString() {
3353             if (textStyle == TextStyle.FULL) {
3354                 return "Text(" + field + ")";
3355             }
3356             return "Text(" + field + "," + textStyle + ")";
3357         }
3358     }
3359 
3360     //-----------------------------------------------------------------------
3361     /**
3362      * Prints or parses an ISO-8601 instant.
3363      */
3364     static final class InstantPrinterParser implements DateTimePrinterParser {
3365         // days in a 400 year cycle = 146097
3366         // days in a 10,000 year cycle = 146097 * 25
3367         // seconds per day = 86400
3368         private static final long SECONDS_PER_10000_YEARS = 146097L * 25L * 86400L;
3369         private static final long SECONDS_0000_TO_1970 = ((146097L * 5L) - (30L * 365L + 7L)) * 86400L;
3370         private final int fractionalDigits;
3371 
3372         InstantPrinterParser(int fractionalDigits) {
3373             this.fractionalDigits = fractionalDigits;
3374         }
3375 
3376         @Override
3377         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3378             // use INSTANT_SECONDS, thus this code is not bound by Instant.MAX
3379             Long inSecs = context.getValue(INSTANT_SECONDS);
3380             Long inNanos = null;
3381             if (context.getTemporal().isSupported(NANO_OF_SECOND)) {
3382                 inNanos = context.getTemporal().getLong(NANO_OF_SECOND);
3383             }
3384             if (inSecs == null) {
3385                 return false;
3386             }
3387             long inSec = inSecs;
3388             int inNano = NANO_OF_SECOND.checkValidIntValue(inNanos != null ? inNanos : 0);
3389             // format mostly using LocalDateTime.toString
3390             if (inSec >= -SECONDS_0000_TO_1970) {
3391                 // current era
3392                 long zeroSecs = inSec - SECONDS_PER_10000_YEARS + SECONDS_0000_TO_1970;
3393                 long hi = Math.floorDiv(zeroSecs, SECONDS_PER_10000_YEARS) + 1;
3394                 long lo = Math.floorMod(zeroSecs, SECONDS_PER_10000_YEARS);
3395                 LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC);
3396                 if (hi > 0) {
3397                     buf.append('+').append(hi);
3398                 }
3399                 buf.append(ldt);
3400                 if (ldt.getSecond() == 0) {
3401                     buf.append(":00");
3402                 }
3403             } else {
3404                 // before current era
3405                 long zeroSecs = inSec + SECONDS_0000_TO_1970;
3406                 long hi = zeroSecs / SECONDS_PER_10000_YEARS;
3407                 long lo = zeroSecs % SECONDS_PER_10000_YEARS;
3408                 LocalDateTime ldt = LocalDateTime.ofEpochSecond(lo - SECONDS_0000_TO_1970, 0, ZoneOffset.UTC);
3409                 int pos = buf.length();
3410                 buf.append(ldt);
3411                 if (ldt.getSecond() == 0) {
3412                     buf.append(":00");
3413                 }
3414                 if (hi < 0) {
3415                     if (ldt.getYear() == -10_000) {
3416                         buf.replace(pos, pos + 2, Long.toString(hi - 1));
3417                     } else if (lo == 0) {
3418                         buf.insert(pos, hi);
3419                     } else {
3420                         buf.insert(pos + 1, Math.abs(hi));
3421                     }
3422                 }
3423             }
3424             // add fraction
3425             if ((fractionalDigits < 0 && inNano > 0) || fractionalDigits > 0) {
3426                 buf.append('.');
3427                 int div = 100_000_000;
3428                 for (int i = 0; ((fractionalDigits == -1 && inNano > 0) ||
3429                                     (fractionalDigits == -2 && (inNano > 0 || (i % 3) != 0)) ||
3430                                     i < fractionalDigits); i++) {
3431                     int digit = inNano / div;
3432                     buf.append((char) (digit + '0'));
3433                     inNano = inNano - (digit * div);
3434                     div = div / 10;
3435                 }
3436             }
3437             buf.append('Z');
3438             return true;
3439         }
3440 
3441         @Override
3442         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3443             // new context to avoid overwriting fields like year/month/day
3444             int minDigits = (fractionalDigits < 0 ? 0 : fractionalDigits);
3445             int maxDigits = (fractionalDigits < 0 ? 9 : fractionalDigits);
3446             CompositePrinterParser parser = new DateTimeFormatterBuilder()
3447                     .append(DateTimeFormatter.ISO_LOCAL_DATE).appendLiteral('T')
3448                     .appendValue(HOUR_OF_DAY, 2).appendLiteral(':')
3449                     .appendValue(MINUTE_OF_HOUR, 2).appendLiteral(':')
3450                     .appendValue(SECOND_OF_MINUTE, 2)
3451                     .appendFraction(NANO_OF_SECOND, minDigits, maxDigits, true)
3452                     .appendLiteral('Z')
3453                     .toFormatter().toPrinterParser(false);
3454             DateTimeParseContext newContext = context.copy();
3455             int pos = parser.parse(newContext, text, position);
3456             if (pos < 0) {
3457                 return pos;
3458             }
3459             // parser restricts most fields to 2 digits, so definitely int
3460             // correctly parsed nano is also guaranteed to be valid
3461             long yearParsed = newContext.getParsed(YEAR);
3462             int month = newContext.getParsed(MONTH_OF_YEAR).intValue();
3463             int day = newContext.getParsed(DAY_OF_MONTH).intValue();
3464             int hour = newContext.getParsed(HOUR_OF_DAY).intValue();
3465             int min = newContext.getParsed(MINUTE_OF_HOUR).intValue();
3466             Long secVal = newContext.getParsed(SECOND_OF_MINUTE);
3467             Long nanoVal = newContext.getParsed(NANO_OF_SECOND);
3468             int sec = (secVal != null ? secVal.intValue() : 0);
3469             int nano = (nanoVal != null ? nanoVal.intValue() : 0);
3470             int days = 0;
3471             if (hour == 24 && min == 0 && sec == 0 && nano == 0) {
3472                 hour = 0;
3473                 days = 1;
3474             } else if (hour == 23 && min == 59 && sec == 60) {
3475                 context.setParsedLeapSecond();
3476                 sec = 59;
3477             }
3478             int year = (int) yearParsed % 10_000;
3479             long instantSecs;
3480             try {
3481                 LocalDateTime ldt = LocalDateTime.of(year, month, day, hour, min, sec, 0).plusDays(days);
3482                 instantSecs = ldt.toEpochSecond(ZoneOffset.UTC);
3483                 instantSecs += Math.multiplyExact(yearParsed / 10_000L, SECONDS_PER_10000_YEARS);
3484             } catch (RuntimeException ex) {
3485                 return ~position;
3486             }
3487             int successPos = pos;
3488             successPos = context.setParsedField(INSTANT_SECONDS, instantSecs, position, successPos);
3489             return context.setParsedField(NANO_OF_SECOND, nano, position, successPos);
3490         }
3491 
3492         @Override
3493         public String toString() {
3494             return "Instant()";
3495         }
3496     }
3497 
3498     //-----------------------------------------------------------------------
3499     /**
3500      * Prints or parses an offset ID.
3501      */
3502     static final class OffsetIdPrinterParser implements DateTimePrinterParser {
3503         static final String[] PATTERNS = new String[] {
3504                 "+HH", "+HHmm", "+HH:mm", "+HHMM", "+HH:MM", "+HHMMss", "+HH:MM:ss", "+HHMMSS", "+HH:MM:SS", "+HHmmss", "+HH:mm:ss",
3505                 "+H",  "+Hmm",  "+H:mm",  "+HMM",  "+H:MM",  "+HMMss",  "+H:MM:ss",  "+HMMSS",  "+H:MM:SS",  "+Hmmss",  "+H:mm:ss",
3506         };  // order used in pattern builder
3507         static final OffsetIdPrinterParser INSTANCE_ID_Z = new OffsetIdPrinterParser("+HH:MM:ss", "Z");
3508         static final OffsetIdPrinterParser INSTANCE_ID_ZERO = new OffsetIdPrinterParser("+HH:MM:ss", "0");
3509 
3510         private final String noOffsetText;
3511         private final int type;
3512         private final int style;
3513 
3514         /**
3515          * Constructor.
3516          *
3517          * @param pattern  the pattern
3518          * @param noOffsetText  the text to use for UTC, not null
3519          */
3520         OffsetIdPrinterParser(String pattern, String noOffsetText) {
3521             Objects.requireNonNull(pattern, "pattern");
3522             Objects.requireNonNull(noOffsetText, "noOffsetText");
3523             this.type = checkPattern(pattern);
3524             this.style = type % 11;
3525             this.noOffsetText = noOffsetText;
3526         }
3527 
3528         private int checkPattern(String pattern) {
3529             for (int i = 0; i < PATTERNS.length; i++) {
3530                 if (PATTERNS[i].equals(pattern)) {
3531                     return i;
3532                 }
3533             }
3534             throw new IllegalArgumentException("Invalid zone offset pattern: " + pattern);
3535         }
3536 
3537         private boolean isPaddedHour() {
3538             return type < 11;
3539         }
3540 
3541         private boolean isColon() {
3542             return style > 0 && (style % 2) == 0;
3543         }
3544 
3545         @Override
3546         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3547             Long offsetSecs = context.getValue(OFFSET_SECONDS);
3548             if (offsetSecs == null) {
3549                 return false;
3550             }
3551             int totalSecs = Math.toIntExact(offsetSecs);
3552             if (totalSecs == 0) {
3553                 buf.append(noOffsetText);
3554             } else {
3555                 int absHours = Math.abs((totalSecs / 3600) % 100);  // anything larger than 99 silently dropped
3556                 int absMinutes = Math.abs((totalSecs / 60) % 60);
3557                 int absSeconds = Math.abs(totalSecs % 60);
3558                 int bufPos = buf.length();
3559                 int output = absHours;
3560                 buf.append(totalSecs < 0 ? "-" : "+");
3561                 if (isPaddedHour() || absHours >= 10) {
3562                     formatZeroPad(false, absHours, buf);
3563                 } else {
3564                     buf.append((char) (absHours + '0'));
3565                 }
3566                 if ((style >= 3 && style <= 8) || (style >= 9 && absSeconds > 0) || (style >= 1 && absMinutes > 0)) {
3567                     formatZeroPad(isColon(), absMinutes, buf);
3568                     output += absMinutes;
3569                     if (style == 7 || style == 8 || (style >= 5 && absSeconds > 0)) {
3570                         formatZeroPad(isColon(), absSeconds, buf);
3571                         output += absSeconds;
3572                     }
3573                 }
3574                 if (output == 0) {
3575                     buf.setLength(bufPos);
3576                     buf.append(noOffsetText);
3577                 }
3578             }
3579             return true;
3580         }
3581 
3582         private void formatZeroPad(boolean colon, int value, StringBuilder buf) {
3583             buf.append(colon ? ":" : "")
3584                     .append((char) (value / 10 + '0'))
3585                     .append((char) (value % 10 + '0'));
3586         }
3587 
3588         @Override
3589         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3590             int length = text.length();
3591             int noOffsetLen = noOffsetText.length();
3592             if (noOffsetLen == 0) {
3593                 if (position == length) {
3594                     return context.setParsedField(OFFSET_SECONDS, 0, position, position);
3595                 }
3596             } else {
3597                 if (position == length) {
3598                     return ~position;
3599                 }
3600                 if (context.subSequenceEquals(text, position, noOffsetText, 0, noOffsetLen)) {
3601                     return context.setParsedField(OFFSET_SECONDS, 0, position, position + noOffsetLen);
3602                 }
3603             }
3604 
3605             // parse normal plus/minus offset
3606             char sign = text.charAt(position);  // IOOBE if invalid position
3607             if (sign == '+' || sign == '-') {
3608                 // starts
3609                 int negative = (sign == '-' ? -1 : 1);
3610                 boolean isColon = isColon();
3611                 boolean paddedHour = isPaddedHour();
3612                 int[] array = new int[4];
3613                 array[0] = position + 1;
3614                 int parseType = type;
3615                 // select parse type when lenient
3616                 if (!context.isStrict()) {
3617                     if (paddedHour) {
3618                         if (isColon || (parseType == 0 && length > position + 3 && text.charAt(position + 3) == ':')) {
3619                             isColon = true; // needed in cases like ("+HH", "+01:01")
3620                             parseType = 10;
3621                         } else {
3622                             parseType = 9;
3623                         }
3624                     } else {
3625                         if (isColon || (parseType == 11 && length > position + 3 && (text.charAt(position + 2) == ':' || text.charAt(position + 3) == ':'))) {
3626                             isColon = true;
3627                             parseType = 21;  // needed in cases like ("+H", "+1:01")
3628                         } else {
3629                             parseType = 20;
3630                         }
3631                     }
3632                 }
3633                 // parse according to the selected pattern
3634                 switch (parseType) {
3635                     case 0: // +HH
3636                     case 11: // +H
3637                         parseHour(text, paddedHour, array);
3638                         break;
3639                     case 1: // +HHmm
3640                     case 2: // +HH:mm
3641                     case 13: // +H:mm
3642                         parseHour(text, paddedHour, array);
3643                         parseMinute(text, isColon, false, array);
3644                         break;
3645                     case 3: // +HHMM
3646                     case 4: // +HH:MM
3647                     case 15: // +H:MM
3648                         parseHour(text, paddedHour, array);
3649                         parseMinute(text, isColon, true, array);
3650                         break;
3651                     case 5: // +HHMMss
3652                     case 6: // +HH:MM:ss
3653                     case 17: // +H:MM:ss
3654                         parseHour(text, paddedHour, array);
3655                         parseMinute(text, isColon, true, array);
3656                         parseSecond(text, isColon, false, array);
3657                         break;
3658                     case 7: // +HHMMSS
3659                     case 8: // +HH:MM:SS
3660                     case 19: // +H:MM:SS
3661                         parseHour(text, paddedHour, array);
3662                         parseMinute(text, isColon, true, array);
3663                         parseSecond(text, isColon, true, array);
3664                         break;
3665                     case 9: // +HHmmss
3666                     case 10: // +HH:mm:ss
3667                     case 21: // +H:mm:ss
3668                         parseHour(text, paddedHour, array);
3669                         parseOptionalMinuteSecond(text, isColon, array);
3670                         break;
3671                     case 12: // +Hmm
3672                         parseVariableWidthDigits(text, 1, 4, array);
3673                         break;
3674                     case 14: // +HMM
3675                         parseVariableWidthDigits(text, 3, 4, array);
3676                         break;
3677                     case 16: // +HMMss
3678                         parseVariableWidthDigits(text, 3, 6, array);
3679                         break;
3680                     case 18: // +HMMSS
3681                         parseVariableWidthDigits(text, 5, 6, array);
3682                         break;
3683                     case 20: // +Hmmss
3684                         parseVariableWidthDigits(text, 1, 6, array);
3685                         break;
3686                 }
3687                 if (array[0] > 0) {
3688                     if (array[1] > 23 || array[2] > 59 || array[3] > 59) {
3689                         throw new DateTimeException("Value out of range: Hour[0-23], Minute[0-59], Second[0-59]");
3690                     }
3691                     long offsetSecs = negative * (array[1] * 3600L + array[2] * 60L + array[3]);
3692                     return context.setParsedField(OFFSET_SECONDS, offsetSecs, position, array[0]);
3693                 }
3694             }
3695             // handle special case of empty no offset text
3696             if (noOffsetLen == 0) {
3697                 return context.setParsedField(OFFSET_SECONDS, 0, position, position);
3698             }
3699             return ~position;
3700         }
3701 
3702         private void parseHour(CharSequence parseText, boolean paddedHour, int[] array) {
3703             if (paddedHour) {
3704                 // parse two digits
3705                 if (!parseDigits(parseText, false, 1, array)) {
3706                     array[0] = ~array[0];
3707                 }
3708             } else {
3709                 // parse one or two digits
3710                 parseVariableWidthDigits(parseText, 1, 2, array);
3711             }
3712         }
3713 
3714         private void parseMinute(CharSequence parseText, boolean isColon, boolean mandatory, int[] array) {
3715             if (!parseDigits(parseText, isColon, 2, array)) {
3716                 if (mandatory) {
3717                     array[0] = ~array[0];
3718                 }
3719             }
3720         }
3721 
3722         private void parseSecond(CharSequence parseText, boolean isColon, boolean mandatory, int[] array) {
3723             if (!parseDigits(parseText, isColon, 3, array)) {
3724                 if (mandatory) {
3725                     array[0] = ~array[0];
3726                 }
3727             }
3728         }
3729 
3730         private void parseOptionalMinuteSecond(CharSequence parseText, boolean isColon, int[] array) {
3731             if (parseDigits(parseText, isColon, 2, array)) {
3732                 parseDigits(parseText, isColon, 3, array);
3733             }
3734         }
3735 
3736         private boolean parseDigits(CharSequence parseText, boolean isColon, int arrayIndex, int[] array) {
3737             int pos = array[0];
3738             if (pos < 0) {
3739                 return true;
3740             }
3741             if (isColon && arrayIndex != 1) { //  ':' will precede only in case of minute/second
3742                 if (pos + 1 > parseText.length() || parseText.charAt(pos) != ':') {
3743                     return false;
3744                 }
3745                 pos++;
3746             }
3747             if (pos + 2 > parseText.length()) {
3748                 return false;
3749             }
3750             char ch1 = parseText.charAt(pos++);
3751             char ch2 = parseText.charAt(pos++);
3752             if (ch1 < '0' || ch1 > '9' || ch2 < '0' || ch2 > '9') {
3753                 return false;
3754             }
3755             int value = (ch1 - 48) * 10 + (ch2 - 48);
3756             if (value < 0 || value > 59) {
3757                 return false;
3758             }
3759             array[arrayIndex] = value;
3760             array[0] = pos;
3761             return true;
3762         }
3763 
3764         private void parseVariableWidthDigits(CharSequence parseText, int minDigits, int maxDigits, int[] array) {
3765             // scan the text to find the available number of digits up to maxDigits
3766             // so long as the number available is minDigits or more, the input is valid
3767             // then parse the number of available digits
3768             int pos = array[0];
3769             int available = 0;
3770             char[] chars = new char[maxDigits];
3771             for (int i = 0; i < maxDigits; i++) {
3772                 if (pos + 1  > parseText.length()) {
3773                     break;
3774                 }
3775                 char ch = parseText.charAt(pos++);
3776                 if (ch < '0' || ch > '9') {
3777                     pos--;
3778                     break;
3779                 }
3780                 chars[i] = ch;
3781                 available++;
3782             }
3783             if (available < minDigits) {
3784                 array[0] = ~array[0];
3785                 return;
3786             }
3787             switch (available) {
3788                 case 1:
3789                     array[1] = (chars[0] - 48);
3790                     break;
3791                 case 2:
3792                     array[1] = ((chars[0] - 48) * 10 + (chars[1] - 48));
3793                     break;
3794                 case 3:
3795                     array[1] = (chars[0] - 48);
3796                     array[2] = ((chars[1] - 48) * 10 + (chars[2] - 48));
3797                     break;
3798                 case 4:
3799                     array[1] = ((chars[0] - 48) * 10 + (chars[1] - 48));
3800                     array[2] = ((chars[2] - 48) * 10 + (chars[3] - 48));
3801                     break;
3802                 case 5:
3803                     array[1] = (chars[0] - 48);
3804                     array[2] = ((chars[1] - 48) * 10 + (chars[2] - 48));
3805                     array[3] = ((chars[3] - 48) * 10 + (chars[4] - 48));
3806                     break;
3807                 case 6:
3808                     array[1] = ((chars[0] - 48) * 10 + (chars[1] - 48));
3809                     array[2] = ((chars[2] - 48) * 10 + (chars[3] - 48));
3810                     array[3] = ((chars[4] - 48) * 10 + (chars[5] - 48));
3811                     break;
3812             }
3813             array[0] = pos;
3814         }
3815 
3816         @Override
3817         public String toString() {
3818             String converted = noOffsetText.replace("'", "''");
3819             return "Offset(" + PATTERNS[type] + ",'" + converted + "')";
3820         }
3821     }
3822 
3823     //-----------------------------------------------------------------------
3824     /**
3825      * Prints or parses an offset ID.
3826      */
3827     static final class LocalizedOffsetIdPrinterParser implements DateTimePrinterParser {
3828         private final TextStyle style;
3829 
3830         /**
3831          * Constructor.
3832          *
3833          * @param style  the style, not null
3834          */
3835         LocalizedOffsetIdPrinterParser(TextStyle style) {
3836             this.style = style;
3837         }
3838 
3839         private static StringBuilder appendHMS(StringBuilder buf, int t) {
3840             return buf.append((char)(t / 10 + '0'))
3841                       .append((char)(t % 10 + '0'));
3842         }
3843 
3844         @Override
3845         public boolean format(DateTimePrintContext context, StringBuilder buf) {
3846             Long offsetSecs = context.getValue(OFFSET_SECONDS);
3847             if (offsetSecs == null) {
3848                 return false;
3849             }
3850             String gmtText = "GMT";  // TODO: get localized version of 'GMT'
3851             buf.append(gmtText);
3852             int totalSecs = Math.toIntExact(offsetSecs);
3853             if (totalSecs != 0) {
3854                 int absHours = Math.abs((totalSecs / 3600) % 100);  // anything larger than 99 silently dropped
3855                 int absMinutes = Math.abs((totalSecs / 60) % 60);
3856                 int absSeconds = Math.abs(totalSecs % 60);
3857                 buf.append(totalSecs < 0 ? "-" : "+");
3858                 if (style == TextStyle.FULL) {
3859                     appendHMS(buf, absHours);
3860                     buf.append(':');
3861                     appendHMS(buf, absMinutes);
3862                     if (absSeconds != 0) {
3863                        buf.append(':');
3864                        appendHMS(buf, absSeconds);
3865                     }
3866                 } else {
3867                     if (absHours >= 10) {
3868                         buf.append((char)(absHours / 10 + '0'));
3869                     }
3870                     buf.append((char)(absHours % 10 + '0'));
3871                     if (absMinutes != 0 || absSeconds != 0) {
3872                         buf.append(':');
3873                         appendHMS(buf, absMinutes);
3874                         if (absSeconds != 0) {
3875                             buf.append(':');
3876                             appendHMS(buf, absSeconds);
3877                         }
3878                     }
3879                 }
3880             }
3881             return true;
3882         }
3883 
3884         int getDigit(CharSequence text, int position) {
3885             char c = text.charAt(position);
3886             if (c < '0' || c > '9') {
3887                 return -1;
3888             }
3889             return c - '0';
3890         }
3891 
3892         @Override
3893         public int parse(DateTimeParseContext context, CharSequence text, int position) {
3894             int pos = position;
3895             int end = text.length();
3896             String gmtText = "GMT";  // TODO: get localized version of 'GMT'
3897             if (!context.subSequenceEquals(text, pos, gmtText, 0, gmtText.length())) {
3898                     return ~position;
3899                 }
3900             pos += gmtText.length();
3901             // parse normal plus/minus offset
3902             int negative = 0;
3903             if (pos == end) {
3904                 return context.setParsedField(OFFSET_SECONDS, 0, position, pos);
3905             }
3906             char sign = text.charAt(pos);  // IOOBE if invalid position
3907             if (sign == '+') {
3908                 negative = 1;
3909             } else if (sign == '-') {
3910                 negative = -1;
3911             } else {
3912                 return context.setParsedField(OFFSET_SECONDS, 0, position, pos);
3913             }
3914             pos++;
3915             int h = 0;
3916             int m = 0;
3917             int s = 0;
3918             if (style == TextStyle.FULL) {
3919                 int h1 = getDigit(text, pos++);
3920                 int h2 = getDigit(text, pos++);
3921                 if (h1 < 0 || h2 < 0 || text.charAt(pos++) != ':') {
3922                     return ~position;
3923                 }
3924                 h = h1 * 10 + h2;
3925                 int m1 = getDigit(text, pos++);
3926                 int m2 = getDigit(text, pos++);
3927                 if (m1 < 0 || m2 < 0) {
3928                     return ~position;
3929                 }
3930                 m = m1 * 10 + m2;
3931                 if (pos + 2 < end && text.charAt(pos) == ':') {
3932                     int s1 = getDigit(text, pos + 1);
3933                     int s2 = getDigit(text, pos + 2);
3934                     if (s1 >= 0 && s2 >= 0) {
3935                         s = s1 * 10 + s2;
3936                         pos += 3;
3937                     }
3938                 }
3939             } else {
3940                 h = getDigit(text, pos++);
3941                 if (h < 0) {
3942                     return ~position;
3943                 }
3944                 if (pos < end) {
3945                     int h2 = getDigit(text, pos);
3946                     if (h2 >=0) {
3947                         h = h * 10 + h2;
3948                         pos++;
3949                     }
3950                     if (pos + 2 < end && text.charAt(pos) == ':') {
3951                         if (pos + 2 < end && text.charAt(pos) == ':') {
3952                             int m1 = getDigit(text, pos + 1);
3953                             int m2 = getDigit(text, pos + 2);
3954                             if (m1 >= 0 && m2 >= 0) {
3955                                 m = m1 * 10 + m2;
3956                                 pos += 3;
3957                                 if (pos + 2 < end && text.charAt(pos) == ':') {
3958                                     int s1 = getDigit(text, pos + 1);
3959                                     int s2 = getDigit(text, pos + 2);
3960                                     if (s1 >= 0 && s2 >= 0) {
3961                                         s = s1 * 10 + s2;
3962                                         pos += 3;
3963                                    }
3964                                 }
3965                             }
3966                         }
3967                     }
3968                 }
3969             }
3970             long offsetSecs = negative * (h * 3600L + m * 60L + s);
3971             return context.setParsedField(OFFSET_SECONDS, offsetSecs, position, pos);
3972         }
3973 
3974         @Override
3975         public String toString() {
3976             return "LocalizedOffset(" + style + ")";
3977         }
3978     }
3979 
3980     //-----------------------------------------------------------------------
3981     /**
3982      * Prints or parses a zone ID.
3983      */
3984     static final class ZoneTextPrinterParser extends ZoneIdPrinterParser {
3985 
3986         /** The text style to output. */
3987         private final TextStyle textStyle;
3988 
3989         /** The preferred zoneid map */
3990         private Set<String> preferredZones;
3991 
3992         /**  Display in generic time-zone format. True in case of pattern letter 'v' */
3993         private final boolean isGeneric;
3994         ZoneTextPrinterParser(TextStyle textStyle, Set<ZoneId> preferredZones, boolean isGeneric) {
3995             super(TemporalQueries.zone(), "ZoneText(" + textStyle + ")");
3996             this.textStyle = Objects.requireNonNull(textStyle, "textStyle");
3997             this.isGeneric = isGeneric;
3998             if (preferredZones != null && preferredZones.size() != 0) {
3999                 this.preferredZones = new HashSet<>();
4000                 for (ZoneId id : preferredZones) {
4001                     this.preferredZones.add(id.getId());
4002                 }
4003             }
4004         }
4005 
4006         private static final int STD = 0;
4007         private static final int DST = 1;
4008         private static final int GENERIC = 2;
4009         private static final Map<String, SoftReference<Map<Locale, String[]>>> cache =
4010             new ConcurrentHashMap<>();
4011 
4012         private String getDisplayName(String id, int type, Locale locale) {
4013             if (textStyle == TextStyle.NARROW) {
4014                 return null;
4015             }
4016             String[] names;
4017             SoftReference<Map<Locale, String[]>> ref = cache.get(id);
4018             Map<Locale, String[]> perLocale = null;
4019             if (ref == null || (perLocale = ref.get()) == null ||
4020                 (names = perLocale.get(locale)) == null) {
4021                 names = TimeZoneNameUtility.retrieveDisplayNames(id, locale);
4022                 if (names == null) {
4023                     return null;
4024                 }
4025                 names = Arrays.copyOfRange(names, 0, 7);
4026                 names[5] =
4027                     TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.LONG, locale);
4028                 if (names[5] == null) {
4029                     names[5] = names[0]; // use the id
4030                 }
4031                 names[6] =
4032                     TimeZoneNameUtility.retrieveGenericDisplayName(id, TimeZone.SHORT, locale);
4033                 if (names[6] == null) {
4034                     names[6] = names[0];
4035                 }
4036                 if (perLocale == null) {
4037                     perLocale = new ConcurrentHashMap<>();
4038                 }
4039                 perLocale.put(locale, names);
4040                 cache.put(id, new SoftReference<>(perLocale));
4041             }
4042             switch (type) {
4043             case STD:
4044                 return names[textStyle.zoneNameStyleIndex() + 1];
4045             case DST:
4046                 return names[textStyle.zoneNameStyleIndex() + 3];
4047             }
4048             return names[textStyle.zoneNameStyleIndex() + 5];
4049         }
4050 
4051         @Override
4052         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4053             ZoneId zone = context.getValue(TemporalQueries.zoneId());
4054             if (zone == null) {
4055                 return false;
4056             }
4057             String zname = zone.getId();
4058             if (!(zone instanceof ZoneOffset)) {
4059                 TemporalAccessor dt = context.getTemporal();
4060                 int type = GENERIC;
4061                 if (!isGeneric) {
4062                     if (dt.isSupported(ChronoField.INSTANT_SECONDS)) {
4063                         type = zone.getRules().isDaylightSavings(Instant.from(dt)) ? DST : STD;
4064                     } else if (dt.isSupported(ChronoField.EPOCH_DAY) &&
4065                                dt.isSupported(ChronoField.NANO_OF_DAY)) {
4066                         LocalDate date = LocalDate.ofEpochDay(dt.getLong(ChronoField.EPOCH_DAY));
4067                         LocalTime time = LocalTime.ofNanoOfDay(dt.getLong(ChronoField.NANO_OF_DAY));
4068                         LocalDateTime ldt = date.atTime(time);
4069                         if (zone.getRules().getTransition(ldt) == null) {
4070                             type = zone.getRules().isDaylightSavings(ldt.atZone(zone).toInstant()) ? DST : STD;
4071                         }
4072                     }
4073                 }
4074                 String name = getDisplayName(zname, type, context.getLocale());
4075                 if (name != null) {
4076                     zname = name;
4077                 }
4078             }
4079             buf.append(zname);
4080             return true;
4081         }
4082 
4083         // cache per instance for now
4084         private final Map<Locale, Entry<Integer, SoftReference<PrefixTree>>>
4085             cachedTree = new HashMap<>();
4086         private final Map<Locale, Entry<Integer, SoftReference<PrefixTree>>>
4087             cachedTreeCI = new HashMap<>();
4088 
4089         @Override
4090         protected PrefixTree getTree(DateTimeParseContext context) {
4091             if (textStyle == TextStyle.NARROW) {
4092                 return super.getTree(context);
4093             }
4094             Locale locale = context.getLocale();
4095             boolean isCaseSensitive = context.isCaseSensitive();
4096             Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
4097             int regionIdsSize = regionIds.size();
4098 
4099             Map<Locale, Entry<Integer, SoftReference<PrefixTree>>> cached =
4100                 isCaseSensitive ? cachedTree : cachedTreeCI;
4101 
4102             Entry<Integer, SoftReference<PrefixTree>> entry = null;
4103             PrefixTree tree = null;
4104             String[][] zoneStrings = null;
4105             if ((entry = cached.get(locale)) == null ||
4106                 (entry.getKey() != regionIdsSize ||
4107                 (tree = entry.getValue().get()) == null)) {
4108                 tree = PrefixTree.newTree(context);
4109                 zoneStrings = TimeZoneNameUtility.getZoneStrings(locale);
4110                 for (String[] names : zoneStrings) {
4111                     String zid = names[0];
4112                     if (!regionIds.contains(zid)) {
4113                         continue;
4114                     }
4115                     tree.add(zid, zid);    // don't convert zid -> metazone
4116                     zid = ZoneName.toZid(zid, locale);
4117                     int i = textStyle == TextStyle.FULL ? 1 : 2;
4118                     for (; i < names.length; i += 2) {
4119                         tree.add(names[i], zid);
4120                     }
4121                 }
4122                 // if we have a set of preferred zones, need a copy and
4123                 // add the preferred zones again to overwrite
4124                 if (preferredZones != null) {
4125                     for (String[] names : zoneStrings) {
4126                         String zid = names[0];
4127                         if (!preferredZones.contains(zid) || !regionIds.contains(zid)) {
4128                             continue;
4129                         }
4130                         int i = textStyle == TextStyle.FULL ? 1 : 2;
4131                         for (; i < names.length; i += 2) {
4132                             tree.add(names[i], zid);
4133                        }
4134                     }
4135                 }
4136                 cached.put(locale, new SimpleImmutableEntry<>(regionIdsSize, new SoftReference<>(tree)));
4137             }
4138             return tree;
4139         }
4140     }
4141 
4142     //-----------------------------------------------------------------------
4143     /**
4144      * Prints or parses a zone ID.
4145      */
4146     static class ZoneIdPrinterParser implements DateTimePrinterParser {
4147         private final TemporalQuery<ZoneId> query;
4148         private final String description;
4149 
4150         ZoneIdPrinterParser(TemporalQuery<ZoneId> query, String description) {
4151             this.query = query;
4152             this.description = description;
4153         }
4154 
4155         @Override
4156         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4157             ZoneId zone = context.getValue(query);
4158             if (zone == null) {
4159                 return false;
4160             }
4161             buf.append(zone.getId());
4162             return true;
4163         }
4164 
4165         /**
4166          * The cached tree to speed up parsing.
4167          */
4168         private static volatile Entry<Integer, PrefixTree> cachedPrefixTree;
4169         private static volatile Entry<Integer, PrefixTree> cachedPrefixTreeCI;
4170 
4171         protected PrefixTree getTree(DateTimeParseContext context) {
4172             // prepare parse tree
4173             Set<String> regionIds = ZoneRulesProvider.getAvailableZoneIds();
4174             final int regionIdsSize = regionIds.size();
4175             Entry<Integer, PrefixTree> cached = context.isCaseSensitive()
4176                                                 ? cachedPrefixTree : cachedPrefixTreeCI;
4177             if (cached == null || cached.getKey() != regionIdsSize) {
4178                 synchronized (this) {
4179                     cached = context.isCaseSensitive() ? cachedPrefixTree : cachedPrefixTreeCI;
4180                     if (cached == null || cached.getKey() != regionIdsSize) {
4181                         cached = new SimpleImmutableEntry<>(regionIdsSize, PrefixTree.newTree(regionIds, context));
4182                         if (context.isCaseSensitive()) {
4183                             cachedPrefixTree = cached;
4184                         } else {
4185                             cachedPrefixTreeCI = cached;
4186                         }
4187                     }
4188                 }
4189             }
4190             return cached.getValue();
4191         }
4192 
4193         /**
4194          * This implementation looks for the longest matching string.
4195          * For example, parsing Etc/GMT-2 will return Etc/GMC-2 rather than just
4196          * Etc/GMC although both are valid.
4197          */
4198         @Override
4199         public int parse(DateTimeParseContext context, CharSequence text, int position) {
4200             int length = text.length();
4201             if (position > length) {
4202                 throw new IndexOutOfBoundsException();
4203             }
4204             if (position == length) {
4205                 return ~position;
4206             }
4207 
4208             // handle fixed time-zone IDs
4209             char nextChar = text.charAt(position);
4210             if (nextChar == '+' || nextChar == '-') {
4211                 return parseOffsetBased(context, text, position, position, OffsetIdPrinterParser.INSTANCE_ID_Z);
4212             } else if (length >= position + 2) {
4213                 char nextNextChar = text.charAt(position + 1);
4214                 if (context.charEquals(nextChar, 'U') && context.charEquals(nextNextChar, 'T')) {
4215                     if (length >= position + 3 && context.charEquals(text.charAt(position + 2), 'C')) {
4216                         return parseOffsetBased(context, text, position, position + 3, OffsetIdPrinterParser.INSTANCE_ID_ZERO);
4217                     }
4218                     return parseOffsetBased(context, text, position, position + 2, OffsetIdPrinterParser.INSTANCE_ID_ZERO);
4219                 } else if (context.charEquals(nextChar, 'G') && length >= position + 3 &&
4220                         context.charEquals(nextNextChar, 'M') && context.charEquals(text.charAt(position + 2), 'T')) {
4221                     if (length >= position + 4 && context.charEquals(text.charAt(position + 3), '0')) {
4222                         context.setParsed(ZoneId.of("GMT0"));
4223                         return position + 4;
4224                     }
4225                     return parseOffsetBased(context, text, position, position + 3, OffsetIdPrinterParser.INSTANCE_ID_ZERO);
4226                 }
4227             }
4228 
4229             // parse
4230             PrefixTree tree = getTree(context);
4231             ParsePosition ppos = new ParsePosition(position);
4232             String parsedZoneId = tree.match(text, ppos);
4233             if (parsedZoneId == null) {
4234                 if (context.charEquals(nextChar, 'Z')) {
4235                     context.setParsed(ZoneOffset.UTC);
4236                     return position + 1;
4237                 }
4238                 return ~position;
4239             }
4240             context.setParsed(ZoneId.of(parsedZoneId));
4241             return ppos.getIndex();
4242         }
4243 
4244         /**
4245          * Parse an offset following a prefix and set the ZoneId if it is valid.
4246          * To matching the parsing of ZoneId.of the values are not normalized
4247          * to ZoneOffsets.
4248          *
4249          * @param context the parse context
4250          * @param text the input text
4251          * @param prefixPos start of the prefix
4252          * @param position start of text after the prefix
4253          * @param parser parser for the value after the prefix
4254          * @return the position after the parse
4255          */
4256         private int parseOffsetBased(DateTimeParseContext context, CharSequence text, int prefixPos, int position, OffsetIdPrinterParser parser) {
4257             String prefix = text.toString().substring(prefixPos, position).toUpperCase();
4258             if (position >= text.length()) {
4259                 context.setParsed(ZoneId.of(prefix));
4260                 return position;
4261             }
4262 
4263             // '0' or 'Z' after prefix is not part of a valid ZoneId; use bare prefix
4264             if (text.charAt(position) == '0' ||
4265                 context.charEquals(text.charAt(position), 'Z')) {
4266                 context.setParsed(ZoneId.of(prefix));
4267                 return position;
4268             }
4269 
4270             DateTimeParseContext newContext = context.copy();
4271             int endPos = parser.parse(newContext, text, position);
4272             try {
4273                 if (endPos < 0) {
4274                     if (parser == OffsetIdPrinterParser.INSTANCE_ID_Z) {
4275                         return ~prefixPos;
4276                     }
4277                     context.setParsed(ZoneId.of(prefix));
4278                     return position;
4279                 }
4280                 int offset = (int) newContext.getParsed(OFFSET_SECONDS).longValue();
4281                 ZoneOffset zoneOffset = ZoneOffset.ofTotalSeconds(offset);
4282                 context.setParsed(ZoneId.ofOffset(prefix, zoneOffset));
4283                 return endPos;
4284             } catch (DateTimeException dte) {
4285                 return ~prefixPos;
4286             }
4287         }
4288 
4289         @Override
4290         public String toString() {
4291             return description;
4292         }
4293     }
4294 
4295     //-----------------------------------------------------------------------
4296     /**
4297      * A String based prefix tree for parsing time-zone names.
4298      */
4299     static class PrefixTree {
4300         protected String key;
4301         protected String value;
4302         protected char c0;    // performance optimization to avoid the
4303                               // boundary check cost of key.charat(0)
4304         protected PrefixTree child;
4305         protected PrefixTree sibling;
4306 
4307         private PrefixTree(String k, String v, PrefixTree child) {
4308             this.key = k;
4309             this.value = v;
4310             this.child = child;
4311             if (k.length() == 0){
4312                 c0 = 0xffff;
4313             } else {
4314                 c0 = key.charAt(0);
4315             }
4316         }
4317 
4318         /**
4319          * Creates a new prefix parsing tree based on parse context.
4320          *
4321          * @param context  the parse context
4322          * @return the tree, not null
4323          */
4324         public static PrefixTree newTree(DateTimeParseContext context) {
4325             //if (!context.isStrict()) {
4326             //    return new LENIENT("", null, null);
4327             //}
4328             if (context.isCaseSensitive()) {
4329                 return new PrefixTree("", null, null);
4330             }
4331             return new CI("", null, null);
4332         }
4333 
4334         /**
4335          * Creates a new prefix parsing tree.
4336          *
4337          * @param keys  a set of strings to build the prefix parsing tree, not null
4338          * @param context  the parse context
4339          * @return the tree, not null
4340          */
4341         public static  PrefixTree newTree(Set<String> keys, DateTimeParseContext context) {
4342             PrefixTree tree = newTree(context);
4343             for (String k : keys) {
4344                 tree.add0(k, k);
4345             }
4346             return tree;
4347         }
4348 
4349         /**
4350          * Clone a copy of this tree
4351          */
4352         public PrefixTree copyTree() {
4353             PrefixTree copy = new PrefixTree(key, value, null);
4354             if (child != null) {
4355                 copy.child = child.copyTree();
4356             }
4357             if (sibling != null) {
4358                 copy.sibling = sibling.copyTree();
4359             }
4360             return copy;
4361         }
4362 
4363 
4364         /**
4365          * Adds a pair of {key, value} into the prefix tree.
4366          *
4367          * @param k  the key, not null
4368          * @param v  the value, not null
4369          * @return  true if the pair is added successfully
4370          */
4371         public boolean add(String k, String v) {
4372             return add0(k, v);
4373         }
4374 
4375         private boolean add0(String k, String v) {
4376             k = toKey(k);
4377             int prefixLen = prefixLength(k);
4378             if (prefixLen == key.length()) {
4379                 if (prefixLen < k.length()) {  // down the tree
4380                     String subKey = k.substring(prefixLen);
4381                     PrefixTree c = child;
4382                     while (c != null) {
4383                         if (isEqual(c.c0, subKey.charAt(0))) {
4384                             return c.add0(subKey, v);
4385                         }
4386                         c = c.sibling;
4387                     }
4388                     // add the node as the child of the current node
4389                     c = newNode(subKey, v, null);
4390                     c.sibling = child;
4391                     child = c;
4392                     return true;
4393                 }
4394                 // have an existing <key, value> already, overwrite it
4395                 // if (value != null) {
4396                 //    return false;
4397                 //}
4398                 value = v;
4399                 return true;
4400             }
4401             // split the existing node
4402             PrefixTree n1 = newNode(key.substring(prefixLen), value, child);
4403             key = k.substring(0, prefixLen);
4404             child = n1;
4405             if (prefixLen < k.length()) {
4406                 PrefixTree n2 = newNode(k.substring(prefixLen), v, null);
4407                 child.sibling = n2;
4408                 value = null;
4409             } else {
4410                 value = v;
4411             }
4412             return true;
4413         }
4414 
4415         /**
4416          * Match text with the prefix tree.
4417          *
4418          * @param text  the input text to parse, not null
4419          * @param off  the offset position to start parsing at
4420          * @param end  the end position to stop parsing
4421          * @return the resulting string, or null if no match found.
4422          */
4423         public String match(CharSequence text, int off, int end) {
4424             if (!prefixOf(text, off, end)){
4425                 return null;
4426             }
4427             if (child != null && (off += key.length()) != end) {
4428                 PrefixTree c = child;
4429                 do {
4430                     if (isEqual(c.c0, text.charAt(off))) {
4431                         String found = c.match(text, off, end);
4432                         if (found != null) {
4433                             return found;
4434                         }
4435                         return value;
4436                     }
4437                     c = c.sibling;
4438                 } while (c != null);
4439             }
4440             return value;
4441         }
4442 
4443         /**
4444          * Match text with the prefix tree.
4445          *
4446          * @param text  the input text to parse, not null
4447          * @param pos  the position to start parsing at, from 0 to the text
4448          *  length. Upon return, position will be updated to the new parse
4449          *  position, or unchanged, if no match found.
4450          * @return the resulting string, or null if no match found.
4451          */
4452         public String match(CharSequence text, ParsePosition pos) {
4453             int off = pos.getIndex();
4454             int end = text.length();
4455             if (!prefixOf(text, off, end)){
4456                 return null;
4457             }
4458             off += key.length();
4459             if (child != null && off != end) {
4460                 PrefixTree c = child;
4461                 do {
4462                     if (isEqual(c.c0, text.charAt(off))) {
4463                         pos.setIndex(off);
4464                         String found = c.match(text, pos);
4465                         if (found != null) {
4466                             return found;
4467                         }
4468                         break;
4469                     }
4470                     c = c.sibling;
4471                 } while (c != null);
4472             }
4473             pos.setIndex(off);
4474             return value;
4475         }
4476 
4477         protected String toKey(String k) {
4478             return k;
4479         }
4480 
4481         protected PrefixTree newNode(String k, String v, PrefixTree child) {
4482             return new PrefixTree(k, v, child);
4483         }
4484 
4485         protected boolean isEqual(char c1, char c2) {
4486             return c1 == c2;
4487         }
4488 
4489         protected boolean prefixOf(CharSequence text, int off, int end) {
4490             if (text instanceof String) {
4491                 return ((String)text).startsWith(key, off);
4492             }
4493             int len = key.length();
4494             if (len > end - off) {
4495                 return false;
4496             }
4497             int off0 = 0;
4498             while (len-- > 0) {
4499                 if (!isEqual(key.charAt(off0++), text.charAt(off++))) {
4500                     return false;
4501                 }
4502             }
4503             return true;
4504         }
4505 
4506         private int prefixLength(String k) {
4507             int off = 0;
4508             while (off < k.length() && off < key.length()) {
4509                 if (!isEqual(k.charAt(off), key.charAt(off))) {
4510                     return off;
4511                 }
4512                 off++;
4513             }
4514             return off;
4515         }
4516 
4517         /**
4518          * Case Insensitive prefix tree.
4519          */
4520         private static class CI extends PrefixTree {
4521 
4522             private CI(String k, String v, PrefixTree child) {
4523                 super(k, v, child);
4524             }
4525 
4526             @Override
4527             protected CI newNode(String k, String v, PrefixTree child) {
4528                 return new CI(k, v, child);
4529             }
4530 
4531             @Override
4532             protected boolean isEqual(char c1, char c2) {
4533                 return DateTimeParseContext.charEqualsIgnoreCase(c1, c2);
4534             }
4535 
4536             @Override
4537             protected boolean prefixOf(CharSequence text, int off, int end) {
4538                 int len = key.length();
4539                 if (len > end - off) {
4540                     return false;
4541                 }
4542                 int off0 = 0;
4543                 while (len-- > 0) {
4544                     if (!isEqual(key.charAt(off0++), text.charAt(off++))) {
4545                         return false;
4546                     }
4547                 }
4548                 return true;
4549             }
4550         }
4551 
4552         /**
4553          * Lenient prefix tree. Case insensitive and ignores characters
4554          * like space, underscore and slash.
4555          */
4556         private static class LENIENT extends CI {
4557 
4558             private LENIENT(String k, String v, PrefixTree child) {
4559                 super(k, v, child);
4560             }
4561 
4562             @Override
4563             protected CI newNode(String k, String v, PrefixTree child) {
4564                 return new LENIENT(k, v, child);
4565             }
4566 
4567             private boolean isLenientChar(char c) {
4568                 return c == ' ' || c == '_' || c == '/';
4569             }
4570 
4571             protected String toKey(String k) {
4572                 for (int i = 0; i < k.length(); i++) {
4573                     if (isLenientChar(k.charAt(i))) {
4574                         StringBuilder sb = new StringBuilder(k.length());
4575                         sb.append(k, 0, i);
4576                         i++;
4577                         while (i < k.length()) {
4578                             if (!isLenientChar(k.charAt(i))) {
4579                                 sb.append(k.charAt(i));
4580                             }
4581                             i++;
4582                         }
4583                         return sb.toString();
4584                     }
4585                 }
4586                 return k;
4587             }
4588 
4589             @Override
4590             public String match(CharSequence text, ParsePosition pos) {
4591                 int off = pos.getIndex();
4592                 int end = text.length();
4593                 int len = key.length();
4594                 int koff = 0;
4595                 while (koff < len && off < end) {
4596                     if (isLenientChar(text.charAt(off))) {
4597                         off++;
4598                         continue;
4599                     }
4600                     if (!isEqual(key.charAt(koff++), text.charAt(off++))) {
4601                         return null;
4602                     }
4603                 }
4604                 if (koff != len) {
4605                     return null;
4606                 }
4607                 if (child != null && off != end) {
4608                     int off0 = off;
4609                     while (off0 < end && isLenientChar(text.charAt(off0))) {
4610                         off0++;
4611                     }
4612                     if (off0 < end) {
4613                         PrefixTree c = child;
4614                         do {
4615                             if (isEqual(c.c0, text.charAt(off0))) {
4616                                 pos.setIndex(off0);
4617                                 String found = c.match(text, pos);
4618                                 if (found != null) {
4619                                     return found;
4620                                 }
4621                                 break;
4622                             }
4623                             c = c.sibling;
4624                         } while (c != null);
4625                     }
4626                 }
4627                 pos.setIndex(off);
4628                 return value;
4629             }
4630         }
4631     }
4632 
4633     //-----------------------------------------------------------------------
4634     /**
4635      * Prints or parses a chronology.
4636      */
4637     static final class ChronoPrinterParser implements DateTimePrinterParser {
4638         /** The text style to output, null means the ID. */
4639         private final TextStyle textStyle;
4640 
4641         ChronoPrinterParser(TextStyle textStyle) {
4642             // validated by caller
4643             this.textStyle = textStyle;
4644         }
4645 
4646         @Override
4647         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4648             Chronology chrono = context.getValue(TemporalQueries.chronology());
4649             if (chrono == null) {
4650                 return false;
4651             }
4652             if (textStyle == null) {
4653                 buf.append(chrono.getId());
4654             } else {
4655                 buf.append(getChronologyName(chrono, context.getLocale()));
4656             }
4657             return true;
4658         }
4659 
4660         @Override
4661         public int parse(DateTimeParseContext context, CharSequence text, int position) {
4662             // simple looping parser to find the chronology
4663             if (position < 0 || position > text.length()) {
4664                 throw new IndexOutOfBoundsException();
4665             }
4666             Set<Chronology> chronos = Chronology.getAvailableChronologies();
4667             Chronology bestMatch = null;
4668             int matchLen = -1;
4669             for (Chronology chrono : chronos) {
4670                 String name;
4671                 if (textStyle == null) {
4672                     name = chrono.getId();
4673                 } else {
4674                     name = getChronologyName(chrono, context.getLocale());
4675                 }
4676                 int nameLen = name.length();
4677                 if (nameLen > matchLen && context.subSequenceEquals(text, position, name, 0, nameLen)) {
4678                     bestMatch = chrono;
4679                     matchLen = nameLen;
4680                 }
4681             }
4682             if (bestMatch == null) {
4683                 return ~position;
4684             }
4685             context.setParsed(bestMatch);
4686             return position + matchLen;
4687         }
4688 
4689         /**
4690          * Returns the chronology name of the given chrono in the given locale
4691          * if available, or the chronology Id otherwise. The regular ResourceBundle
4692          * search path is used for looking up the chronology name.
4693          *
4694          * @param chrono  the chronology, not null
4695          * @param locale  the locale, not null
4696          * @return the chronology name of chrono in locale, or the id if no name is available
4697          * @throws NullPointerException if chrono or locale is null
4698          */
4699         private String getChronologyName(Chronology chrono, Locale locale) {
4700             String key = "calendarname." + chrono.getCalendarType();
4701             String name = DateTimeTextProvider.getLocalizedResource(key, locale);
4702             return Objects.requireNonNullElseGet(name, () -> chrono.getId());
4703         }
4704     }
4705 
4706     //-----------------------------------------------------------------------
4707     /**
4708      * Prints or parses a localized pattern.
4709      */
4710     static final class LocalizedPrinterParser implements DateTimePrinterParser {
4711         /** Cache of formatters. */
4712         private static final ConcurrentMap<String, DateTimeFormatter> FORMATTER_CACHE = new ConcurrentHashMap<>(16, 0.75f, 2);
4713 
4714         private final FormatStyle dateStyle;
4715         private final FormatStyle timeStyle;
4716 
4717         /**
4718          * Constructor.
4719          *
4720          * @param dateStyle  the date style to use, may be null
4721          * @param timeStyle  the time style to use, may be null
4722          */
4723         LocalizedPrinterParser(FormatStyle dateStyle, FormatStyle timeStyle) {
4724             // validated by caller
4725             this.dateStyle = dateStyle;
4726             this.timeStyle = timeStyle;
4727         }
4728 
4729         @Override
4730         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4731             Chronology chrono = Chronology.from(context.getTemporal());
4732             return formatter(context.getLocale(), chrono).toPrinterParser(false).format(context, buf);
4733         }
4734 
4735         @Override
4736         public int parse(DateTimeParseContext context, CharSequence text, int position) {
4737             Chronology chrono = context.getEffectiveChronology();
4738             return formatter(context.getLocale(), chrono).toPrinterParser(false).parse(context, text, position);
4739         }
4740 
4741         /**
4742          * Gets the formatter to use.
4743          * <p>
4744          * The formatter will be the most appropriate to use for the date and time style in the locale.
4745          * For example, some locales will use the month name while others will use the number.
4746          *
4747          * @param locale  the locale to use, not null
4748          * @param chrono  the chronology to use, not null
4749          * @return the formatter, not null
4750          * @throws IllegalArgumentException if the formatter cannot be found
4751          */
4752         private DateTimeFormatter formatter(Locale locale, Chronology chrono) {
4753             String key = chrono.getId() + '|' + locale.toString() + '|' + dateStyle + timeStyle;
4754             DateTimeFormatter formatter = FORMATTER_CACHE.get(key);
4755             if (formatter == null) {
4756                 String pattern = getLocalizedDateTimePattern(dateStyle, timeStyle, chrono, locale);
4757                 formatter = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(locale);
4758                 DateTimeFormatter old = FORMATTER_CACHE.putIfAbsent(key, formatter);
4759                 if (old != null) {
4760                     formatter = old;
4761                 }
4762             }
4763             return formatter;
4764         }
4765 
4766         @Override
4767         public String toString() {
4768             return "Localized(" + (dateStyle != null ? dateStyle : "") + "," +
4769                 (timeStyle != null ? timeStyle : "") + ")";
4770         }
4771     }
4772 
4773     //-----------------------------------------------------------------------
4774     /**
4775      * Prints or parses a localized pattern from a localized field.
4776      * The specific formatter and parameters is not selected until the
4777      * the field is to be printed or parsed.
4778      * The locale is needed to select the proper WeekFields from which
4779      * the field for day-of-week, week-of-month, or week-of-year is selected.
4780      * Hence the inherited field NumberPrinterParser.field is unused.
4781      */
4782     static final class WeekBasedFieldPrinterParser extends NumberPrinterParser {
4783         private char chr;
4784         private int count;
4785 
4786         /**
4787          * Constructor.
4788          *
4789          * @param chr the pattern format letter that added this PrinterParser.
4790          * @param count the repeat count of the format letter
4791          * @param minWidth  the minimum field width, from 1 to 19
4792          * @param maxWidth  the maximum field width, from minWidth to 19
4793          */
4794         WeekBasedFieldPrinterParser(char chr, int count, int minWidth, int maxWidth) {
4795             this(chr, count, minWidth, maxWidth, 0);
4796         }
4797 
4798         /**
4799          * Constructor.
4800          *
4801          * @param chr the pattern format letter that added this PrinterParser.
4802          * @param count the repeat count of the format letter
4803          * @param minWidth  the minimum field width, from 1 to 19
4804          * @param maxWidth  the maximum field width, from minWidth to 19
4805          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater,
4806          * -1 if fixed width due to active adjacent parsing
4807          */
4808         WeekBasedFieldPrinterParser(char chr, int count, int minWidth, int maxWidth,
4809                 int subsequentWidth) {
4810             super(null, minWidth, maxWidth, SignStyle.NOT_NEGATIVE, subsequentWidth);
4811             this.chr = chr;
4812             this.count = count;
4813         }
4814 
4815         /**
4816          * Returns a new instance with fixed width flag set.
4817          *
4818          * @return a new updated printer-parser, not null
4819          */
4820         @Override
4821         WeekBasedFieldPrinterParser withFixedWidth() {
4822             if (subsequentWidth == -1) {
4823                 return this;
4824             }
4825             return new WeekBasedFieldPrinterParser(chr, count, minWidth, maxWidth, -1);
4826         }
4827 
4828         /**
4829          * Returns a new instance with an updated subsequent width.
4830          *
4831          * @param subsequentWidth  the width of subsequent non-negative numbers, 0 or greater
4832          * @return a new updated printer-parser, not null
4833          */
4834         @Override
4835         WeekBasedFieldPrinterParser withSubsequentWidth(int subsequentWidth) {
4836             return new WeekBasedFieldPrinterParser(chr, count, minWidth, maxWidth,
4837                     this.subsequentWidth + subsequentWidth);
4838         }
4839 
4840         @Override
4841         public boolean format(DateTimePrintContext context, StringBuilder buf) {
4842             return printerParser(context.getLocale()).format(context, buf);
4843         }
4844 
4845         @Override
4846         public int parse(DateTimeParseContext context, CharSequence text, int position) {
4847             return printerParser(context.getLocale()).parse(context, text, position);
4848         }
4849 
4850         /**
4851          * Gets the printerParser to use based on the field and the locale.
4852          *
4853          * @param locale  the locale to use, not null
4854          * @return the formatter, not null
4855          * @throws IllegalArgumentException if the formatter cannot be found
4856          */
4857         private DateTimePrinterParser printerParser(Locale locale) {
4858             WeekFields weekDef = WeekFields.of(locale);
4859             TemporalField field = null;
4860             switch (chr) {
4861                 case 'Y':
4862                     field = weekDef.weekBasedYear();
4863                     if (count == 2) {
4864                         return new ReducedPrinterParser(field, 2, 2, 0, ReducedPrinterParser.BASE_DATE,
4865                                 this.subsequentWidth);
4866                     } else {
4867                         return new NumberPrinterParser(field, count, 19,
4868                                 (count < 4) ? SignStyle.NORMAL : SignStyle.EXCEEDS_PAD,
4869                                 this.subsequentWidth);
4870                     }
4871                 case 'e':
4872                 case 'c':
4873                     field = weekDef.dayOfWeek();
4874                     break;
4875                 case 'w':
4876                     field = weekDef.weekOfWeekBasedYear();
4877                     break;
4878                 case 'W':
4879                     field = weekDef.weekOfMonth();
4880                     break;
4881                 default:
4882                     throw new IllegalStateException("unreachable");
4883             }
4884             return new NumberPrinterParser(field, minWidth, maxWidth, SignStyle.NOT_NEGATIVE,
4885                     this.subsequentWidth);
4886         }
4887 
4888         @Override
4889         public String toString() {
4890             StringBuilder sb = new StringBuilder(30);
4891             sb.append("Localized(");
4892             if (chr == 'Y') {
4893                 if (count == 1) {
4894                     sb.append("WeekBasedYear");
4895                 } else if (count == 2) {
4896                     sb.append("ReducedValue(WeekBasedYear,2,2,2000-01-01)");
4897                 } else {
4898                     sb.append("WeekBasedYear,").append(count).append(",")
4899                             .append(19).append(",")
4900                             .append((count < 4) ? SignStyle.NORMAL : SignStyle.EXCEEDS_PAD);
4901                 }
4902             } else {
4903                 switch (chr) {
4904                     case 'c':
4905                     case 'e':
4906                         sb.append("DayOfWeek");
4907                         break;
4908                     case 'w':
4909                         sb.append("WeekOfWeekBasedYear");
4910                         break;
4911                     case 'W':
4912                         sb.append("WeekOfMonth");
4913                         break;
4914                     default:
4915                         break;
4916                 }
4917                 sb.append(",");
4918                 sb.append(count);
4919             }
4920             sb.append(")");
4921             return sb.toString();
4922         }
4923     }
4924 
4925     //-------------------------------------------------------------------------
4926     /**
4927      * Length comparator.
4928      */
4929     static final Comparator<String> LENGTH_SORT = new Comparator<String>() {
4930         @Override
4931         public int compare(String str1, String str2) {
4932             return str1.length() == str2.length() ? str1.compareTo(str2) : str1.length() - str2.length();
4933         }
4934     };
4935 }
--- EOF ---