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, 13 * software distributed under the License is distributed on an 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 * 19 */ 20 package org.apache.mina.util.byteaccess; 21 22 23 /** 24 * 25 * Abstract class that implements {@link ByteArray}. This class will only be 26 * used internally and should not be used by end users. 27 * 28 * @author The Apache MINA Project (dev@mina.apache.org) 29 * @version $Rev$, $Date$ 30 */ 31 abstract class AbstractByteArray implements ByteArray 32 { 33 34 /** 35 * @inheritDoc 36 */ 37 public final int length() 38 { 39 return last() - first(); 40 } 41 42 43 /** 44 * @inheritDoc 45 */ 46 @Override 47 public final boolean equals( Object other ) 48 { 49 // Optimization: compare pointers. 50 if ( other == this ) 51 { 52 return true; 53 } 54 // Compare types. 55 if ( !( other instanceof ByteArray ) ) 56 { 57 return false; 58 } 59 ByteArray otherByteArray = ( ByteArray ) other; 60 // Compare properties. 61 if ( first() != otherByteArray.first() || last() != otherByteArray.last() 62 || !order().equals( otherByteArray.order() ) ) 63 { 64 return false; 65 } 66 // Compare bytes. 67 Cursor cursor = cursor(); 68 Cursor otherCursor = otherByteArray.cursor(); 69 for ( int remaining = cursor.getRemaining(); remaining > 0; ) 70 { 71 // Optimization: prefer int comparisons over byte comparisons 72 if ( remaining >= 4 ) 73 { 74 int i = cursor.getInt(); 75 int otherI = otherCursor.getInt(); 76 if ( i != otherI ) 77 { 78 return false; 79 } 80 } 81 else 82 { 83 byte b = cursor.get(); 84 byte otherB = otherCursor.get(); 85 if ( b != otherB ) 86 { 87 return false; 88 } 89 } 90 } 91 return true; 92 } 93 94 }