File: S.java

package info (click to toggle)
openjdk-11 11.0.22%2B7-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 781,236 kB
  • sloc: java: 5,174,754; xml: 1,192,262; cpp: 1,133,036; ansic: 461,316; javascript: 162,554; sh: 16,859; objc: 13,683; python: 4,753; asm: 3,570; makefile: 2,894; perl: 357; awk: 351; sed: 172; jsp: 24; csh: 3
file content (277 lines) | stat: -rw-r--r-- 9,531 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/*
 * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.Flow.Publisher;
import java.util.concurrent.Flow.Subscriber;
import java.util.concurrent.Flow.Subscription;
import java.util.stream.Stream;

/*
 * S for Support.
 *
 * Auxiliary methods for tests that check conformance with reactive streams
 * specification.
 *
 * Short name is for the sake of convenience calling this class' static methods.
 * It could've been called Support or TckSupport, but then we would need to
 * place this class in its own package so as to use "import static".
 */
public class S {

    private static final Random RANDOM = new SecureRandom();

    private S() { }

    public static List<ByteBuffer> listOfBuffersFromBufferOfNBytes(int nBytes) {
        return scatterBuffer(bufferOfNRandomBytes(nBytes));
    }

    /*
     * Spreads the remaining contents of the given byte buffer across a number
     * of buffers put into a list.
     */
    public static List<ByteBuffer> scatterBuffer(ByteBuffer src) {
        List<ByteBuffer> buffers = new ArrayList<>();
        while (src.hasRemaining()) {
            // We do not allow empty buffers ~~~~~~~~~~~~~~~~v
            int capacity = RANDOM.nextInt(src.remaining()) + 1;
            ByteBuffer b = ByteBuffer.allocate(capacity);
            for (int i = 0; i < capacity; i++) {
                b.put(src.get());
            }
            b.flip();
            buffers.add(b);
        }
        return List.copyOf(buffers);
    }

    public static ByteBuffer bufferOfNRandomBytes(int capacity) {
        return ByteBuffer.wrap(arrayOfNRandomBytes(capacity));
    }

    public static byte[] arrayOfNRandomBytes(int nBytes) {
        byte[] contents = new byte[nBytes];
        RANDOM.nextBytes(contents);
        return contents;
    }

    public static InputStream inputStreamOfNReads(long n) {
        return new NReadsInputStream(n);
    }

    /*
     * Convenience method for testing publishers.
     */
    public static byte[] arrayOfNRandomBytes(long nBytes) {
        return arrayOfNRandomBytes((int) nBytes);
    }

    public static ByteBuffer bufferOfNRandomASCIIBytes(int capacity) {
        String alphaNumeric = "abcdefghijklmnopqrstuvwxyz1234567890";
        StringBuilder builder = new StringBuilder(capacity);
        for (int i = 0; i < capacity; i++) {
            int idx = RANDOM.nextInt(alphaNumeric.length());
            builder.append(alphaNumeric.charAt(idx));
        }
        return ByteBuffer.wrap(builder.toString().getBytes(
                StandardCharsets.US_ASCII));
    }

    /*
     * Returns a simple non-compliant Subscriber.
     *
     * This Subscriber is useful for testing our adaptors and wrappers, to make
     * sure they do not delegate RS compliance to the underlying (and foreign to
     * java.net.http codebase) Subscribers, but rather comply themselves.
     *
     * Here's an example:
     *
     *     public void onSubscribe(Subscription s) {
     *         delegate.onSubscribe(s);
     *     }
     *
     * The snippet above cannot be considered a good implementation of a
     * Subscriber if `delegate` is an unknown Subscriber. In this case the
     * implementation should independently check all the rules from the RS spec
     * related to subscribers.
     */
    public static <T> Subscriber<T> nonCompliantSubscriber() {
        return new Subscriber<>() {

            @Override
            public void onSubscribe(Subscription subscription) {
                subscription.request(Long.MAX_VALUE);
            }

            @Override
            public void onNext(T item) { }

            @Override
            public void onError(Throwable throwable) { }

            @Override
            public void onComplete() { }
        };
    }

    public static int randomIntUpTo(int bound) {
        return RANDOM.nextInt(bound);
    }

    /*
     * Signals an error to its subscribers immediately after subscription.
     */
    public static <T> Publisher<T> newErroredPublisher() {
        return subscriber -> {
            subscriber.onSubscribe(new Subscription() {
                @Override
                public void request(long n) { }

                @Override
                public void cancel() { }
            });
            subscriber.onError(new IOException());
        };
    }

    /*
     * Publishes the elements obtained from the stream and signals completion.
     * Can be cancelled, but cannot signal an error.
     *
     * This trivial ad-hoc implementation of Publisher was created so as to
     * publish lists of byte buffers. We can publish ByteBuffer, but we can't
     * seem to publish List<ByteBuffer> since there's no readily available
     * publisher of those, nor there's a simple adaptor.
     */
    public static <T> Publisher<T> publisherOfStream(Stream<? extends T> stream)
    {
        if (stream == null) {
            throw new NullPointerException();
        }
        return new Publisher<T>() {
            @Override
            public void subscribe(Subscriber<? super T> subscriber) {
                if (subscriber == null) {
                    throw new NullPointerException();
                }
                Subscription subscription = new Subscription() {

                    boolean inOnNext; // recursion control
                    volatile boolean cancelled;
                    long demand;
                    final Iterator<? extends T> supply = stream.iterator();

                    @Override
                    public void request(long n) {
                        demand = demand + n < 0 ? Long.MAX_VALUE : demand + n;
                        if (inOnNext) {
                            return;
                        }
                        if (cancelled)
                            return;
                        if (n <= 0) {
                            cancelled = true;
                            subscriber.onError(new IllegalArgumentException(
                                    "non-positive subscription request"));
                            return;
                        }
                        while (supply.hasNext() && demand > 0 && !cancelled) {
                            demand--;
                            inOnNext = true;
                            try {
                                T item = supply.next();
                                subscriber.onNext(item);
                            } finally {
                                inOnNext = false;
                            }
                        }
                        if (!supply.hasNext()) {
                            cancelled = true;
                            subscriber.onComplete();
                        }
                    }

                    @Override
                    public void cancel() {
                        cancelled = true;
                    }
                };
                subscriber.onSubscribe(subscription);
            }
        };
    }

    static final class NReadsInputStream extends InputStream {

        private static final int EOF = -1;
        private long readsLeft;

        NReadsInputStream(long n) {
            if (n < 0) {
                throw new IllegalArgumentException(String.valueOf(n));
            }
            this.readsLeft = n;
        }

        @Override
        public int read() {
            if (readsLeft == 0L) {
                return EOF;
            }
            readsLeft--;
            return S.randomIntUpTo(256);
        }

        @Override
        public int read(byte[] b, int off, int len) {
            Objects.checkFromIndexSize(off, len, b.length);
            // Must return 0 if len == 0,
            // even if there are no more reads left
            if (len == 0) {
                return 0;
            }
            if (readsLeft == 0L) {
                return EOF;
            }
            readsLeft--;
            // At least one byte MUST be read, but we can read
            // less than `len` bytes
            int r = RANDOM.nextInt(len) + 1;
            for (int i = 0; i < r; i++) {
                b[i] = (byte) randomIntUpTo(256);
            }
            return r;
        }
    }
}