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 com.google.common.annotations.Beta;
13 import org.eclipse.jdt.annotation.NonNull;
16 * IPv4 address parsing for ietf-inet-types ipv4-address. This is an internal implementation class, not meant to be
17 * exposed in any shape or form to the outside world, as the code relies on the fact that the strings presented to it
18 * have been previously validated to conform to the regular expressions defined in the YANG model.
21 public final class Ipv4Utils {
22 static final int INET4_LENGTH = 4;
28 static void fillIpv4Bytes(final byte @NonNull[] bytes, final int byteStart, final String str, final int strStart,
32 for (int i = strStart; i < strLimit; ++i) {
33 final char c = str.charAt(i);
35 bytes[out++] = (byte) val;
38 val = 10 * val + c - '0';
42 bytes[out] = (byte) val;
45 public static int addressBits(final String str, final int limit) {
48 for (int i = 0; i < limit; ++i) {
49 final char c = str.charAt(i);
51 prev = prev << 8 | current;
54 current = 10 * current + c - '0';
57 return prev << 8 | current;
60 public static byte @NonNull[] addressBytes(final String str, final int limit) {
61 final byte[] bytes = new byte[4];
62 Ipv4Utils.fillIpv4Bytes(bytes, 0, str, 0, limit);
66 public static String addressString(final int bits) {
67 return (bits >>> 24) + "." + (bits >>> 16 & 0xFF) + "." + (bits >>> 8 & 0xFF) + "." + (bits & 0xFF);
70 public static String addressString(final byte @NonNull[] bytes) {
71 final StringBuilder sb = new StringBuilder(15);
72 appendIpv4String(sb, bytes);
76 static void appendIpv4String(final StringBuilder sb, final byte @NonNull[] bytes) {
77 checkArgument(bytes.length == INET4_LENGTH, "IPv4 address length is 4 bytes");
79 sb.append(Byte.toUnsignedInt(bytes[0]));
80 for (int i = 1; i < INET4_LENGTH; ++i) {
81 sb.append('.').append(Byte.toUnsignedInt(bytes[i]));