package org.postgresql.util;
import java.sql.SQLException;
public class PGbytea {
private static final int MAX_3_BUFF_SIZE = 2 * 1024 * 1024;
public static byte[] toBytes(byte[] s) throws SQLException {
if (s == null) {
return null;
}
if (s.length < 2 || s[0] != '\\' || s[1] != 'x') {
return toBytesOctalEscaped(s);
}
return toBytesHexEscaped(s);
}
private static byte[] toBytesHexEscaped(byte[] s) {
byte[] output = new byte[(s.length - 2) / 2];
for (int i = 0; i < output.length; i++) {
byte b1 = gethex(s[2 + i * 2]);
byte b2 = gethex(s[2 + i * 2 + 1]);
output[i] = (byte) ((b1 << 4) | (b2 & 0xff));
}
return output;
}
private static byte gethex(byte b) {
if (b <= 57) {
return (byte) (b - 48);
}
if (b >= 97) {
return (byte) (b - 97 + 10);
}
return (byte) (b - 65 + 10);
}
private static byte[] toBytesOctalEscaped(byte[] s) {
final int slength = s.length;
byte[] buf = null;
int correctSize = slength;
if (slength > MAX_3_BUFF_SIZE) {
for (int i = 0; i < slength; ++i) {
byte current = s[i];
if (current == '\\') {
byte next = s[++i];
if (next == '\\') {
--correctSize;
} else {
correctSize -= 3;
}
}
}
buf = new byte[correctSize];
} else {
buf = new byte[slength];
}
int bufpos = 0;
int thebyte;
byte nextbyte;
byte secondbyte;
for (int i = 0; i < slength; i++) {
nextbyte = s[i];
if (nextbyte == (byte) '\\') {
secondbyte = s[++i];
if (secondbyte == (byte) '\\') {
buf[bufpos++] = (byte) '\\';
} else {
thebyte = (secondbyte - 48) * 64 + (s[++i] - 48) * 8 + (s[++i] - 48);
if (thebyte > 127) {
thebyte -= 256;
}
buf[bufpos++] = (byte) thebyte;
}
} else {
buf[bufpos++] = nextbyte;
}
}
if (bufpos == correctSize) {
return buf;
}
byte[] result = new byte[bufpos];
System.arraycopy(buf, 0, result, 0, bufpos);
return result;
}
public static String toPGString(byte[] buf) {
if (buf == null) {
return null;
}
StringBuilder stringBuilder = new StringBuilder(2 * buf.length);
for (byte element : buf) {
int elementAsInt = (int) element;
if (elementAsInt < 0) {
elementAsInt = 256 + elementAsInt;
}
if (elementAsInt < 040 || elementAsInt > 0176) {
stringBuilder.append("\\");
stringBuilder.append((char) (((elementAsInt >> 6) & 0x3) + 48));
stringBuilder.append((char) (((elementAsInt >> 3) & 0x7) + 48));
stringBuilder.append((char) ((elementAsInt & 0x07) + 48));
} else if (element == (byte) '\\') {
stringBuilder.append("\\\\");
} else {
stringBuilder.append((char) element);
}
}
return stringBuilder.toString();
}
}