Yuta HIGUCHI | 75fb1f4 | 2014-11-19 13:56:19 -0800 | [diff] [blame] | 1 | /* |
Brian O'Connor | a09fe5b | 2017-08-03 21:12:30 -0700 | [diff] [blame] | 2 | * Copyright 2014-present Open Networking Foundation |
Yuta HIGUCHI | 75fb1f4 | 2014-11-19 13:56:19 -0800 | [diff] [blame] | 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package org.onlab.util; |
| 18 | |
| 19 | import java.util.Arrays; |
| 20 | |
| 21 | import com.google.common.base.MoreObjects; |
| 22 | import com.google.common.base.MoreObjects.ToStringHelper; |
| 23 | |
| 24 | /** |
| 25 | * Helper to print byte[] length and hashCode. |
| 26 | */ |
| 27 | public final class ByteArraySizeHashPrinter { |
| 28 | |
| 29 | private final byte[] bytes; |
| 30 | |
| 31 | /** |
| 32 | * Returns ByteArraySizeHashPrinter wrapping given byte[]. |
| 33 | * |
| 34 | * @param bytes bytes to wrap around |
| 35 | * @return ByteArraySizeHashPrinter |
| 36 | */ |
| 37 | public static ByteArraySizeHashPrinter of(byte[] bytes) { |
| 38 | return new ByteArraySizeHashPrinter(bytes); |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Returns ByteArraySizeHashPrinter wrapping given byte[]. |
| 43 | * |
| 44 | * @param bytes bytes to wrap around |
| 45 | * @return null if {@code bytes == null}, ByteArraySizeHashPrinter otherwise |
| 46 | */ |
| 47 | public static ByteArraySizeHashPrinter orNull(byte[] bytes) { |
| 48 | if (bytes == null) { |
| 49 | return null; |
| 50 | } |
| 51 | return new ByteArraySizeHashPrinter(bytes); |
| 52 | } |
| 53 | |
| 54 | public ByteArraySizeHashPrinter(byte[] bytes) { |
| 55 | this.bytes = bytes; |
| 56 | } |
| 57 | |
| 58 | @Override |
| 59 | public String toString() { |
| 60 | ToStringHelper helper = MoreObjects.toStringHelper("byte[]"); |
| 61 | if (bytes != null) { |
| 62 | helper.add("length", bytes.length) |
| 63 | .add("hash", Arrays.hashCode(bytes)); |
| 64 | } else { |
| 65 | helper.addValue(bytes); |
| 66 | } |
| 67 | return helper.toString(); |
| 68 | } |
| 69 | } |