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

net.sourceforge.plantuml.code.Upf9Encoder Maven / Gradle / Ivy

There is a newer version: 1.2025.0
Show newest version
// THIS FILE HAS BEEN GENERATED BY A PREPROCESSOR.
package net.sourceforge.plantuml.code;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import net.sourceforge.plantuml.log.Logme;

public class Upf9Encoder {
	// ::remove file when __CORE__

	private Upf9Encoder() {

	}

	public static byte[] encodeChar(char c) {
		final byte[] result = encodeCharInternal(c);
		assert checkBack(c, result);
		return result;
	}

	private static boolean checkBack(char c, byte[] result) {
		try {
			if (c == Upf9Decoder.decodeChar(new ByteArrayInputStream(result)))
				return true;
		} catch (IOException e) {
			Logme.error(e);
		}
		return false;
	}

	private static byte[] encodeCharInternal(char c) {
		if (c == '\n' || c == '\r' || c == '\t') {
			// Using regular ASCII code for   and 
			return new byte[] { (byte) c };
		}
		if (c >= '\u000E' && c <= '\u0012') {
			return new byte[] { (byte) c };
		}
		if (c >= '\u0020' && c <= '\u007E') {
			// Using regular ASCII code for ASCII printable char
			return new byte[] { (byte) c };
		}
		if (c >= '\u0080' && c <= '\u00FF') {
			// Char from  to  are encoded as [0x0B 0x80] to [0x0B 0xFF]
			return new byte[] { 0x0B, (byte) c };
		}
		if (c >= '\u0100' && c <= '\u08FF') {
			// Char from  to  are encoded as [0x01 0x00] to [0x08 0xFF]
			return new byte[] { highByte(c), lowByte(c) };
		}
		if (c >= '\u2000' && c <= '\u9FFF') {
			// Char from  to  are encoded as [0x80 0x00] to [0xFF 0xFF]
			return new byte[] { (byte) (0x60 + highByte(c)), lowByte(c) };
		}
		if (c >= '\uE000' && c <= '\uE07F') {
			// Char from  to  are encoded as [0x0B 0x00] to [0x0B 0x7F]
			return new byte[] { 0x0B, lowByte(c) };
		}
		// All other char are encoded on 3 bytes, starting with 0x0C
		return new byte[] { 0x0C, highByte(c), lowByte(c) };
	}

	private static byte lowByte(char c) {
		return (byte) (c & 0x00FF);
	}

	private static byte highByte(char c) {
		return (byte) ((c & 0xFF00) >> 8);
	}

	public static byte[] getBytes(String s) throws IOException {
		final ByteArrayOutputStream baos = new ByteArrayOutputStream();
		for (int i = 0; i < s.length(); i++) {
			baos.write(encodeChar(s.charAt(i)));
		}
		baos.close();
		final byte[] result = baos.toByteArray();
		assert s.endsWith(Upf9Decoder.decodeString(result, result.length));
		return result;
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy