Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/time/chrono/ChronoPeriodImpl.java
38918 views
/*1* Copyright (c) 2013, 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* Copyright (c) 2013, Stephen Colebourne & Michael Nascimento Santos27*28* All rights reserved.29*30* Redistribution and use in source and binary forms, with or without31* modification, are permitted provided that the following conditions are met:32*33* * Redistributions of source code must retain the above copyright notice,34* this list of conditions and the following disclaimer.35*36* * Redistributions in binary form must reproduce the above copyright notice,37* this list of conditions and the following disclaimer in the documentation38* and/or other materials provided with the distribution.39*40* * Neither the name of JSR-310 nor the names of its contributors41* may be used to endorse or promote products derived from this software42* without specific prior written permission.43*44* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS45* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT46* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR47* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR48* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,49* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,50* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR51* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF52* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING53* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS54* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.55*/56package java.time.chrono;5758import static java.time.temporal.ChronoField.MONTH_OF_YEAR;59import static java.time.temporal.ChronoUnit.DAYS;60import static java.time.temporal.ChronoUnit.MONTHS;61import static java.time.temporal.ChronoUnit.YEARS;6263import java.io.DataInput;64import java.io.DataOutput;65import java.io.IOException;66import java.io.InvalidObjectException;67import java.io.ObjectInputStream;68import java.io.ObjectStreamException;69import java.io.Serializable;70import java.time.DateTimeException;71import java.time.temporal.ChronoUnit;72import java.time.temporal.Temporal;73import java.time.temporal.TemporalAccessor;74import java.time.temporal.TemporalAmount;75import java.time.temporal.TemporalQueries;76import java.time.temporal.TemporalUnit;77import java.time.temporal.UnsupportedTemporalTypeException;78import java.time.temporal.ValueRange;79import java.util.Arrays;80import java.util.Collections;81import java.util.List;82import java.util.Objects;8384/**85* A period expressed in terms of a standard year-month-day calendar system.86* <p>87* This class is used by applications seeking to handle dates in non-ISO calendar systems.88* For example, the Japanese, Minguo, Thai Buddhist and others.89*90* @implSpec91* This class is immutable nad thread-safe.92*93* @since 1.894*/95final class ChronoPeriodImpl96implements ChronoPeriod, Serializable {97// this class is only used by JDK chronology implementations and makes assumptions based on that fact9899/**100* Serialization version.101*/102private static final long serialVersionUID = 57387258289L;103104/**105* The set of supported units.106*/107private static final List<TemporalUnit> SUPPORTED_UNITS =108Collections.unmodifiableList(Arrays.<TemporalUnit>asList(YEARS, MONTHS, DAYS));109110/**111* The chronology.112*/113private final Chronology chrono;114/**115* The number of years.116*/117final int years;118/**119* The number of months.120*/121final int months;122/**123* The number of days.124*/125final int days;126127/**128* Creates an instance.129*/130ChronoPeriodImpl(Chronology chrono, int years, int months, int days) {131Objects.requireNonNull(chrono, "chrono");132this.chrono = chrono;133this.years = years;134this.months = months;135this.days = days;136}137138//-----------------------------------------------------------------------139@Override140public long get(TemporalUnit unit) {141if (unit == ChronoUnit.YEARS) {142return years;143} else if (unit == ChronoUnit.MONTHS) {144return months;145} else if (unit == ChronoUnit.DAYS) {146return days;147} else {148throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);149}150}151152@Override153public List<TemporalUnit> getUnits() {154return ChronoPeriodImpl.SUPPORTED_UNITS;155}156157@Override158public Chronology getChronology() {159return chrono;160}161162//-----------------------------------------------------------------------163@Override164public boolean isZero() {165return years == 0 && months == 0 && days == 0;166}167168@Override169public boolean isNegative() {170return years < 0 || months < 0 || days < 0;171}172173//-----------------------------------------------------------------------174@Override175public ChronoPeriod plus(TemporalAmount amountToAdd) {176ChronoPeriodImpl amount = validateAmount(amountToAdd);177return new ChronoPeriodImpl(178chrono,179Math.addExact(years, amount.years),180Math.addExact(months, amount.months),181Math.addExact(days, amount.days));182}183184@Override185public ChronoPeriod minus(TemporalAmount amountToSubtract) {186ChronoPeriodImpl amount = validateAmount(amountToSubtract);187return new ChronoPeriodImpl(188chrono,189Math.subtractExact(years, amount.years),190Math.subtractExact(months, amount.months),191Math.subtractExact(days, amount.days));192}193194/**195* Obtains an instance of {@code ChronoPeriodImpl} from a temporal amount.196*197* @param amount the temporal amount to convert, not null198* @return the period, not null199*/200private ChronoPeriodImpl validateAmount(TemporalAmount amount) {201Objects.requireNonNull(amount, "amount");202if (amount instanceof ChronoPeriodImpl == false) {203throw new DateTimeException("Unable to obtain ChronoPeriod from TemporalAmount: " + amount.getClass());204}205ChronoPeriodImpl period = (ChronoPeriodImpl) amount;206if (chrono.equals(period.getChronology()) == false) {207throw new ClassCastException("Chronology mismatch, expected: " + chrono.getId() + ", actual: " + period.getChronology().getId());208}209return period;210}211212//-----------------------------------------------------------------------213@Override214public ChronoPeriod multipliedBy(int scalar) {215if (this.isZero() || scalar == 1) {216return this;217}218return new ChronoPeriodImpl(219chrono,220Math.multiplyExact(years, scalar),221Math.multiplyExact(months, scalar),222Math.multiplyExact(days, scalar));223}224225//-----------------------------------------------------------------------226@Override227public ChronoPeriod normalized() {228long monthRange = monthRange();229if (monthRange > 0) {230long totalMonths = years * monthRange + months;231long splitYears = totalMonths / monthRange;232int splitMonths = (int) (totalMonths % monthRange); // no overflow233if (splitYears == years && splitMonths == months) {234return this;235}236return new ChronoPeriodImpl(chrono, Math.toIntExact(splitYears), splitMonths, days);237238}239return this;240}241242/**243* Calculates the range of months.244*245* @return the month range, -1 if not fixed range246*/247private long monthRange() {248ValueRange startRange = chrono.range(MONTH_OF_YEAR);249if (startRange.isFixed() && startRange.isIntValue()) {250return startRange.getMaximum() - startRange.getMinimum() + 1;251}252return -1;253}254255//-------------------------------------------------------------------------256@Override257public Temporal addTo(Temporal temporal) {258validateChrono(temporal);259if (months == 0) {260if (years != 0) {261temporal = temporal.plus(years, YEARS);262}263} else {264long monthRange = monthRange();265if (monthRange > 0) {266temporal = temporal.plus(years * monthRange + months, MONTHS);267} else {268if (years != 0) {269temporal = temporal.plus(years, YEARS);270}271temporal = temporal.plus(months, MONTHS);272}273}274if (days != 0) {275temporal = temporal.plus(days, DAYS);276}277return temporal;278}279280281282@Override283public Temporal subtractFrom(Temporal temporal) {284validateChrono(temporal);285if (months == 0) {286if (years != 0) {287temporal = temporal.minus(years, YEARS);288}289} else {290long monthRange = monthRange();291if (monthRange > 0) {292temporal = temporal.minus(years * monthRange + months, MONTHS);293} else {294if (years != 0) {295temporal = temporal.minus(years, YEARS);296}297temporal = temporal.minus(months, MONTHS);298}299}300if (days != 0) {301temporal = temporal.minus(days, DAYS);302}303return temporal;304}305306/**307* Validates that the temporal has the correct chronology.308*/309private void validateChrono(TemporalAccessor temporal) {310Objects.requireNonNull(temporal, "temporal");311Chronology temporalChrono = temporal.query(TemporalQueries.chronology());312if (temporalChrono != null && chrono.equals(temporalChrono) == false) {313throw new DateTimeException("Chronology mismatch, expected: " + chrono.getId() + ", actual: " + temporalChrono.getId());314}315}316317//-----------------------------------------------------------------------318@Override319public boolean equals(Object obj) {320if (this == obj) {321return true;322}323if (obj instanceof ChronoPeriodImpl) {324ChronoPeriodImpl other = (ChronoPeriodImpl) obj;325return years == other.years && months == other.months &&326days == other.days && chrono.equals(other.chrono);327}328return false;329}330331@Override332public int hashCode() {333return (years + Integer.rotateLeft(months, 8) + Integer.rotateLeft(days, 16)) ^ chrono.hashCode();334}335336//-----------------------------------------------------------------------337@Override338public String toString() {339if (isZero()) {340return getChronology().toString() + " P0D";341} else {342StringBuilder buf = new StringBuilder();343buf.append(getChronology().toString()).append(' ').append('P');344if (years != 0) {345buf.append(years).append('Y');346}347if (months != 0) {348buf.append(months).append('M');349}350if (days != 0) {351buf.append(days).append('D');352}353return buf.toString();354}355}356357//-----------------------------------------------------------------------358/**359* Writes the Chronology using a360* <a href="../../../serialized-form.html#java.time.chrono.Ser">dedicated serialized form</a>.361* <pre>362* out.writeByte(12); // identifies this as a ChronoPeriodImpl363* out.writeUTF(getId()); // the chronology364* out.writeInt(years);365* out.writeInt(months);366* out.writeInt(days);367* </pre>368*369* @return the instance of {@code Ser}, not null370*/371protected Object writeReplace() {372return new Ser(Ser.CHRONO_PERIOD_TYPE, this);373}374375/**376* Defend against malicious streams.377*378* @param s the stream to read379* @throws InvalidObjectException always380*/381private void readObject(ObjectInputStream s) throws ObjectStreamException {382throw new InvalidObjectException("Deserialization via serialization delegate");383}384385void writeExternal(DataOutput out) throws IOException {386out.writeUTF(chrono.getId());387out.writeInt(years);388out.writeInt(months);389out.writeInt(days);390}391392static ChronoPeriodImpl readExternal(DataInput in) throws IOException {393Chronology chrono = Chronology.of(in.readUTF());394int years = in.readInt();395int months = in.readInt();396int days = in.readInt();397return new ChronoPeriodImpl(chrono, years, months, days);398}399400}401402403