All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jcckit.util.FormatElement Maven / Gradle / Ivy

There is a newer version: 1.2024.8
Show newest version
// THIS FILE HAS BEEN GENERATED BY A PREPROCESSOR.
/* +=======================================================================
 * |
 * |      PlantUML : a free UML diagram generator
 * |
 * +=======================================================================
 *
 * (C) Copyright 2009-2024, Arnaud Roques
 *
 * Project Info:  https://plantuml.com
 *
 * If you like this project or if you find it useful, you can support us at:
 *
 * https://plantuml.com/patreon (only 1$ per month!)
 * https://plantuml.com/liberapay (only 1€ per month!)
 * https://plantuml.com/paypal
 *
 *
 * PlantUML is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License V2.
 *
 * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
 * LICENSE ("AGREEMENT"). [GNU General Public License V2]
 *
 * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
 * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
 *
 * You may obtain a copy of the License at
 *
 * https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * PlantUML can occasionally display sponsored or advertising messages. Those
 * messages are usually generated on welcome or error images and never on
 * functional diagrams.
 * See https://plantuml.com/professional if you want to remove them
 *
 * Images (whatever their format : PNG, SVG, EPS...) generated by running PlantUML
 * are owned by the author of their corresponding sources code (that is, their
 * textual description in PlantUML language). Those images are not covered by
 * this GPL v2 license.
 *
 * The generated images can then be used without any reference to the GPL v2 license.
 * It is not even necessary to stipulate that they have been generated with PlantUML,
 * although this will be appreciated by the PlantUML team.
 *
 * There is an exception : if the textual description in PlantUML language is also covered
 * by any license, then the generated images are logically covered
 * by the very same license.
 *
 * This is the IGY distribution (Install GraphViz by Yourself).
 * You have to install GraphViz and to setup the GRAPHVIZ_DOT environment variable
 * (see https://plantuml.com/graphviz-dot )
 *
 * Icons provided by OpenIconic :  https://useiconic.com/open
 * Archimate sprites provided by Archi :  http://www.archimatetool.com
 * Stdlib AWS provided by https://github.com/milo-minderbinder/AWS-PlantUML
 * Stdlib Icons provided https://github.com/tupadr3/plantuml-icon-font-sprites
 * ASCIIMathML (c) Peter Jipsen http://www.chapman.edu/~jipsen
 * ASCIIMathML (c) David Lippman http://www.pierce.ctc.edu/dlippman
 * CafeUndZopfli ported by Eugene Klyuchnikov https://github.com/eustas/CafeUndZopfli
 * Brotli (c) by the Brotli Authors https://github.com/google/brotli
 * Themes (c) by Brett Schwarz https://github.com/bschwarz/puml-themes
 * Twemoji (c) by Twitter at https://twemoji.twitter.com/
 *
 */
package jcckit.util;

/**
 * 
 * 
 * @author Franz-Josef Elmer
 */
class FormatElement {
  /** All descriptor characters. */
  static final String DESCRIPTORS = "doxfeEgG";
  private static final String INT_DESCRIPTORS = "dox";
  private static final int INT_DESCRIPTOR = 0;
  private static final int FLOAT_DESCRIPTOR = 1;
  /**
   *  Calculate the integer power of a floating point number.
   *  @param n Exponent.
   *  @param x Number.
   *  @return x^n.
   */
  private static final double power(double x, int n) {
    return n < 0 ? 1.0 / power2(x, -n) : power2(x, n);
  }

  /** Calculate x^n recursively assuming n > 0. */
  private static final double power2(double x, int n) {
    switch (n) {
    case 0: return 1;
    case 1: return x;
    default:
      double p = power2(x, n / 2);
      return p * p * power2(x, n % 2);
    }
  }

  private final char _descriptor;
  private final int _descriptorType;
  private final double _tenToPrecision;
  private boolean _decimalPoint;
  private boolean _flushLeft;
  private boolean _leadingZeros;
  private boolean _alwaysSign;
  private int _width;
  private int _precision;

  /** Creates an instance for the specified format string. */
  FormatElement(String formatString) {
    int len = formatString.length() - 1;
    _descriptor = formatString.charAt(len);
    if (DESCRIPTORS.indexOf(_descriptor) < 0) {
      throw new IllegalArgumentException("Format element '" + formatString
          + "' does not ends with one of the following characters: "
          + DESCRIPTORS);
    }
    _descriptorType = INT_DESCRIPTORS.indexOf(_descriptor) >= 0
                                ? INT_DESCRIPTOR : FLOAT_DESCRIPTOR;
    if (formatString.length() > 1) {
      switch (formatString.charAt(0)) {
      case '-':
        _flushLeft = true;
        formatString = formatString.substring(1);
        break;
      case '0':
        _leadingZeros = true;
        formatString = formatString.substring(1);
        break;
      case '+':
        _alwaysSign = true;
        formatString = formatString.substring(1);
        break;
      }
      len = formatString.length() - 1;
      int index = formatString.indexOf('.');
      _decimalPoint = index >= 0;
      int last = _decimalPoint ? index : len;
      if (last > 0) {
        _width = Integer.parseInt(formatString.substring(0, last));
      }
      if (_decimalPoint) {
        index++;
        if (index < len) {
          _precision = Integer.parseInt(formatString.substring(index, len));
        }
      }
    }
    _tenToPrecision = power(10, _precision);
  }

  /**
   *  Format a number in accordance of the format string
   *  given at the initialisation of this instance.
   *  @param buffer Buffer to which the formated output will be appended.
   *  @param number Number to be formated.
   */
  public void form(StringBuffer buffer, long number) {
    if (_descriptorType == FLOAT_DESCRIPTOR) {
      form(buffer, (double) number);
    } else {
      // Format absolut value in the right base
      buffer.append(form(number < 0,
                         Long.toString(Math.abs(number),
                                _descriptor == 'o' ? 8
                                          : (_descriptor == 'x' ? 16 : 10)),
                         ""));
    }
  }

  /**
   *  Format a number in accordance of the format string
   *  given at the initialisation of this instance.
   *  @param buffer Buffer to which the formated output will be appended.
   *  @param number Number to be formated.
   */
  public void form(StringBuffer buffer, double number) {
    if (_descriptorType == INT_DESCRIPTOR) {
      form(buffer, (long) Math.floor(number + 0.5));
    } else if (_descriptor == 'f') {
      buffer.append(formF(number));
    } else if (_descriptor == 'e' || _descriptor == 'E') {
      buffer.append(formE(number));
    } else if (_descriptor == 'g' || _descriptor == 'G') {
      String formF = formF(number);
      String formE = formE(number);
      buffer.append(formF.length() > formE.length() ? formE : formF);
    } 
  }

  private String form(boolean negativeValue, String intPart, String fracPart) {
    int len = intPart.length() + fracPart.length();

    // Buffer holding the result
    StringBuffer result = new StringBuffer();
    int count = 0;

    // add sign if necessary
    if (_alwaysSign || negativeValue) {
      result.append(negativeValue ? '-' : '+');
      count++;
    }

    // add zeros  if necessary
    if (_leadingZeros) {
      for (int i = count + len; i < _width; i++) {
        result.append('0');
        count++;
      }
    }

    // add number
    result.append(intPart).append(fracPart);
    count += len;

    // add spaces if necessary
    if (_flushLeft) {
      for (; count < _width; count++) {
        result.append(' ');
      }
    } else {
      for (; count < _width; count++) {
        result.insert(0, ' ');
      }
    }

    return new String(result);
  }

  /** Format floating point number with exponent. */
  private String formE(double number) {
    // format absolute mantisse
    int exponent = 0;
    String zeros = "00000000000000000000000".substring(0, _precision + 1);
    if (number != 0) {
      exponent = (int) Math.floor(Math.log(Math.abs(number)) / Math.log(10));
      double mantisse = Math.floor(Math.abs(number * power(10.0,
                                            _precision - exponent)) + 0.5);
      if (mantisse >= 10 * _tenToPrecision) {
        exponent++;
        mantisse = Math.floor(Math.abs(number * power(10.0,
                                          _precision - exponent)) + 0.5);
      }
      zeros = Long.toString((long) mantisse);
    }

    // make fractional part
    StringBuffer fracPart = new StringBuffer();
    if (_decimalPoint) {
      fracPart.append('.').append(zeros.substring(1));
    }

    // make exponent
    fracPart.append(Character.isLowerCase(_descriptor) ? 'e': 'E')
            .append(exponent < 0 ? '-' : '+');
    exponent = Math.abs(exponent);
    for (int i = 0, n = fracPart.length(); i < 3; i++) {
      fracPart.insert(n, Character.forDigit(exponent % 10, 10));
      exponent /= 10;
    }

    return form(number < 0, zeros.substring(0, 1), new String(fracPart));
  }

  /** Format floating point number. */
  private String formF(double number) {
    // Format absolut value
    double multiplier = number < 0 ? - _tenToPrecision : _tenToPrecision;
    String digits 
        = Long.toString((long) Math.floor(number * multiplier + 0.5));
    String intPart = digits;
    StringBuffer fracPart = new StringBuffer();
    if (_decimalPoint) {
      int len = digits.length() - _precision;
      fracPart.append('.').append(digits.substring(Math.max(0, len)));
      if (len > 0) {
        intPart = digits.substring(0, len);
      } else {
        intPart = "0";
        for (; len < 0; len++) {
          fracPart.insert(1, '0');
        }
      }
    }

    return form(number < 0, intPart, new String(fracPart));
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy