| 1 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 2 | // Copyright (c) 2018 Saxonica Limited. |
| 3 | // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. |
| 4 | // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 | // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. |
| 6 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 7 | |
| 8 | package net.sf.saxon.expr.number; |
| 9 | |
| 10 | import net.sf.saxon.regex.UnicodeString; |
| 11 | import net.sf.saxon.tree.util.FastStringBuffer; |
| 12 | |
| 13 | /** |
| 14 | * A RegularGroupFormatter is a NumericGroupFormatter that inserts a separator |
| 15 | * at constant intervals through a number: for example, a comma after every three |
| 16 | * digits counting from the right. |
| 17 | */ |
| 18 | |
| 19 | public class RegularGroupFormatter extends NumericGroupFormatter { |
| 20 | |
| 21 | private int groupSize; |
| 22 | private String groupSeparator; |
| 23 | |
| 24 | /** |
| 25 | * Create a RegularGroupFormatter |
| 26 | * |
| 27 | * @param grpSize the grouping size. If zero, no grouping separators are inserted |
| 28 | * @param grpSep the grouping separator (normally but not necessarily a single character) |
| 29 | * @param adjustedPicture The picture, adjusted to conform to the rules of the xsl:number function, |
| 30 | * which means the picture supplied to format-integer minus any modifiers, and minus grouping separators |
| 31 | * and optional-digit signs |
| 32 | */ |
| 33 | |
| 34 | public RegularGroupFormatter(int grpSize, String grpSep, UnicodeString adjustedPicture) { |
| 35 | groupSize = grpSize; |
| 36 | groupSeparator = grpSep; |
| 37 | this.adjustedPicture = adjustedPicture; |
| 38 | } |
| 39 | |
| 40 | @Override |
| 41 | public String format(/*@NotNull*/ FastStringBuffer value) { |
| 42 | if (groupSize > 0 && groupSeparator.length() > 0) { |
| 43 | UnicodeString valueEx = UnicodeString.makeUnicodeString(value); |
| 44 | FastStringBuffer temp = new FastStringBuffer(FastStringBuffer.C16); |
| 45 | for (int i = valueEx.uLength() - 1, j = 0; i >= 0; i--, j++) { |
| 46 | if (j != 0 && (j % groupSize) == 0) { |
| 47 | temp.prepend(groupSeparator); |
| 48 | } |
| 49 | temp.prependWideChar(valueEx.uCharAt(i)); |
| 50 | } |
| 51 | return temp.toString(); |
| 52 | } else { |
| 53 | return value.toString(); |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Get the grouping separator to be used |
| 59 | * |
| 60 | * @return the grouping separator |
| 61 | */ |
| 62 | @Override |
| 63 | public String getSeparator() { |
| 64 | return groupSeparator; |
| 65 | } |
| 66 | } |
| 67 |