View Javadoc
1   /*
2    * Copyright 2015 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  
17  package io.netty5.resolver.dns;
18  
19  import java.net.InetSocketAddress;
20  import java.util.Collection;
21  import java.util.List;
22  
23  final class SequentialDnsServerAddressStream implements DnsServerAddressStream {
24  
25      private final List<? extends InetSocketAddress> addresses;
26      private int i;
27  
28      SequentialDnsServerAddressStream(List<? extends InetSocketAddress> addresses, int startIdx) {
29          this.addresses = addresses;
30          i = startIdx;
31      }
32  
33      @Override
34      public InetSocketAddress next() {
35          int i = this.i;
36          InetSocketAddress next = addresses.get(i);
37          if (++ i < addresses.size()) {
38              this.i = i;
39          } else {
40              this.i = 0;
41          }
42          return next;
43      }
44  
45      @Override
46      public int size() {
47          return addresses.size();
48      }
49  
50      @Override
51      public SequentialDnsServerAddressStream duplicate() {
52          return new SequentialDnsServerAddressStream(addresses, i);
53      }
54  
55      @Override
56      public String toString() {
57          return toString("sequential", i, addresses);
58      }
59  
60      static String toString(String type, int index, Collection<? extends InetSocketAddress> addresses) {
61          final StringBuilder buf = new StringBuilder(type.length() + 2 + addresses.size() * 16);
62          buf.append(type).append("(index: ").append(index);
63          buf.append(", addrs: (");
64          for (InetSocketAddress a: addresses) {
65              buf.append(a).append(", ");
66          }
67  
68          buf.setLength(buf.length() - 2);
69          buf.append("))");
70  
71          return buf.toString();
72      }
73  }