1 // © 2020 and later: Unicode, Inc. and others. 2 // License & terms of use: http://www.unicode.org/copyright.html 3 package com.ibm.icu.impl.number; 4 5 import java.math.BigDecimal; 6 import java.util.List; 7 8 import com.ibm.icu.impl.units.ComplexUnitsConverter; 9 import com.ibm.icu.impl.units.MeasureUnitImpl; 10 import com.ibm.icu.impl.units.UnitsRouter; 11 import com.ibm.icu.util.MeasureUnit; 12 import com.ibm.icu.util.ULocale; 13 14 public class UsagePrefsHandler implements MicroPropsGenerator { 15 16 private final MicroPropsGenerator fParent; 17 private UnitsRouter fUnitsRouter; 18 UsagePrefsHandler(ULocale locale, MeasureUnit inputUnit, String usage, MicroPropsGenerator parent)19 public UsagePrefsHandler(ULocale locale, MeasureUnit inputUnit, String usage, MicroPropsGenerator parent) { 20 assert parent != null; 21 22 this.fParent = parent; 23 this.fUnitsRouter = 24 new UnitsRouter(MeasureUnitImpl.forIdentifier(inputUnit.getIdentifier()), locale.getCountry(), usage); 25 } 26 27 /** 28 * Populates micros.mixedMeasures and modifies quantity, based on the values 29 * in measures. 30 */ 31 protected static void mixedMeasuresToMicros(ComplexUnitsConverter.ComplexConverterResult complexConverterResult, DecimalQuantity quantity, MicroProps outMicros)32 mixedMeasuresToMicros(ComplexUnitsConverter.ComplexConverterResult complexConverterResult, DecimalQuantity quantity, MicroProps outMicros) { 33 outMicros.mixedMeasures = complexConverterResult.measures; 34 outMicros.indexOfQuantity = complexConverterResult.indexOfQuantity; 35 quantity.setToBigDecimal((BigDecimal) outMicros.mixedMeasures.get(outMicros.indexOfQuantity).getNumber()); 36 } 37 38 /** 39 * Returns the list of possible output units, i.e. the full set of 40 * preferences, for the localized, usage-specific unit preferences. 41 * <p> 42 * The returned pointer should be valid for the lifetime of the 43 * UsagePrefsHandler instance. 44 */ getOutputUnits()45 public List<MeasureUnit> getOutputUnits() { 46 return fUnitsRouter.getOutputUnits(); 47 } 48 49 /** 50 * Obtains the appropriate output value, MeasureUnit and 51 * rounding/precision behaviour from the UnitsRouter. 52 * <p> 53 * The output unit is passed on to the LongNameHandler via 54 * micros.outputUnit. 55 */ 56 @Override processQuantity(DecimalQuantity quantity)57 public MicroProps processQuantity(DecimalQuantity quantity) { 58 MicroProps micros = this.fParent.processQuantity(quantity); 59 60 quantity.roundToInfinity(); // Enables toDouble 61 final UnitsRouter.RouteResult routed = fUnitsRouter.route(quantity.toBigDecimal(), micros); 62 micros.outputUnit = routed.outputUnit.build(); 63 UsagePrefsHandler.mixedMeasuresToMicros(routed.complexConverterResult, quantity, micros); 64 return micros; 65 } 66 } 67