001/*
002 * Copyright 2005,2009 Ivan SZKIBA
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.ini4j.spi;
017
018public class WinEscapeTool extends EscapeTool
019{
020    private static final int ANSI_HEX_DIGITS = 2;
021    private static final int ANSI_OCTAL_DIGITS = 3;
022    private static final int OCTAL_RADIX = 8;
023    private static final WinEscapeTool INSTANCE = new WinEscapeTool();
024
025    public static WinEscapeTool getInstance()
026    {
027        return INSTANCE;
028    }
029
030    @Override void escapeBinary(StringBuilder buff, char c)
031    {
032        buff.append("\\x");
033        buff.append(HEX[(c >>> HEX_DIGIT_3_OFFSET) & HEX_DIGIT_MASK]);
034        buff.append(HEX[c & HEX_DIGIT_MASK]);
035    }
036
037    @Override int unescapeBinary(StringBuilder buff, char escapeType, String line, int index)
038    {
039        int ret = index;
040
041        if (escapeType == 'x')
042        {
043            try
044            {
045                buff.append((char) Integer.parseInt(line.substring(index, index + ANSI_HEX_DIGITS), HEX_RADIX));
046                ret = index + ANSI_HEX_DIGITS;
047            }
048            catch (Exception x)
049            {
050                throw new IllegalArgumentException("Malformed \\xHH encoding.", x);
051            }
052        }
053        else if (escapeType == 'o')
054        {
055            try
056            {
057                buff.append((char) Integer.parseInt(line.substring(index, index + ANSI_OCTAL_DIGITS), OCTAL_RADIX));
058                ret = index + ANSI_OCTAL_DIGITS;
059            }
060            catch (Exception x)
061            {
062                throw new IllegalArgumentException("Malformed \\oOO encoding.", x);
063            }
064        }
065
066        return ret;
067    }
068}