[120] | 1 | /** |
---|
| 2 | * Licensed to the Apache Software Foundation (ASF) under one |
---|
| 3 | * or more contributor license agreements. See the NOTICE file |
---|
| 4 | * distributed with this work for additional information |
---|
| 5 | * regarding copyright ownership. The ASF licenses this file |
---|
| 6 | * to you under the Apache License, Version 2.0 (the |
---|
| 7 | * "License"); you may not use this file except in compliance |
---|
| 8 | * with the License. You may obtain a copy of the License at |
---|
| 9 | * |
---|
| 10 | * http://www.apache.org/licenses/LICENSE-2.0 |
---|
| 11 | * |
---|
| 12 | * Unless required by applicable law or agreed to in writing, software |
---|
| 13 | * distributed under the License is distributed on an "AS IS" BASIS, |
---|
| 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
---|
| 15 | * See the License for the specific language governing permissions and |
---|
| 16 | * limitations under the License. |
---|
| 17 | */ |
---|
| 18 | |
---|
| 19 | package org.apache.hadoop.io.serializer; |
---|
| 20 | |
---|
| 21 | import java.io.IOException; |
---|
| 22 | import java.util.Comparator; |
---|
| 23 | |
---|
| 24 | import org.apache.hadoop.io.InputBuffer; |
---|
| 25 | import org.apache.hadoop.io.RawComparator; |
---|
| 26 | |
---|
| 27 | /** |
---|
| 28 | * <p> |
---|
| 29 | * A {@link RawComparator} that uses a {@link Deserializer} to deserialize |
---|
| 30 | * the objects to be compared so that the standard {@link Comparator} can |
---|
| 31 | * be used to compare them. |
---|
| 32 | * </p> |
---|
| 33 | * <p> |
---|
| 34 | * One may optimize compare-intensive operations by using a custom |
---|
| 35 | * implementation of {@link RawComparator} that operates directly |
---|
| 36 | * on byte representations. |
---|
| 37 | * </p> |
---|
| 38 | * @param <T> |
---|
| 39 | */ |
---|
| 40 | public abstract class DeserializerComparator<T> implements RawComparator<T> { |
---|
| 41 | |
---|
| 42 | private InputBuffer buffer = new InputBuffer(); |
---|
| 43 | private Deserializer<T> deserializer; |
---|
| 44 | |
---|
| 45 | private T key1; |
---|
| 46 | private T key2; |
---|
| 47 | |
---|
| 48 | protected DeserializerComparator(Deserializer<T> deserializer) |
---|
| 49 | throws IOException { |
---|
| 50 | |
---|
| 51 | this.deserializer = deserializer; |
---|
| 52 | this.deserializer.open(buffer); |
---|
| 53 | } |
---|
| 54 | |
---|
| 55 | public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { |
---|
| 56 | try { |
---|
| 57 | |
---|
| 58 | buffer.reset(b1, s1, l1); |
---|
| 59 | key1 = deserializer.deserialize(key1); |
---|
| 60 | |
---|
| 61 | buffer.reset(b2, s2, l2); |
---|
| 62 | key2 = deserializer.deserialize(key2); |
---|
| 63 | |
---|
| 64 | } catch (IOException e) { |
---|
| 65 | throw new RuntimeException(e); |
---|
| 66 | } |
---|
| 67 | return compare(key1, key2); |
---|
| 68 | } |
---|
| 69 | |
---|
| 70 | } |
---|