01 /*
02 *
03 * Licensed to the Apache Software Foundation (ASF) under one
04 * or more contributor license agreements. See the NOTICE file
05 * distributed with this work for additional information
06 * regarding copyright ownership. The ASF licenses this file
07 * to you under the Apache License, Version 2.0 (the
08 * "License"); you may not use this file except in compliance
09 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 */
21 package org.apache.qpid.transport.util;
22
23 import java.nio.ByteBuffer;
24
25 import static java.lang.Math.*;
26
27
28 /**
29 * Functions
30 *
31 * @author Rafael H. Schloming
32 */
33
34 public class Functions
35 {
36
37 public static final int mod(int n, int m)
38 {
39 int r = n % m;
40 return r < 0 ? m + r : r;
41 }
42
43 public static final byte lsb(int i)
44 {
45 return (byte) (0xFF & i);
46 }
47
48 public static final byte lsb(long l)
49 {
50 return (byte) (0xFF & l);
51 }
52
53 public static final String str(ByteBuffer buf)
54 {
55 return str(buf, buf.remaining());
56 }
57
58 public static final String str(ByteBuffer buf, int limit)
59 {
60 StringBuilder str = new StringBuilder();
61 str.append('"');
62
63 for (int i = 0; i < min(buf.remaining(), limit); i++)
64 {
65 byte c = buf.get(buf.position() + i);
66
67 if (c > 31 && c < 127 && c != '\\')
68 {
69 str.append((char)c);
70 }
71 else
72 {
73 str.append(String.format("\\x%02x", c));
74 }
75 }
76
77 str.append('"');
78
79 if (limit < buf.remaining())
80 {
81 str.append("...");
82 }
83
84 return str.toString();
85 }
86
87 public static final String str(byte[] bytes)
88 {
89 return str(ByteBuffer.wrap(bytes));
90 }
91
92 public static final String str(byte[] bytes, int limit)
93 {
94 return str(ByteBuffer.wrap(bytes), limit);
95 }
96
97 }
|