Debian Codegraph @

src/main/org/h2/expression/function/BitFunction.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.expression.function;
7
8 import java.util.Arrays;
9
10 import org.h2.engine.SessionLocal;
11 import org.h2.expression.Expression;
12 import org.h2.expression.TypedValueExpression;
13 import org.h2.expression.aggregate.Aggregate;
14 import org.h2.expression.aggregate.AggregateType;
15 import org.h2.message.DbException;
16 import org.h2.mvstore.db.Store;
17 import org.h2.util.Bits;
18 import org.h2.value.DataType;
19 import org.h2.value.TypeInfo;
20 import org.h2.value.Value;
21 import org.h2.value.ValueBigint;
22 import org.h2.value.ValueBinary;
23 import org.h2.value.ValueBoolean;
24 import org.h2.value.ValueInteger;
25 import org.h2.value.ValueSmallint;
26 import org.h2.value.ValueTinyint;
27 import org.h2.value.ValueVarbinary;
28
29 /**
30 * A bitwise function.
31 */
32 public final class BitFunction extends Function1_2 {
33
34 /**
35 * BITAND() (non-standard).
36 */
37 public static final int BITAND = 0;
38
39 /**
40 * BITOR() (non-standard).
41 */
42 public static final int BITOR = BITAND + 1;
43
44 /**
45 * BITXOR() (non-standard).
46 */
47 public static final int BITXOR = BITOR + 1;
48
49 /**
50 * BITNOT() (non-standard).
51 */
52 public static final int BITNOT = BITXOR + 1;
53
54 /**
55 * BITNAND() (non-standard).
56 */
57 public static final int BITNAND = BITNOT + 1;
58
59 /**
60 * BITNOR() (non-standard).
61 */
62 public static final int BITNOR = BITNAND + 1;
63
64 /**
65 * BITXNOR() (non-standard).
66 */
67 public static final int BITXNOR = BITNOR + 1;
68
69 /**
70 * BITGET() (non-standard).
71 */
72 public static final int BITGET = BITXNOR + 1;
73
74 /**
75 * BITCOUNT() (non-standard).
76 */
77 public static final int BITCOUNT = BITGET + 1;
78
79 /**
80 * LSHIFT() (non-standard).
81 */
82 public static final int LSHIFT = BITCOUNT + 1;
83
84 /**
85 * RSHIFT() (non-standard).
86 */
87 public static final int RSHIFT = LSHIFT + 1;
88
89 /**
90 * ULSHIFT() (non-standard).
91 */
92 public static final int ULSHIFT = RSHIFT + 1;
93
94 /**
95 * URSHIFT() (non-standard).
96 */
97 public static final int URSHIFT = ULSHIFT + 1;
98
99 /**
100 * ROTATELEFT() (non-standard).
101 */
102 public static final int ROTATELEFT = URSHIFT + 1;
103
104 /**
105 * ROTATERIGHT() (non-standard).
106 */
107 public static final int ROTATERIGHT = ROTATELEFT + 1;
108
109 private static final String[] NAMES = { //
110 "BITAND", "BITOR", "BITXOR", "BITNOT", "BITNAND", "BITNOR", "BITXNOR", "BITGET", "BITCOUNT", "LSHIFT",
111 "RSHIFT", "ULSHIFT", "URSHIFT", "ROTATELEFT", "ROTATERIGHT" //
112 };
113
114 private final int function;
115
116 public BitFunction(Expression arg1, Expression arg2, int function) {
117 super(arg1, arg2);
118 this.function = function;
119 }
120
121 @Override
122 public Value getValue(SessionLocal session, Value v1, Value v2) {
123 switch (function) {
124 case BITGET:
125 return bitGet(v1, v2);
126 case BITCOUNT:
127 return bitCount(v1);
128 case LSHIFT:
129 return shift(v1, v2.getLong(), false);
130 case RSHIFT: {
131 long offset = v2.getLong();
132 return shift(v1, offset != Long.MIN_VALUE ? -offset : Long.MAX_VALUE, false);
133 }
134 case ULSHIFT:
135 return shift(v1, v2.getLong(), true);
136 case URSHIFT:
137 return shift(v1, -v2.getLong(), true);
138 case ROTATELEFT:
139 return rotate(v1, v2.getLong(), false);
140 case ROTATERIGHT:
141 return rotate(v1, v2.getLong(), true);
142 }
143 return getBitwise(function, type, v1, v2);
144 }
145
146 private static ValueBoolean bitGet(Value v1, Value v2) {
147 long offset = v2.getLong();
148 boolean b;
149 if (offset >= 0L) {
150 switch (v1.getValueType()) {
151 case Value.BINARY:
152 case Value.VARBINARY: {
153 byte[] bytes = v1.getBytesNoCopy();
154 int bit = (int) (offset & 0x7);
155 offset >>>= 3;
156 b = offset < bytes.length && (bytes[(int) offset] & (1 << bit)) != 0;
157 break;
158 }
159 case Value.TINYINT:
160 b = offset < 8 && (v1.getByte() & (1 << offset)) != 0;
161 break;
162 case Value.SMALLINT:
163 b = offset < 16 && (v1.getShort() & (1 << offset)) != 0;
164 break;
165 case Value.INTEGER:
166 b = offset < 32 && (v1.getInt() & (1 << offset)) != 0;
167 break;
168 case Value.BIGINT:
169 b = (v1.getLong() & (1L << offset)) != 0;
170 break;
171 default:
172 throw DbException.getInvalidValueException("bit function parameter", v1.getTraceSQL());
173 }
174 } else {
175 b = false;
176 }
177 return ValueBoolean.get(b);
178 }
179
180 private static ValueBigint bitCount(Value v1) {
181 long c;
182 switch (v1.getValueType()) {
183 case Value.BINARY:
184 case Value.VARBINARY: {
185 byte[] bytes = v1.getBytesNoCopy();
186 int l = bytes.length;
187 c = 0L;
188 int i = 0;
189 for (int bound = l & 0xfffffff8; i < bound; i += 8) {
190 c += Long.bitCount(Bits.readLong(bytes, i));
191 }
192 for (; i < l; i++) {
193 c += Integer.bitCount(bytes[i] & 0xff);
194 }
195 break;
196 }
197 case Value.TINYINT:
198 c = Integer.bitCount(v1.getByte() & 0xff);
199 break;
200 case Value.SMALLINT:
201 c = Integer.bitCount(v1.getShort() & 0xffff);
202 break;
203 case Value.INTEGER:
204 c = Integer.bitCount(v1.getInt());
205 break;
206 case Value.BIGINT:
207 c = Long.bitCount(v1.getLong());
208 break;
209 default:
210 throw DbException.getInvalidValueException("bit function parameter", v1.getTraceSQL());
211 }
212 return ValueBigint.get(c);
213 }
214
215 private static Value shift(Value v1, long offset, boolean unsigned) {
216 if (offset == 0L) {
217 return v1;
218 }
219 int vt = v1.getValueType();
220 switch (vt) {
221 case Value.BINARY:
222 case Value.VARBINARY: {
223 byte[] bytes = v1.getBytesNoCopy();
224 int length = bytes.length;
225 if (length == 0) {
226 return v1;
227 }
228 byte[] newBytes = new byte[length];
229 if (offset > -8L * length && offset < 8L * length) {
230 if (offset > 0) {
231 int nBytes = (int) (offset >> 3);
232 int nBits = ((int) offset) & 0x7;
233 if (nBits == 0) {
234 System.arraycopy(bytes, nBytes, newBytes, 0, length - nBytes);
235 } else {
236 int nBits2 = 8 - nBits;
237 int dstIndex = 0, srcIndex = nBytes;
238 length--;
239 while (srcIndex < length) {
240 newBytes[dstIndex++] = (byte) (bytes[srcIndex++] << nBits
241 | (bytes[srcIndex] & 0xff) >>> nBits2);
242 }
243 newBytes[dstIndex] = (byte) (bytes[srcIndex] << nBits);
244 }
245 } else {
246 offset = -offset;
247 int nBytes = (int) (offset >> 3);
248 int nBits = ((int) offset) & 0x7;
249 if (nBits == 0) {
250 System.arraycopy(bytes, 0, newBytes, nBytes, length - nBytes);
251 } else {
252 int nBits2 = 8 - nBits;
253 int dstIndex = nBytes, srcIndex = 0;
254 newBytes[dstIndex++] = (byte) ((bytes[srcIndex] & 0xff) >>> nBits);
255 while (dstIndex < length) {
256 newBytes[dstIndex++] = (byte) (bytes[srcIndex++] << nBits2
257 | (bytes[srcIndex] & 0xff) >>> nBits);
258 }
259 }
260 }
261 }
262 return vt == Value.BINARY ? ValueBinary.getNoCopy(newBytes) : ValueVarbinary.getNoCopy(newBytes);
263 }
264 case Value.TINYINT: {
265 byte v;
266 if (offset < 8) {
267 v = v1.getByte();
268 if (offset > -8) {
269 if (offset > 0) {
270 v <<= (int) offset;
271 } else if (unsigned) {
272 v = (byte) ((v & 0xFF) >>> (int) -offset);
273 } else {
274 v >>= (int) -offset;
275 }
276 } else if (unsigned) {
277 v = 0;
278 } else {
279 v >>= 7;
280 }
281 } else {
282 v = 0;
283 }
284 return ValueTinyint.get(v);
285 }
286 case Value.SMALLINT: {
287 short v;
288 if (offset < 16) {
289 v = v1.getShort();
290 if (offset > -16) {
291 if (offset > 0) {
292 v <<= (int) offset;
293 } else if (unsigned) {
294 v = (short) ((v & 0xFFFF) >>> (int) -offset);
295 } else {
296 v >>= (int) -offset;
297 }
298 } else if (unsigned) {
299 v = 0;
300 } else {
301 v >>= 15;
302 }
303 } else {
304 v = 0;
305 }
306 return ValueSmallint.get(v);
307 }
308 case Value.INTEGER: {
309 int v;
310 if (offset < 32) {
311 v = v1.getInt();
312 if (offset > -32) {
313 if (offset > 0) {
314 v <<= (int) offset;
315 } else if (unsigned) {
316 v >>>= (int) -offset;
317 } else {
318 v >>= (int) -offset;
319 }
320 } else if (unsigned) {
321 v = 0;
322 } else {
323 v >>= 31;
324 }
325 } else {
326 v = 0;
327 }
328 return ValueInteger.get(v);
329 }
330 case Value.BIGINT: {
331 long v;
332 if (offset < 64) {
333 v = v1.getLong();
334 if (offset > -64) {
335 if (offset > 0) {
336 v <<= offset;
337 } else if (unsigned) {
338 v >>>= -offset;
339 } else {
340 v >>= -offset;
341 }
342 } else if (unsigned) {
343 v = 0;
344 } else {
345 v >>= 63;
346 }
347 } else {
348 v = 0;
349 }
350 return ValueBigint.get(v);
351 }
352 default:
353 throw DbException.getInvalidValueException("bit function parameter", v1.getTraceSQL());
354 }
355 }
356
357 private static Value rotate(Value v1, long offset, boolean right) {
358 int vt = v1.getValueType();
359 switch (vt) {
360 case Value.BINARY:
361 case Value.VARBINARY: {
362 byte[] bytes = v1.getBytesNoCopy();
363 int length = bytes.length;
364 if (length == 0) {
365 return v1;
366 }
367 long bitLength = length << 3L;
368 offset %= bitLength;
369 if (right) {
370 offset = -offset;
371 }
372 if (offset == 0L) {
373 return v1;
374 } else if (offset < 0) {
375 offset += bitLength;
376 }
377 byte[] newBytes = new byte[length];
378 int nBytes = (int) (offset >> 3);
379 int nBits = ((int) offset) & 0x7;
380 if (nBits == 0) {
381 System.arraycopy(bytes, nBytes, newBytes, 0, length - nBytes);
382 System.arraycopy(bytes, 0, newBytes, length - nBytes, nBytes);
383 } else {
384 int nBits2 = 8 - nBits;
385 for (int dstIndex = 0, srcIndex = nBytes; dstIndex < length;) {
386 newBytes[dstIndex++] = (byte) (bytes[srcIndex] << nBits
387 | (bytes[srcIndex = (srcIndex + 1) % length] & 0xFF) >>> nBits2);
388 }
389 }
390 return vt == Value.BINARY ? ValueBinary.getNoCopy(newBytes) : ValueVarbinary.getNoCopy(newBytes);
391 }
392 case Value.TINYINT: {
393 int o = (int) offset;
394 if (right) {
395 o = -o;
396 }
397 if ((o &= 0x7) == 0) {
398 return v1;
399 }
400 int v = v1.getByte() & 0xFF;
401 return ValueTinyint.get((byte) ((v << o) | (v >>> 8 - o)));
402 }
403 case Value.SMALLINT: {
404 int o = (int) offset;
405 if (right) {
406 o = -o;
407 }
408 if ((o &= 0xF) == 0) {
409 return v1;
410 }
411 int v = v1.getShort() & 0xFFFF;
412 return ValueSmallint.get((short) ((v << o) | (v >>> 16 - o)));
413 }
414 case Value.INTEGER: {
415 int o = (int) offset;
416 if (right) {
417 o = -o;
418 }
419 if ((o &= 0x1F) == 0) {
420 return v1;
421 }
422 return ValueInteger.get(Integer.rotateLeft(v1.getInt(), o));
423 }
424 case Value.BIGINT: {
425 int o = (int) offset;
426 if (right) {
427 o = -o;
428 }
429 if ((o &= 0x3F) == 0) {
430 return v1;
431 }
432 return ValueBigint.get(Long.rotateLeft(v1.getLong(), o));
433 }
434 default:
435 throw DbException.getInvalidValueException("bit function parameter", v1.getTraceSQL());
436 }
437 }
438
439 /**
440 * Computes the value of bitwise function.
441 *
442 * @param function
443 * one of {@link #BITAND}, {@link #BITOR}, {@link #BITXOR},
444 * {@link #BITNOT}, {@link #BITNAND}, {@link #BITNOR},
445 * {@link #BITXNOR}
446 * @param type
447 * the type of result
448 * @param v1
449 * the value of first argument
450 * @param v2
451 * the value of second argument, or {@code null}
452 * @return the resulting value
453 */
454 public static Value getBitwise(int function, TypeInfo type, Value v1, Value v2) {
455 return type.getValueType() < Value.TINYINT ? getBinaryString(function, type, v1, v2)
456 : getNumeric(function, type, v1, v2);
457 }
458
459 private static Value getBinaryString(int function, TypeInfo type, Value v1, Value v2) {
460 byte[] bytes;
461 if (function == BITNOT) {
462 bytes = v1.getBytes();
463 for (int i = 0, l = bytes.length; i < l; i++) {
464 bytes[i] = (byte) ~bytes[i];
465 }
466 } else {
467 byte[] bytes1 = v1.getBytesNoCopy(), bytes2 = v2.getBytesNoCopy();
468 int length1 = bytes1.length, length2 = bytes2.length;
469 int min, max;
470 if (length1 <= length2) {
471 min = length1;
472 max = length2;
473 } else {
474 min = length2;
475 max = length1;
476 byte[] t = bytes1;
477 bytes1 = bytes2;
478 bytes2 = t;
479 }
480 int limit = (int) type.getPrecision();
481 if (min > limit) {
482 max = min = limit;
483 } else if (max > limit) {
484 max = limit;
485 }
486 bytes = new byte[max];
487 int i = 0;
488 switch (function) {
489 case BITAND:
490 for (; i < min; i++) {
491 bytes[i] = (byte) (bytes1[i] & bytes2[i]);
492 }
493 break;
494 case BITOR:
495 for (; i < min; i++) {
496 bytes[i] = (byte) (bytes1[i] | bytes2[i]);
497 }
498 System.arraycopy(bytes2, i, bytes, i, max - i);
499 break;
500 case BITXOR:
501 for (; i < min; i++) {
502 bytes[i] = (byte) (bytes1[i] ^ bytes2[i]);
503 }
504 System.arraycopy(bytes2, i, bytes, i, max - i);
505 break;
506 case BITNAND:
507 for (; i < min; i++) {
508 bytes[i] = (byte) ~(bytes1[i] & bytes2[i]);
509 }
510 Arrays.fill(bytes, i, max, (byte) -1);
511 break;
512 case BITNOR:
513 for (; i < min; i++) {
514 bytes[i] = (byte) ~(bytes1[i] | bytes2[i]);
515 }
516 for (; i < max; i++) {
517 bytes[i] = (byte) ~bytes2[i];
518 }
519 break;
520 case BITXNOR:
521 for (; i < min; i++) {
522 bytes[i] = (byte) ~(bytes1[i] ^ bytes2[i]);
523 }
524 for (; i < max; i++) {
525 bytes[i] = (byte) ~bytes2[i];
526 }
527 break;
528 default:
529 throw DbException.getInternalError("function=" + function);
530 }
531 }
532 return type.getValueType() == Value.BINARY ? ValueBinary.getNoCopy(bytes) : ValueVarbinary.getNoCopy(bytes);
533 }
534
535 private static Value getNumeric(int function, TypeInfo type, Value v1, Value v2) {
536 long l1 = v1.getLong();
537 switch (function) {
538 case BITAND:
539 l1 &= v2.getLong();
540 break;
541 case BITOR:
542 l1 |= v2.getLong();
543 break;
544 case BITXOR:
545 l1 ^= v2.getLong();
546 break;
547 case BITNOT:
548 l1 = ~l1;
549 break;
550 case BITNAND:
551 l1 = ~(l1 & v2.getLong());
552 break;
553 case BITNOR:
554 l1 = ~(l1 | v2.getLong());
555 break;
556 case BITXNOR:
557 l1 = ~(l1 ^ v2.getLong());
558 break;
559 default:
560 throw DbException.getInternalError("function=" + function);
561 }
562 switch (type.getValueType()) {
563 case Value.TINYINT:
564 return ValueTinyint.get((byte) l1);
565 case Value.SMALLINT:
566 return ValueSmallint.get((short) l1);
567 case Value.INTEGER:
568 return ValueInteger.get((int) l1);
569 case Value.BIGINT:
570 return ValueBigint.get(l1);
571 default:
572 throw DbException.getInternalError();
573 }
574 }
575
576 @Override
577 public Expression optimize(SessionLocal session) {
578 left = left.optimize(session);
579 if (right != null) {
580 right = right.optimize(session);
581 }
582 switch (function) {
583 case BITNOT:
584 return optimizeNot(session);
585 case BITGET:
586 type = TypeInfo.TYPE_BOOLEAN;
587 break;
588 case BITCOUNT:
589 type = TypeInfo.TYPE_BIGINT;
590 break;
591 case LSHIFT:
592 case RSHIFT:
593 case ULSHIFT:
594 case URSHIFT:
595 case ROTATELEFT:
596 case ROTATERIGHT:
597 type = checkArgType(left);
598 break;
599 default:
600 type = getCommonType(left, right);
601 break;
602 }
603 if (left.isConstant() && (right == null || right.isConstant())) {
604 return TypedValueExpression.getTypedIfNull(getValue(session), type);
605 }
606 return this;
607 }
608
609 private Expression optimizeNot(SessionLocal session) {
610 type = checkArgType(left);
611 if (left.isConstant()) {
612 return TypedValueExpression.getTypedIfNull(getValue(session), type);
613 } else if (left instanceof BitFunction) {
614 BitFunction l = (BitFunction) left;
615 int f = l.function;
616 switch (f) {
617 case BITAND:
618 case BITOR:
619 case BITXOR:
620 f += BITNAND - BITAND;
621 break;
622 case BITNOT:
623 return l.left;
624 case BITNAND:
625 case BITNOR:
626 case BITXNOR:
627 f -= BITNAND - BITAND;
628 break;
629 default:
630 return this;
631 }
632 return new BitFunction(l.left, l.right, f).optimize(session);
633 } else if (left instanceof Aggregate) {
634 Aggregate l = (Aggregate) left;
635 AggregateType t;
636 switch (l.getAggregateType()) {
637 case BIT_AND_AGG:
638 t = AggregateType.BIT_NAND_AGG;
639 break;
640 case BIT_OR_AGG:
641 t = AggregateType.BIT_NOR_AGG;
642 break;
643 case BIT_XOR_AGG:
644 t = AggregateType.BIT_XNOR_AGG;
645 break;
646 case BIT_NAND_AGG:
647 t = AggregateType.BIT_AND_AGG;
648 break;
649 case BIT_NOR_AGG:
650 t = AggregateType.BIT_OR_AGG;
651 break;
652 case BIT_XNOR_AGG:
653 t = AggregateType.BIT_XOR_AGG;
654 break;
655 default:
656 return this;
657 }
658 Aggregate aggregate = new Aggregate(t, new Expression[] { l.getSubexpression(0) }, l.getSelect(),
659 l.isDistinct());
660 aggregate.setFilterCondition(l.getFilterCondition());
661 aggregate.setOverCondition(l.getOverCondition());
662 return aggregate.optimize(session);
663 }
664 return this;
665 }
666
667 private static TypeInfo getCommonType(Expression arg1, Expression arg2) {
668 TypeInfo t1 = checkArgType(arg1), t2 = checkArgType(arg2);
669 int vt1 = t1.getValueType(), vt2 = t2.getValueType();
670 boolean bs = DataType.isBinaryStringType(vt1);
671 if (bs != DataType.isBinaryStringType(vt2)) {
672 throw DbException.getInvalidValueException("bit function parameters",
673 t2.getSQL(t1.getSQL(new StringBuilder(), TRACE_SQL_FLAGS).append(" vs "), TRACE_SQL_FLAGS)
674 .toString());
675 }
676 if (bs) {
677 long precision;
678 if (vt1 == Value.BINARY) {
679 precision = t1.getDeclaredPrecision();
680 if (vt2 == Value.BINARY) {
681 precision = Math.max(precision, t2.getDeclaredPrecision());
682 }
683 } else {
684 if (vt2 == Value.BINARY) {
685 vt1 = Value.BINARY;
686 precision = t2.getDeclaredPrecision();
687 } else {
688 long precision1 = t1.getDeclaredPrecision(), precision2 = t2.getDeclaredPrecision();
689 precision = precision1 <= 0L || precision2 <= 0L ? -1L : Math.max(precision1, precision2);
690 }
691 }
692 return TypeInfo.getTypeInfo(vt1, precision, 0, null);
693 }
694 return TypeInfo.getTypeInfo(Math.max(vt1, vt2));
695 }
696
697 /**
698 * Checks the type of an argument of bitwise function (one of
699 * {@link #BITAND}, {@link #BITOR}, {@link #BITXOR}, {@link #BITNOT},
700 * {@link #BITNAND}, {@link #BITNOR}, {@link #BITXNOR}).
701 *
702 * @param arg
703 * the argument
704 * @return the type of the specified argument
705 * @throws DbException
706 * if argument type is not supported by bitwise functions
707 */
708 public static TypeInfo checkArgType(Expression arg) {
709 TypeInfo t = arg.getType();
710 switch (t.getValueType()) {
711 case Value.NULL:
712 case Value.BINARY:
713 case Value.VARBINARY:
714 case Value.TINYINT:
715 case Value.SMALLINT:
716 case Value.INTEGER:
717 case Value.BIGINT:
718 return t;
719 }
720 throw Store.getInvalidExpressionTypeException("bit function argument", arg);
721 }
722
723 @Override
724 public String getName() {
725 return NAMES[function];
726 }
727
728 }