Path: blob/master/src/java.base/share/classes/java/time/temporal/ValueRange.java
41159 views
/*1* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425/*26* This file is available under and governed by the GNU General Public27* License version 2 only, as published by the Free Software Foundation.28* However, the following notice accompanied the original version of this29* file:30*31* Copyright (c) 2011-2012, Stephen Colebourne & Michael Nascimento Santos32*33* All rights reserved.34*35* Redistribution and use in source and binary forms, with or without36* modification, are permitted provided that the following conditions are met:37*38* * Redistributions of source code must retain the above copyright notice,39* this list of conditions and the following disclaimer.40*41* * Redistributions in binary form must reproduce the above copyright notice,42* this list of conditions and the following disclaimer in the documentation43* and/or other materials provided with the distribution.44*45* * Neither the name of JSR-310 nor the names of its contributors46* may be used to endorse or promote products derived from this software47* without specific prior written permission.48*49* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS50* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT51* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR52* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR53* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,54* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,55* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR56* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF57* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING58* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS59* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.60*/61package java.time.temporal;6263import java.io.IOException;64import java.io.InvalidObjectException;65import java.io.ObjectInputStream;66import java.io.Serializable;67import java.time.DateTimeException;6869/**70* The range of valid values for a date-time field.71* <p>72* All {@link TemporalField} instances have a valid range of values.73* For example, the ISO day-of-month runs from 1 to somewhere between 28 and 31.74* This class captures that valid range.75* <p>76* It is important to be aware of the limitations of this class.77* Only the minimum and maximum values are provided.78* It is possible for there to be invalid values within the outer range.79* For example, a weird field may have valid values of 1, 2, 4, 6, 7, thus80* have a range of '1 - 7', despite that fact that values 3 and 5 are invalid.81* <p>82* Instances of this class are not tied to a specific field.83*84* @implSpec85* This class is immutable and thread-safe.86*87* @since 1.888*/89public final class ValueRange implements Serializable {9091/**92* Serialization version.93*/94@java.io.Serial95private static final long serialVersionUID = -7317881728594519368L;9697/**98* The smallest minimum value.99*/100private final long minSmallest;101/**102* The largest minimum value.103*/104private final long minLargest;105/**106* The smallest maximum value.107*/108private final long maxSmallest;109/**110* The largest maximum value.111*/112private final long maxLargest;113114/**115* Obtains a fixed value range.116* <p>117* This factory obtains a range where the minimum and maximum values are fixed.118* For example, the ISO month-of-year always runs from 1 to 12.119*120* @param min the minimum value121* @param max the maximum value122* @return the ValueRange for min, max, not null123* @throws IllegalArgumentException if the minimum is greater than the maximum124*/125public static ValueRange of(long min, long max) {126if (min > max) {127throw new IllegalArgumentException("Minimum value must be less than maximum value");128}129return new ValueRange(min, min, max, max);130}131132/**133* Obtains a variable value range.134* <p>135* This factory obtains a range where the minimum value is fixed and the maximum value may vary.136* For example, the ISO day-of-month always starts at 1, but ends between 28 and 31.137*138* @param min the minimum value139* @param maxSmallest the smallest maximum value140* @param maxLargest the largest maximum value141* @return the ValueRange for min, smallest max, largest max, not null142* @throws IllegalArgumentException if143* the minimum is greater than the smallest maximum,144* or the smallest maximum is greater than the largest maximum145*/146public static ValueRange of(long min, long maxSmallest, long maxLargest) {147if (min > maxSmallest) {148throw new IllegalArgumentException("Minimum value must be less than smallest maximum value");149}150return of(min, min, maxSmallest, maxLargest);151}152153/**154* Obtains a fully variable value range.155* <p>156* This factory obtains a range where both the minimum and maximum value may vary.157*158* @param minSmallest the smallest minimum value159* @param minLargest the largest minimum value160* @param maxSmallest the smallest maximum value161* @param maxLargest the largest maximum value162* @return the ValueRange for smallest min, largest min, smallest max, largest max, not null163* @throws IllegalArgumentException if164* the smallest minimum is greater than the smallest maximum,165* or the smallest maximum is greater than the largest maximum,166* or the largest minimum is greater than the largest maximum,167* or the smallest minimum is greater than the largest minimum168*/169public static ValueRange of(long minSmallest, long minLargest, long maxSmallest, long maxLargest) {170if (minSmallest > minLargest) {171throw new IllegalArgumentException("Smallest minimum value must be less than largest minimum value");172}173if (maxSmallest > maxLargest) {174throw new IllegalArgumentException("Smallest maximum value must be less than largest maximum value");175}176if (minLargest > maxLargest) {177throw new IllegalArgumentException("Largest minimum value must be less than largest maximum value");178}179if (minSmallest > maxSmallest) {180throw new IllegalArgumentException("Smallest minimum value must be less than smallest maximum value");181}182return new ValueRange(minSmallest, minLargest, maxSmallest, maxLargest);183}184185/**186* Restrictive constructor.187*188* @param minSmallest the smallest minimum value189* @param minLargest the largest minimum value190* @param maxSmallest the smallest minimum value191* @param maxLargest the largest minimum value192*/193private ValueRange(long minSmallest, long minLargest, long maxSmallest, long maxLargest) {194this.minSmallest = minSmallest;195this.minLargest = minLargest;196this.maxSmallest = maxSmallest;197this.maxLargest = maxLargest;198}199200//-----------------------------------------------------------------------201/**202* Is the value range fixed and fully known.203* <p>204* For example, the ISO day-of-month runs from 1 to between 28 and 31.205* Since there is uncertainty about the maximum value, the range is not fixed.206* However, for the month of January, the range is always 1 to 31, thus it is fixed.207*208* @return true if the set of values is fixed209*/210public boolean isFixed() {211return minSmallest == minLargest && maxSmallest == maxLargest;212}213214//-----------------------------------------------------------------------215/**216* Gets the minimum value that the field can take.217* <p>218* For example, the ISO day-of-month always starts at 1.219* The minimum is therefore 1.220*221* @return the minimum value for this field222*/223public long getMinimum() {224return minSmallest;225}226227/**228* Gets the largest possible minimum value that the field can take.229* <p>230* For example, the ISO day-of-month always starts at 1.231* The largest minimum is therefore 1.232*233* @return the largest possible minimum value for this field234*/235public long getLargestMinimum() {236return minLargest;237}238239/**240* Gets the smallest possible maximum value that the field can take.241* <p>242* For example, the ISO day-of-month runs to between 28 and 31 days.243* The smallest maximum is therefore 28.244*245* @return the smallest possible maximum value for this field246*/247public long getSmallestMaximum() {248return maxSmallest;249}250251/**252* Gets the maximum value that the field can take.253* <p>254* For example, the ISO day-of-month runs to between 28 and 31 days.255* The maximum is therefore 31.256*257* @return the maximum value for this field258*/259public long getMaximum() {260return maxLargest;261}262263//-----------------------------------------------------------------------264/**265* Checks if all values in the range fit in an {@code int}.266* <p>267* This checks that all valid values are within the bounds of an {@code int}.268* <p>269* For example, the ISO month-of-year has values from 1 to 12, which fits in an {@code int}.270* By comparison, ISO nano-of-day runs from 1 to 86,400,000,000,000 which does not fit in an {@code int}.271* <p>272* This implementation uses {@link #getMinimum()} and {@link #getMaximum()}.273*274* @return true if a valid value always fits in an {@code int}275*/276public boolean isIntValue() {277return getMinimum() >= Integer.MIN_VALUE && getMaximum() <= Integer.MAX_VALUE;278}279280/**281* Checks if the value is within the valid range.282* <p>283* This checks that the value is within the stored range of values.284*285* @param value the value to check286* @return true if the value is valid287*/288public boolean isValidValue(long value) {289return (value >= getMinimum() && value <= getMaximum());290}291292/**293* Checks if the value is within the valid range and that all values294* in the range fit in an {@code int}.295* <p>296* This method combines {@link #isIntValue()} and {@link #isValidValue(long)}.297*298* @param value the value to check299* @return true if the value is valid and fits in an {@code int}300*/301public boolean isValidIntValue(long value) {302return isIntValue() && isValidValue(value);303}304305/**306* Checks that the specified value is valid.307* <p>308* This validates that the value is within the valid range of values.309* The field is only used to improve the error message.310*311* @param value the value to check312* @param field the field being checked, may be null313* @return the value that was passed in314* @see #isValidValue(long)315*/316public long checkValidValue(long value, TemporalField field) {317if (isValidValue(value) == false) {318throw new DateTimeException(genInvalidFieldMessage(field, value));319}320return value;321}322323/**324* Checks that the specified value is valid and fits in an {@code int}.325* <p>326* This validates that the value is within the valid range of values and that327* all valid values are within the bounds of an {@code int}.328* The field is only used to improve the error message.329*330* @param value the value to check331* @param field the field being checked, may be null332* @return the value that was passed in333* @see #isValidIntValue(long)334*/335public int checkValidIntValue(long value, TemporalField field) {336if (isValidIntValue(value) == false) {337throw new DateTimeException(genInvalidFieldMessage(field, value));338}339return (int) value;340}341342private String genInvalidFieldMessage(TemporalField field, long value) {343if (field != null) {344return "Invalid value for " + field + " (valid values " + this + "): " + value;345} else {346return "Invalid value (valid values " + this + "): " + value;347}348}349350//-----------------------------------------------------------------------351/**352* Restore the state of an ValueRange from the stream.353* Check that the values are valid.354*355* @param s the stream to read356* @throws IOException if an I/O error occurs357* @throws InvalidObjectException if358* the smallest minimum is greater than the smallest maximum,359* or the smallest maximum is greater than the largest maximum360* or the largest minimum is greater than the largest maximum361* @throws ClassNotFoundException if a class cannot be resolved362*/363@java.io.Serial364private void readObject(ObjectInputStream s)365throws IOException, ClassNotFoundException, InvalidObjectException366{367s.defaultReadObject();368if (minSmallest > minLargest) {369throw new InvalidObjectException("Smallest minimum value must be less than largest minimum value");370}371if (maxSmallest > maxLargest) {372throw new InvalidObjectException("Smallest maximum value must be less than largest maximum value");373}374if (minLargest > maxLargest) {375throw new InvalidObjectException("Minimum value must be less than maximum value");376}377}378379//-----------------------------------------------------------------------380/**381* Checks if this range is equal to another range.382* <p>383* The comparison is based on the four values, minimum, largest minimum,384* smallest maximum and maximum.385* Only objects of type {@code ValueRange} are compared, other types return false.386*387* @param obj the object to check, null returns false388* @return true if this is equal to the other range389*/390@Override391public boolean equals(Object obj) {392if (obj == this) {393return true;394}395return (obj instanceof ValueRange other)396&& minSmallest == other.minSmallest397&& minLargest == other.minLargest398&& maxSmallest == other.maxSmallest399&& maxLargest == other.maxLargest;400}401402/**403* A hash code for this range.404*405* @return a suitable hash code406*/407@Override408public int hashCode() {409long hash = minSmallest + (minLargest << 16) + (minLargest >> 48) +410(maxSmallest << 32) + (maxSmallest >> 32) + (maxLargest << 48) +411(maxLargest >> 16);412return (int) (hash ^ (hash >>> 32));413}414415//-----------------------------------------------------------------------416/**417* Outputs this range as a {@code String}.418* <p>419* The format will be '{min}/{largestMin} - {smallestMax}/{max}',420* where the largestMin or smallestMax sections may be omitted, together421* with associated slash, if they are the same as the min or max.422*423* @return a string representation of this range, not null424*/425@Override426public String toString() {427StringBuilder buf = new StringBuilder();428buf.append(minSmallest);429if (minSmallest != minLargest) {430buf.append('/').append(minLargest);431}432buf.append(" - ").append(maxSmallest);433if (maxSmallest != maxLargest) {434buf.append('/').append(maxLargest);435}436return buf.toString();437}438439}440441442