001 /*
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements. See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership. The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License. You may obtain a copy of the License at
010 *
011 * http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing,
014 * software distributed under the License is distributed on an
015 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
016 * KIND, either express or implied. See the License for the
017 * specific language governing permissions and limitations
018 * under the License.
019 *
020 */
021 package org.apache.qpid.transport;
022
023 import java.nio.ByteBuffer;
024
025 import static org.apache.qpid.transport.util.Functions.*;
026
027
028 /**
029 * Binary
030 *
031 */
032
033 public final class Binary
034 {
035
036 private byte[] bytes;
037 private int offset;
038 private int size;
039 private int hash = 0;
040
041 public Binary(byte[] bytes, int offset, int size)
042 {
043 if (offset + size > bytes.length)
044 {
045 throw new ArrayIndexOutOfBoundsException();
046 }
047
048 this.bytes = bytes;
049 this.offset = offset;
050 this.size = size;
051 }
052
053 public Binary(byte[] bytes)
054 {
055 this(bytes, 0, bytes.length);
056 }
057
058 public final byte[] getBytes()
059 {
060 byte[] result = new byte[size];
061 System.arraycopy(bytes, offset, result, 0, size);
062 return result;
063 }
064
065 public final byte[] array()
066 {
067 return bytes;
068 }
069
070 public final int offset()
071 {
072 return offset;
073 }
074
075 public final int size()
076 {
077 return size;
078 }
079
080 public final Binary slice(int low, int high)
081 {
082 int sz;
083
084 if (high < 0)
085 {
086 sz = size + high;
087 }
088 else
089 {
090 sz = high - low;
091 }
092
093 if (sz < 0)
094 {
095 sz = 0;
096 }
097
098 return new Binary(bytes, offset + low, sz);
099 }
100
101 public final int hashCode()
102 {
103 if (hash == 0)
104 {
105 int hc = 0;
106 for (int i = 0; i < size; i++)
107 {
108 hc = 31*hc + (0xFF & bytes[offset + i]);
109 }
110 hash = hc;
111 }
112
113 return hash;
114 }
115
116 public final boolean equals(Object o)
117 {
118 if (!(o instanceof Binary))
119 {
120 return false;
121 }
122
123 Binary buf = (Binary) o;
124 if (this.size != buf.size)
125 {
126 return false;
127 }
128
129 for (int i = 0; i < size; i++)
130 {
131 if (bytes[offset + i] != buf.bytes[buf.offset + i])
132 {
133 return false;
134 }
135 }
136
137 return true;
138 }
139
140 public String toString()
141 {
142 return str(ByteBuffer.wrap(bytes, offset, size));
143 }
144
145 }
|