summaryrefslogtreecommitdiff
path: root/clformat/src/main/java/bjc/utils/ioutils/format/directives/NumberDirective.java
blob: de1bb2863ec6c4132fef37e9cbff2e254333cc67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package bjc.utils.ioutils.format.directives;

import java.io.*;
import java.util.*;

import bjc.utils.ioutils.format.*;
import bjc.utils.math.*;

import static bjc.utils.ioutils.format.directives.GeneralNumberDirective.NumberParams;

/**
 * Implements radix based numbers.
 *
 * @author student
 *
 */
public class NumberDirective extends GeneralNumberDirective {
	/**
	 * Create a new radix based number directive.
	 *
	 * @param argidx
	 *                  The argument offset to use.
	 * @param radix
	 *                  The radix of the number to use.
	 * @param directive
	 *                  The character that marks this directive.
	 */
	public NumberDirective(int argidx, int radix, char directive) {
		this.argidx = argidx;
		this.radix = radix;

		this.directive = directive;
	}

	private int argidx;
	private int radix;

	private char directive;

	@Override
	public Edict compile(CompileContext compCTX) {
		NumberParams np = getParams(compCTX, argidx);

		return new NumberEdict(radix, directive, argidx, np);
	}
}

class NumberEdict implements Edict {
	private int radix;
	private String directive;

	private NumberParams np;

	public NumberEdict(int radix, char directive, int argidx, NumberParams np) {
		this.radix = radix;
		this.directive = Character.toString(directive);

		this.np = np;
	}

	@Override
	public void format(FormatContext formCTX) throws IOException {
		Object item = formCTX.items.item();

		CLFormatter.checkItem(item, directive.charAt(0));

		if (!(item instanceof Number)) {
			throw new IllegalFormatConversionException(directive.charAt(0),
					item.getClass());
		}

		long val = ((Number) item).longValue();

		int  mincol  = np.mincol.asInt(formCTX.items, "minimum column count", directive, 0);
		char padchar = np.padchar.asChar(formCTX.items, "padding character", directive, ' ');

		boolean signed = np.signed;

		String res;

		if (np.commaMode) {
			char commaChar = np.commaChar.asChar(formCTX.items, "comma character",
					directive, ',');
			int commaInterval = np.commaInterval.asInt(formCTX.items, "comma interval",
					directive, 0);

			res = NumberUtils.toCommaString(val, mincol, padchar, commaInterval,
					commaChar, signed, radix);
		} else {
			res = NumberUtils.toNormalString(val, mincol, padchar, signed, radix);
		}

		formCTX.writer.write(res);

		formCTX.items.right();
	}
}