2 * Copyright (c) 2016 Pantheon Technologies s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.model.ietf.util;
10 import static com.google.common.base.Preconditions.checkArgument;
12 import org.eclipse.jdt.annotation.NonNull;
15 * IPv4 address parsing for {@code ietf-inet-types} ipv4-address. This is an internal implementation class, not meant to
16 * be used directly in any shape or form to the outside world, as the code relies on the fact that the strings presented
17 * to it have been previously validated to conform to the regular expressions defined in the YANG model.
19 public final class Ipv4Utils {
20 public static final int INET4_LENGTH = 4;
26 public static void fillIpv4Bytes(final byte @NonNull[] bytes, final int byteStart, final String str,
27 final int strStart, final int strLimit) {
30 for (int i = strStart; i < strLimit; ++i) {
31 final char c = str.charAt(i);
33 bytes[out++] = (byte) val;
36 val = 10 * val + c - '0';
40 bytes[out] = (byte) val;
43 public static int addressBits(final String str, final int limit) {
46 for (int i = 0; i < limit; ++i) {
47 final char c = str.charAt(i);
49 prev = prev << 8 | current;
52 current = 10 * current + c - '0';
55 return prev << 8 | current;
58 public static byte @NonNull[] addressBytes(final String str, final int limit) {
59 final byte[] bytes = new byte[4];
60 Ipv4Utils.fillIpv4Bytes(bytes, 0, str, 0, limit);
64 public static String addressString(final int bits) {
65 return (bits >>> 24) + "." + (bits >>> 16 & 0xFF) + "." + (bits >>> 8 & 0xFF) + "." + (bits & 0xFF);
68 public static String addressString(final byte @NonNull[] bytes) {
69 final StringBuilder sb = new StringBuilder(15);
70 appendIpv4String(sb, bytes);
74 public static void appendIpv4String(final StringBuilder sb, final byte @NonNull[] bytes) {
75 checkArgument(bytes.length == INET4_LENGTH, "IPv4 address length is 4 bytes");
77 sb.append(Byte.toUnsignedInt(bytes[0]));
78 for (int i = 1; i < INET4_LENGTH; ++i) {
79 sb.append('.').append(Byte.toUnsignedInt(bytes[i]));