基于字符流命令的内容解释
基于字符流命令的内容解释
1、概述
我们常常需要解释ASCII码的输入流,这些输入流读入时一般是以字节数组的形式,这些输入还会包括命令或控制字符,对应不同的命令或控制字符都有不同的处理方式。而解释和匹配这些命令常常会令我们头痛。这里介绍一种方法可以有效的处理这些命令。
2、场景
以VT100 Terminal Control为例,这些控制命令是严谨的不会发生混淆的,他的命令有如:
3、分析
上面这些命令主要分为: (I)明确的命令(
4、解决办法
使用逐个字符来判断的确不是一个好的方法,这里推荐另一种做法,使用定长字节数据进行判断。这种方法的具体做法如下: a)把(I)明确的命令使用hash code及对应的处理方法存入map中,其中hash code为该控制命令字节数组的hash code,存储的形式如:map(hashCode, processMethod)。 b)处理(II)定长可变的命令和(III)变长但可穷举的命令,使用类似如下的语句: byte bs = new byte; System.arraycopy(src, startPos, bs, 0, len); byte b1 = cs, b2 = cs, be = cs; if (b1 != '
5、整个程序的结构
Map<Integer, ProcessMethod> map = new HashMap<Integer, ProcessMethod>(); private List list = Arrays.asList(new byte, new byte, new byte, new byte, new byte, new byte, new byte, new byte, new byte, new byte); private void init() { map.put(hashCode(new byte { ' bs, int start, int len) { if (map.isEmpty()) { init(); } for (int i = start; i < len; i++) { byte b = bs*; if (b == '') { for (int j = 0; j < list.size() && j + i + 1 < len; j++) { byte cs = list.get(j); System.arraycopy(bs, i + 1, cs, 0, cs.length); if (map.contains(hashCode(cs))) { //map.get(hashCode(cs)).process(); break; } else { if (j + 1 < 3) { continue; } byte b1 = cs, b2 = cs, be = cs; int old = i; if (b1 != '