001/*
002 * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences.
003 * Copyright (C) 2006 - JScience (http://jscience.org/)
004 * All rights reserved.
005 * 
006 * Permission to use, copy, modify, and distribute this software is
007 * freely granted, provided that this notice is preserved.
008 */
009package javax.measure.converter;
010
011
012/**
013 * <p> This class represents a converter adding a constant offset 
014 *     (approximated as a <code>double</code>) to numeric values.</p>
015 *     
016 * <p> Instances of this class are immutable.</p>
017 *
018 * @author  <a href="mailto:jean-marie@dautelle.com">Jean-Marie Dautelle</a>
019 * @version 3.1, April 22, 2006
020 */
021public final class AddConverter extends UnitConverter {
022
023    /**
024     * Holds the offset.
025     */
026    private final double _offset;
027
028    /**
029     * Creates an add converter with the specified offset.
030     *
031     * @param  offset the offset value.
032     * @throws IllegalArgumentException if offset is zero (or close to zero).
033     */
034    public AddConverter(double offset) {
035        if ((float)offset == 0.0)
036            throw new IllegalArgumentException("Identity converter not allowed");
037        _offset = offset;
038    }
039
040    /**
041     * Returns the offset value for this add converter.
042     *
043     * @return the offset value.
044     */
045    public double getOffset() {
046        return _offset;
047    }
048    
049    @Override
050    public UnitConverter inverse() {
051        return new AddConverter(- _offset);
052    }
053
054    @Override
055    public double convert(double amount) {
056        return amount + _offset;
057    }
058
059    @Override
060    public boolean isLinear() {
061        return false;
062    }
063
064    @Override
065    public UnitConverter concatenate(UnitConverter converter) {
066        if (converter instanceof AddConverter) {
067            double offset = _offset + ((AddConverter)converter)._offset;
068            return valueOf(offset);
069        } else {
070            return super.concatenate(converter);
071        }
072    }
073
074    private static UnitConverter valueOf(double offset) {
075        float asFloat = (float) offset;
076        return asFloat == 0.0f ? UnitConverter.IDENTITY : new AddConverter(offset);
077    }
078    
079    private static final long serialVersionUID = 1L;
080}