|
5 | 5 |
|
6 | 6 | /*
|
7 | 7 | * Copyright (C) 2008 The Guava Authors
|
| 8 | + * Copyright (C) 2024 National Library of Australia and the jwarc contributors |
8 | 9 | *
|
9 | 10 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
|
10 | 11 | * in compliance with the License. You may obtain a copy of the License at
|
|
19 | 20 |
|
20 | 21 | package org.netpreserve.jwarc;
|
21 | 22 |
|
| 23 | +import java.net.Inet6Address; |
22 | 24 | import java.net.InetAddress;
|
23 | 25 | import java.net.UnknownHostException;
|
24 | 26 | import java.nio.ByteBuffer;
|
@@ -224,4 +226,40 @@ private static IllegalArgumentException formatIllegalArgumentException(
|
224 | 226 | String format, Object... args) {
|
225 | 227 | return new IllegalArgumentException(String.format(Locale.ROOT, format, args));
|
226 | 228 | }
|
| 229 | + |
| 230 | + /** |
| 231 | + * Formats an IPv6 address as the RFC5952 canonical textual representation. |
| 232 | + */ |
| 233 | + static String canonicalInet6(Inet6Address address) { |
| 234 | + byte[] bytes = address.getAddress(); |
| 235 | + StringBuilder full = new StringBuilder(); |
| 236 | + for (int i = 0; i < bytes.length; i += 2) { |
| 237 | + if (i > 0) full.append(':'); |
| 238 | + int group = ((bytes[i] & 0xFF) << 8) | (bytes[i + 1] & 0xFF); |
| 239 | + full.append(Integer.toHexString(group)); |
| 240 | + } |
| 241 | + |
| 242 | + // Compress longest zero sequence |
| 243 | + int lengthOfLongestZeroSequence = 2; |
| 244 | + int startOfLongestZeroSequence = 0; |
| 245 | + for (int i = 0; i < full.length(); i++) { |
| 246 | + if (i > 0 && full.charAt(i) != ':') continue; |
| 247 | + |
| 248 | + // Find the end of the zero sequence |
| 249 | + int j; |
| 250 | + for (j = i; j < full.length(); j++) { |
| 251 | + char c = full.charAt(j); |
| 252 | + if (c != ':' && c != '0') break; |
| 253 | + } |
| 254 | + |
| 255 | + int length = j - i; |
| 256 | + if (length > lengthOfLongestZeroSequence) { |
| 257 | + startOfLongestZeroSequence = i; |
| 258 | + lengthOfLongestZeroSequence = length; |
| 259 | + } |
| 260 | + } |
| 261 | + if (lengthOfLongestZeroSequence <= 2) return full.toString(); |
| 262 | + return full.substring(0, startOfLongestZeroSequence) + "::" + |
| 263 | + full.substring(startOfLongestZeroSequence + lengthOfLongestZeroSequence); |
| 264 | + } |
227 | 265 | }
|
0 commit comments