001/** 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018 019package org.apache.hadoop.io; 020 021import java.io.*; 022 023import org.apache.hadoop.classification.InterfaceAudience; 024import org.apache.hadoop.classification.InterfaceStability; 025 026/** A WritableComparable for a single byte. */ 027@InterfaceAudience.Public 028@InterfaceStability.Stable 029public class ByteWritable implements WritableComparable<ByteWritable> { 030 private byte value; 031 032 public ByteWritable() {} 033 034 public ByteWritable(byte value) { set(value); } 035 036 /** Set the value of this ByteWritable. */ 037 public void set(byte value) { this.value = value; } 038 039 /** Return the value of this ByteWritable. */ 040 public byte get() { return value; } 041 042 public void readFields(DataInput in) throws IOException { 043 value = in.readByte(); 044 } 045 046 public void write(DataOutput out) throws IOException { 047 out.writeByte(value); 048 } 049 050 /** Returns true iff <code>o</code> is a ByteWritable with the same value. */ 051 @Override 052 public boolean equals(Object o) { 053 if (!(o instanceof ByteWritable)) { 054 return false; 055 } 056 ByteWritable other = (ByteWritable)o; 057 return this.value == other.value; 058 } 059 060 @Override 061 public int hashCode() { 062 return (int)value; 063 } 064 065 /** Compares two ByteWritables. */ 066 @Override 067 public int compareTo(ByteWritable o) { 068 int thisValue = this.value; 069 int thatValue = o.value; 070 return (thisValue < thatValue ? -1 : (thisValue == thatValue ? 0 : 1)); 071 } 072 073 @Override 074 public String toString() { 075 return Byte.toString(value); 076 } 077 078 /** A Comparator optimized for ByteWritable. */ 079 public static class Comparator extends WritableComparator { 080 public Comparator() { 081 super(ByteWritable.class); 082 } 083 084 @Override 085 public int compare(byte[] b1, int s1, int l1, 086 byte[] b2, int s2, int l2) { 087 byte thisValue = b1[s1]; 088 byte thatValue = b2[s2]; 089 return (thisValue < thatValue ? -1 : (thisValue == thatValue ? 0 : 1)); 090 } 091 } 092 093 static { // register this comparator 094 WritableComparator.define(ByteWritable.class, new Comparator()); 095 } 096} 097