blob: a069125388ff8e9e86ee153b0e3e4f6d8bd85340 [file] [log] [blame]
Yuta HIGUCHI75fb1f42014-11-19 13:56:19 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2014-present Open Networking Foundation
Yuta HIGUCHI75fb1f42014-11-19 13:56:19 -08003 *
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
17package org.onlab.util;
18
19import java.util.Arrays;
20
21import com.google.common.base.MoreObjects;
22import com.google.common.base.MoreObjects.ToStringHelper;
23
24/**
25 * Helper to print byte[] length and hashCode.
26 */
27public 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}