Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HIVE-27094: Support of big numbers conversions #4074

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
179 changes: 48 additions & 131 deletions ql/src/java/org/apache/hadoop/hive/ql/udf/UDFConv.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
*/
package org.apache.hadoop.hive.ql.udf;

import java.util.Arrays;
import java.math.BigInteger;
import java.util.Locale;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDF;
Expand All @@ -39,104 +40,6 @@
+ " > SELECT _FUNC_(-10, 16, -10) FROM src LIMIT 1;\n" + " '16'")
public class UDFConv extends UDF {
private final Text result = new Text();
private final byte[] value = new byte[64];

/**
* Divide x by m as if x is an unsigned 64-bit integer. Examples:
* unsignedLongDiv(-1, 2) == Long.MAX_VALUE unsignedLongDiv(6, 3) == 2
* unsignedLongDiv(0, 5) == 0
*
* @param x
* is treated as unsigned
* @param m
* is treated as signed
*/
private long unsignedLongDiv(long x, int m) {
if (x >= 0) {
return x / m;
}

// Let uval be the value of the unsigned long with the same bits as x
// Two's complement => x = uval - 2*MAX - 2
// => uval = x + 2*MAX + 2
// Now, use the fact: (a+b)/c = a/c + b/c + (a%c+b%c)/c
return x / m + 2 * (Long.MAX_VALUE / m) + 2 / m
+ (x % m + 2 * (Long.MAX_VALUE % m) + 2 % m) / m;
}

/**
* Decode val into value[].
*
* @param val
* is treated as an unsigned 64-bit integer
* @param radix
* must be between MIN_RADIX and MAX_RADIX
*/
private void decode(long val, int radix) {
Arrays.fill(value, (byte) 0);
for (int i = value.length - 1; val != 0; i--) {
long q = unsignedLongDiv(val, radix);
value[i] = (byte) (val - q * radix);
val = q;
}
}

/**
* Convert value[] into a long. On overflow, return -1 (as mySQL does). If a
* negative digit is found, ignore the suffix starting there.
*
* @param radix
* must be between MIN_RADIX and MAX_RADIX
* @param fromPos
* is the first element that should be conisdered
* @return the result should be treated as an unsigned 64-bit integer.
*/
private long encode(int radix, int fromPos) {
long val = 0;
long bound = unsignedLongDiv(-1 - radix, radix); // Possible overflow once
// val
// exceeds this value
for (int i = fromPos; i < value.length && value[i] >= 0; i++) {
if (val >= bound) {
// Check for overflow
if (unsignedLongDiv(-1 - value[i], radix) < val) {
return -1;
}
}
val = val * radix + value[i];
}
return val;
}

/**
* Convert the bytes in value[] to the corresponding chars.
*
* @param radix
* must be between MIN_RADIX and MAX_RADIX
* @param fromPos
* is the first nonzero element
*/
private void byte2char(int radix, int fromPos) {
for (int i = fromPos; i < value.length; i++) {
value[i] = (byte) Character.toUpperCase(Character.forDigit(value[i],
radix));
}
}

/**
* Convert the chars in value[] to the corresponding integers. Convert invalid
* characters to -1.
*
* @param radix
* must be between MIN_RADIX and MAX_RADIX
* @param fromPos
* is the first nonzero element
*/
private void char2byte(int radix, int fromPos) {
for (int i = fromPos; i < value.length; i++) {
value[i] = (byte) Character.digit(value[i], radix);
}
}

/**
* Convert numbers between different number bases. If toBase&gt;0 the result is
Expand All @@ -150,55 +53,69 @@ public Text evaluate(Text n, IntWritable fromBase, IntWritable toBase) {

int fromBs = fromBase.get();
int toBs = toBase.get();
int toBaseAbsoluteValue = Math.abs(toBs);
if (fromBs < Character.MIN_RADIX || fromBs > Character.MAX_RADIX
|| Math.abs(toBs) < Character.MIN_RADIX
|| Math.abs(toBs) > Character.MAX_RADIX) {
|| toBaseAbsoluteValue < Character.MIN_RADIX
|| toBaseAbsoluteValue > Character.MAX_RADIX) {
return null;
}

byte[] num = n.getBytes();
if (num.length == 0) {
String num = n.toString();
if (num.isEmpty()) {
return null;
}
boolean negative = (num[0] == '-');
int first = 0;
if (negative) {
first = 1;

String validNum = getLongestValidPrefix(num, fromBs);
if (validNum == null || validNum.isEmpty()) {
return null;
}

// Copy the digits in the right side of the array
for (int i = 1; i <= n.getLength() - first; i++) {
value[value.length - i] = num[n.getLength() - i];
BigInteger bigInteger = new BigInteger(validNum, fromBs);
BigInteger bigIntegerResolved = toBs > 0 ? getUnsignedBigInt(bigInteger) : bigInteger;
String convertedValue = bigIntegerResolved
.toString(toBaseAbsoluteValue)
.toUpperCase(Locale.ROOT);
result.set(convertedValue);
return result;
}

private boolean isSign(char c) {
return c == '-' || c == '+';
}

private String getLongestValidPrefix(String num, int radix) {
boolean isSigned = isSign(num.charAt(0));
StringBuilder builder = new StringBuilder();
int startIndex = 0;
if (isSigned) {
builder.append(num.charAt(0));
startIndex = 1;
}
char2byte(fromBs, value.length - n.getLength() + first);

// Do the conversion by going through a 64 bit integer
long val = encode(fromBs, value.length - n.getLength() + first);
if (negative && toBs > 0) {
if (val < 0) {
val = -1;
char[] charNumbers = num.toCharArray();
for (int i = startIndex; i < charNumbers.length; i++) {
char charNumber = charNumbers[i];
if (Character.digit(charNumber, radix) >= 0) {
builder.append(charNumber);
} else {
val = -val;
break;
}
}
if (toBs < 0 && val < 0) {
val = -val;
negative = true;
}
decode(val, Math.abs(toBs));

// Find the first non-zero digit or the last digits if all are zero.
for (first = 0; first < value.length - 1 && value[first] == 0; first++) {
;
if (isSigned && builder.length() == 1) {
return null;
}

byte2char(Math.abs(toBs), first);
return builder.toString();
}

if (negative && toBs < 0) {
value[--first] = '-';
private BigInteger getUnsignedBigInt(BigInteger bigInteger) {
boolean isValueSigned = bigInteger.signum() < 0;
if (isValueSigned) {
BigInteger shiftedOne = BigInteger.ONE.shiftLeft(Math.max(bigInteger.bitLength(), 64));
return bigInteger.add(shiftedOne);
} else {
return bigInteger;
}

result.set(value, first, value.length - first);
return result;
}
}
99 changes: 99 additions & 0 deletions ql/src/test/org/apache/hadoop/hive/ql/udf/TestUDFConv.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.hadoop.hive.ql.udf;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
* Unit test cases for UDFConv class.
*/
public class TestUDFConv {

private UDFConv udf;

@Before
public void setUp() {
udf = new UDFConv();
}

@Test
public void testConvFunctionSmallNumbers() {
runAndVerifyStr("3", 10, 2, "11", udf);
runAndVerifyStr("-15", 10, -16, "-F", udf);
runAndVerifyStr("-15", 10, 16, "FFFFFFFFFFFFFFF1", udf);
runAndVerifyStr("big", 36, 16, "3A48", udf);
runAndVerifyStr(null, 36, 16, null, udf);
runAndVerifyStr("3", null, 16, null, udf);
runAndVerifyStr("3", 16, null, null, udf);
runAndVerifyStr("1234", 10, 37, null, udf);
runAndVerifyStr("", 10, 16, null, udf);
runAndVerifyStr("3", -10, 2, null, udf);
runAndVerifyStr("3", -10, -2, null, udf);
runAndVerifyStr("3", 0, -2, null, udf);
runAndVerifyStr("3", 10, 0, null, udf);
runAndVerifyStr("3", 2, 10, null, udf);
runAndVerifyStr("a", 36, 10, "10", udf);
runAndVerifyStr("A", 36, 10, "10", udf);
runAndVerifyStr("10", 10, 36, "A", udf);
}

@Test
public void testConvFunctionBigNumbers() {
runAndVerifyStr("9223372036854775807", 36, 16, "12DDAC15F246BAF8C0D551AC7", udf);
runAndVerifyStr("92233720368547758070", 10, 16, "4FFFFFFFFFFFFFFF6", udf);
runAndVerifyStr("-92233720368547758070", 10, -16, "-4FFFFFFFFFFFFFFF6", udf);
runAndVerifyStr("-92233720368547758070", 10, 16, "3000000000000000A", udf);
runAndVerifyStr("100000000000000000000000000000000000000000000000000000000000000000", 2, 10,
"36893488147419103232", udf);
runAndVerifyStr("100000000000000000000000000000000000000000000000000000000000000000", 2, 8,
"4000000000000000000000", udf);
runAndVerifyStr("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16, 10,
"115792089237316195423570985008687907853269984665640564039457584007913129639935", udf);
}

@Test
public void testConvFunctionWithInvalidCharacters() {
runAndVerifyStr("11abc", 10, 16, "B", udf);
runAndVerifyStr("ABC325TGH", 16, 10, "11256613", udf);
runAndVerifyStr("ABC325 TGH", 16, 10, "11256613", udf);
runAndVerifyStr("-11abc", 10, -16, "-B", udf);
runAndVerifyStr("+010134", 2, 10, "5", udf);
runAndVerifyStr("+01A0134", 2, 10, "1", udf);
runAndVerifyStr("+01-01", 2, 10, "1", udf);
runAndVerifyStr("++01A0134", 2, 10, null, udf);
runAndVerifyStr("--1", 2, 10, null, udf);
runAndVerifyStr("++1", 2, 10, null, udf);
runAndVerifyStr("-", 2, 10, null, udf);
runAndVerifyStr("+", 2, 10, null, udf);
runAndVerifyStr("?", 2, 10, null, udf);
}

private void runAndVerifyStr(String str, Integer fromBase, Integer toBase, String expResult, UDFConv udf) {
Text t = str != null ? new Text(str) : null;
IntWritable fromBaseResolved = fromBase != null ? new IntWritable(fromBase) : null;
IntWritable toBaseResolved = toBase != null ? new IntWritable(toBase) : null;
Text output = udf.evaluate(t, fromBaseResolved, toBaseResolved);
assertEquals("conv function test ", expResult, output != null ? output.toString() : null);
}
}
4 changes: 2 additions & 2 deletions ql/src/test/results/clientpositive/llap/udf_conv.q.out
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ FROM src tablesample (1 rows)
POSTHOOK: type: QUERY
POSTHOOK: Input: default@src
#### A masked pattern was here ####
FFFFFFFFFFFFFFFF -1 FFFFFFFFFFFFFFFF -1
12DDAC15F246BAF8C0D551AC7 12DDAC15F246BAF8C0D551AC7 D2253EA0DB945073F2AAE539 -12DDAC15F246BAF8C0D551AC7
PREHOOK: query: SELECT
conv('123455', 3, 10),
conv('131', 1, 5),
Expand Down Expand Up @@ -146,7 +146,7 @@ FROM src tablesample (1 rows)
POSTHOOK: type: QUERY
POSTHOOK: Input: default@src
#### A masked pattern was here ####
FFFFFFFFFFFFFFFF -1 FFFFFFFFFFFFFFFF -1
12DDAC15F246BAF8C0D551AC7 12DDAC15F246BAF8C0D551AC7 D2253EA0DB945073F2AAE539 -12DDAC15F246BAF8C0D551AC7
PREHOOK: query: SELECT
conv(123455, 3, 10),
conv(131, 1, 5),
Expand Down