summaryrefslogtreecommitdiff
path: root/clformat/src/main/java/bjc/utils/ioutils/format/directives/CharacterDirective.java
blob: 6fd230918424933f1399bfe24adf3d2396aed0ef (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
package bjc.utils.ioutils.format.directives;

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

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

/**
 * Implements the C directive.
 *
 * This serves to print out a single character, in the way that the '%c' printf
 * directive does.
 *
 * @author Ben Culkin
 */
public class CharacterDirective implements Directive {
	@Override
	public Edict compile(CompileContext compCTX) {
		return new CharacterEdict(compCTX.decr.modifiers.colonMod);
	}
}

class CharacterEdict implements Edict {
	private boolean printCharName;

	public CharacterEdict(boolean printCharName) {
		this.printCharName = printCharName;
	}

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

		CLFormatter.checkItem(item, 'C');

		if (!(item instanceof Character)) {
			throw new IllegalFormatConversionException('C', item.getClass());
		}

		char ch = (Character) item;
		int codepoint = ch;

		ReportWriter rw = formCTX.writer;

		if (printCharName) rw.write(Character.getName(codepoint));
		else               rw.write(ch);

		formCTX.items.right();
	}
}