Eliminate shift variable
[mdsal.git] / model / ietf / ietf-type-util / src / main / java / org / opendaylight / mdsal / model / ietf / util / Ipv4Utils.java
1 /*
2  * Copyright (c) 2016 Pantheon Technologies s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.model.ietf.util;
9
10 import org.eclipse.jdt.annotation.NonNull;
11
12 /**
13  * IPv4 address parsing for ietf-inet-types ipv4-address. This is an internal implementation class, not meant to be
14  * exposed in any shape or form to the outside world, as the code relies on the fact that the strings presented to it
15  * have been previously validated to conform to the regular expressions defined in the YANG model.
16  */
17 final class Ipv4Utils {
18     private Ipv4Utils() {
19
20     }
21
22     static void fillIpv4Bytes(final byte @NonNull[] bytes, final int byteStart, final String str, final int strStart,
23             final int strLimit) {
24         int out = byteStart;
25         int val = 0;
26         for (int i = strStart; i < strLimit; ++i) {
27             final char c = str.charAt(i);
28             if (c == '.') {
29                 bytes[out++] = (byte) val;
30                 val = 0;
31             } else {
32                 val = 10 * val + c - '0';
33             }
34         }
35
36         bytes[out] = (byte) val;
37     }
38
39     static int addressBits(final String str, final int limit) {
40         int prev = 0;
41         int current = 0;
42         for (int i = 0; i < limit; ++i) {
43             final char c = str.charAt(i);
44             if (c == '.') {
45                 prev = prev << 8 | current;
46                 current = 0;
47             } else {
48                 current = 10 * current + c - '0';
49             }
50         }
51         return prev << 8 | current;
52     }
53
54     static byte @NonNull[] addressBytes(final String str, final int limit) {
55         final byte[] bytes = new byte[4];
56         Ipv4Utils.fillIpv4Bytes(bytes, 0, str, 0, limit);
57         return bytes;
58     }
59
60     static String addressString(final int bits) {
61         return new StringBuilder(15)
62                 .append(bits >>> 24).append('.')
63                 .append(bits >>> 16 & 0xFF).append('.')
64                 .append(bits >>> 8 & 0xFF).append('.')
65                 .append(bits & 0xFF)
66                 .toString();
67     }
68 }