summaryrefslogtreecommitdiff
path: root/common/tests/unit/src/com/android/net/module/util/async/CircularByteBufferTest.java
blob: 01abee2b4a37ad6a8592a4688bc191d1ec0d90bd (plain)
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
/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.net.module.util.async;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.fail;

import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;

import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(AndroidJUnit4.class)
@SmallTest
public class CircularByteBufferTest {
    @Test
    public void writeBytes() {
        final int capacity = 23;
        CircularByteBuffer buffer = new CircularByteBuffer(capacity);
        assertEquals(0, buffer.size());
        assertEquals(0, buffer.getDirectReadSize());
        assertEquals(capacity, buffer.freeSize());
        assertEquals(capacity, buffer.getDirectWriteSize());

        final byte[] writeBuffer = new byte[15];
        buffer.writeBytes(writeBuffer, 0, writeBuffer.length);

        assertEquals(writeBuffer.length, buffer.size());
        assertEquals(writeBuffer.length, buffer.getDirectReadSize());
        assertEquals(capacity - writeBuffer.length, buffer.freeSize());
        assertEquals(capacity - writeBuffer.length, buffer.getDirectWriteSize());

        buffer.clear();
        assertEquals(0, buffer.size());
        assertEquals(0, buffer.getDirectReadSize());
        assertEquals(capacity, buffer.freeSize());
        assertEquals(capacity, buffer.getDirectWriteSize());
    }

    @Test
    public void writeBytes_withRollover() {
        doTestReadWriteWithRollover(new BufferAccessor(false, false));
    }

    @Test
    public void writeBytes_withFullBuffer() {
        doTestReadWriteWithFullBuffer(new BufferAccessor(false, false));
    }

    @Test
    public void directWriteBytes_withRollover() {
        doTestReadWriteWithRollover(new BufferAccessor(true, true));
    }

    @Test
    public void directWriteBytes_withFullBuffer() {
        doTestReadWriteWithFullBuffer(new BufferAccessor(true, true));
    }

    private void doTestReadWriteWithFullBuffer(BufferAccessor accessor) {
        CircularByteBuffer buffer = doTestReadWrite(accessor, 20, 5, 4);

        assertEquals(0, buffer.size());
        assertEquals(20, buffer.freeSize());
    }

    private void doTestReadWriteWithRollover(BufferAccessor accessor) {
        // All buffer sizes are prime numbers to ensure that some read or write
        // operations will roll over the end of the internal buffer.
        CircularByteBuffer buffer = doTestReadWrite(accessor, 31, 13, 7);

        assertNotEquals(0, buffer.size());
    }

    private CircularByteBuffer doTestReadWrite(BufferAccessor accessor,
            final int capacity, final int writeLen, final int readLen) {
        CircularByteBuffer buffer = new CircularByteBuffer(capacity);

        final byte[] writeBuffer = new byte[writeLen + 2];
        final byte[] peekBuffer = new byte[readLen + 2];
        final byte[] readBuffer = new byte[readLen + 2];

        final int numIterations = 1011;
        final int maxRemaining = readLen - 1;

        int currentWriteSymbol = 0;
        int expectedReadSymbol = 0;
        int expectedSize = 0;
        int totalWritten = 0;
        int totalRead = 0;

        for (int i = 0; i < numIterations; i++) {
            // Fill in with write buffers as much as possible.
            while (buffer.freeSize() >= writeLen) {
                currentWriteSymbol = fillTestBytes(writeBuffer, 1, writeLen, currentWriteSymbol);
                accessor.writeBytes(buffer, writeBuffer, 1, writeLen);

                expectedSize += writeLen;
                totalWritten += writeLen;
                assertEquals(expectedSize, buffer.size());
                assertEquals(capacity - expectedSize, buffer.freeSize());
            }

            // Keep reading into read buffers while there's still data.
            while (buffer.size() >= readLen) {
                peekBuffer[1] = 0;
                peekBuffer[2] = 0;
                buffer.peekBytes(2, peekBuffer, 3, readLen - 2);
                assertEquals(0, peekBuffer[1]);
                assertEquals(0, peekBuffer[2]);

                peekBuffer[2] = buffer.peek(1);

                accessor.readBytes(buffer, readBuffer, 1, readLen);
                peekBuffer[1] = readBuffer[1];

                expectedReadSymbol = checkTestBytes(
                    readBuffer, 1, readLen, expectedReadSymbol, totalRead);

                assertArrayEquals(peekBuffer, readBuffer);

                expectedSize -= readLen;
                totalRead += readLen;
                assertEquals(expectedSize, buffer.size());
                assertEquals(capacity - expectedSize, buffer.freeSize());
            }

            if (buffer.size() > maxRemaining) {
                fail("Too much data remaining: " + buffer.size());
            }
        }

        final int maxWritten = capacity * numIterations;
        final int minWritten = maxWritten / 2;
        if (totalWritten < minWritten || totalWritten > maxWritten
                || (totalWritten - totalRead) > maxRemaining) {
            fail("Unexpected counts: read=" + totalRead + ", written=" + totalWritten
                    + ", minWritten=" + minWritten + ", maxWritten=" + maxWritten);
        }

        return buffer;
    }

    @Test
    public void readBytes_overflow() {
        CircularByteBuffer buffer = new CircularByteBuffer(23);

        final byte[] dataBuffer = new byte[15];
        buffer.writeBytes(dataBuffer, 0, dataBuffer.length - 2);

        try {
            buffer.readBytes(dataBuffer, 0, dataBuffer.length);
            assertTrue(false);
        } catch (IllegalArgumentException e) {
            // expected
        }

        assertEquals(13, buffer.size());
        assertEquals(10, buffer.freeSize());
    }

    @Test
    public void writeBytes_overflow() {
        CircularByteBuffer buffer = new CircularByteBuffer(23);

        final byte[] dataBuffer = new byte[15];
        buffer.writeBytes(dataBuffer, 0, dataBuffer.length);

        try {
            buffer.writeBytes(dataBuffer, 0, dataBuffer.length);
            assertTrue(false);
        } catch (IllegalArgumentException e) {
            // expected
        }

        assertEquals(15, buffer.size());
        assertEquals(8, buffer.freeSize());
    }

    private static int fillTestBytes(byte[] buffer, int pos, int len, int startValue) {
        for (int i = 0; i < len; i++) {
            buffer[pos + i] = (byte) (startValue & 0xFF);
            startValue = (startValue + 1) % 256;
        }
        return startValue;
    }

    private static int checkTestBytes(
            byte[] buffer, int pos, int len, int startValue, int totalRead) {
        for (int i = 0; i < len; i++) {
            byte expectedValue = (byte) (startValue & 0xFF);
            if (expectedValue != buffer[pos + i]) {
                fail("Unexpected byte=" + (((int) buffer[pos + i]) & 0xFF)
                        + ", expected=" + (((int) expectedValue) & 0xFF)
                        + ", pos=" + (totalRead + i));
            }
            startValue = (startValue + 1) % 256;
        }
        return startValue;
    }

    private static final class BufferAccessor {
        private final boolean mDirectRead;
        private final boolean mDirectWrite;

        BufferAccessor(boolean directRead, boolean directWrite) {
            mDirectRead = directRead;
            mDirectWrite = directWrite;
        }

        void writeBytes(CircularByteBuffer buffer, byte[] src, int pos, int len) {
            if (mDirectWrite) {
                while (len > 0) {
                    if (buffer.getDirectWriteSize() == 0) {
                        fail("Direct write size is zero: free=" + buffer.freeSize()
                                + ", size=" + buffer.size());
                    }
                    int copyLen = Math.min(len, buffer.getDirectWriteSize());
                    System.arraycopy(src, pos, buffer.getDirectWriteBuffer(),
                        buffer.getDirectWritePos(), copyLen);
                    buffer.accountForDirectWrite(copyLen);
                    len -= copyLen;
                    pos += copyLen;
                }
            } else {
                buffer.writeBytes(src, pos, len);
            }
        }

        void readBytes(CircularByteBuffer buffer, byte[] dst, int pos, int len) {
            if (mDirectRead) {
                while (len > 0) {
                    if (buffer.getDirectReadSize() == 0) {
                        fail("Direct read size is zero: free=" + buffer.freeSize()
                                + ", size=" + buffer.size());
                    }
                    int copyLen = Math.min(len, buffer.getDirectReadSize());
                    System.arraycopy(
                        buffer.getDirectReadBuffer(), buffer.getDirectReadPos(), dst, pos, copyLen);
                    buffer.accountForDirectRead(copyLen);
                    len -= copyLen;
                    pos += copyLen;
                }
            } else {
                buffer.readBytes(dst, pos, len);
            }
        }
    }
}