View Javadoc
1   /*
2    * Copyright (C) 2021, Thomas Wolf <thomas.wolf@paranor.ch> and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  package org.eclipse.jgit.util;
11  
12  import static org.junit.Assert.assertArrayEquals;
13  import static org.junit.Assert.assertEquals;
14  
15  import java.io.ByteArrayInputStream;
16  import java.io.IOException;
17  import java.io.InputStream;
18  import java.nio.charset.StandardCharsets;
19  import java.util.Arrays;
20  
21  import org.junit.Test;
22  
23  public class IOTest {
24  
25  	private static final byte[] DATA = "abcdefghijklmnopqrstuvwxyz"
26  			.getBytes(StandardCharsets.US_ASCII);
27  
28  	private byte[] initBuffer(int size) {
29  		byte[] buffer = new byte[size];
30  		for (int i = 0; i < size; i++) {
31  			buffer[i] = (byte) ('0' + (i % 10));
32  		}
33  		return buffer;
34  	}
35  
36  	private int read(byte[] buffer, int from) throws IOException {
37  		try (InputStream in = new ByteArrayInputStream(DATA)) {
38  			return IO.readFully(in, buffer, from);
39  		}
40  	}
41  
42  	@Test
43  	public void readFullyBufferShorter() throws Exception {
44  		byte[] buffer = initBuffer(9);
45  		int length = read(buffer, 0);
46  		assertEquals(buffer.length, length);
47  		assertArrayEquals(buffer, Arrays.copyOfRange(DATA, 0, length));
48  	}
49  
50  	@Test
51  	public void readFullyBufferLonger() throws Exception {
52  		byte[] buffer = initBuffer(50);
53  		byte[] initial = Arrays.copyOf(buffer, buffer.length);
54  		int length = read(buffer, 0);
55  		assertEquals(DATA.length, length);
56  		assertArrayEquals(Arrays.copyOfRange(buffer, 0, length), DATA);
57  		assertArrayEquals(Arrays.copyOfRange(buffer, length, buffer.length),
58  				Arrays.copyOfRange(initial, length, initial.length));
59  	}
60  
61  	@Test
62  	public void readFullyBufferShorterOffset() throws Exception {
63  		byte[] buffer = initBuffer(9);
64  		byte[] initial = Arrays.copyOf(buffer, buffer.length);
65  		int length = read(buffer, 6);
66  		assertEquals(3, length);
67  		assertArrayEquals(Arrays.copyOfRange(buffer, 0, 6),
68  				Arrays.copyOfRange(initial, 0, 6));
69  		assertArrayEquals(Arrays.copyOfRange(buffer, 6, buffer.length),
70  				Arrays.copyOfRange(DATA, 0, 3));
71  	}
72  
73  	@Test
74  	public void readFullyBufferLongerOffset() throws Exception {
75  		byte[] buffer = initBuffer(50);
76  		byte[] initial = Arrays.copyOf(buffer, buffer.length);
77  		int length = read(buffer, 40);
78  		assertEquals(10, length);
79  		assertArrayEquals(Arrays.copyOfRange(buffer, 0, 40),
80  				Arrays.copyOfRange(initial, 0, 40));
81  		assertArrayEquals(Arrays.copyOfRange(buffer, 40, buffer.length),
82  				Arrays.copyOfRange(DATA, 0, 10));
83  	}
84  }