Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serialization test. #18

Merged
merged 1 commit into from
Sep 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@
<configuration>
<source>1.5</source>
<target>1.5</target>
<testSource>1.8</testSource>
<testTarget>1.8</testTarget>
</configuration>
</plugin>
<plugin>
Expand Down
82 changes: 82 additions & 0 deletions src/test/java/com/zaxxer/sparsebits/SerializationTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package com.zaxxer.sparsebits;

import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;

import org.junit.Test;
import static org.junit.Assert.assertEquals;

/**
* Tests serialization of SparseBitSet of different number of set bits,
* from 1 to MAX_BITS.
*/
public class SerializationTest {

private static final Path DST = Paths.get(System.getProperty("java.io.tmpdir"), "sbs.ser");
private static final int MAX_BITS = Integer.parseInt(System.getProperty("test.max_bits", "100"));

private int numOfBits;
private int[] data;
private SparseBitSet sparseBitSet;

@Test
public void testFromOneToNBits() {
IntStream.range(1, MAX_BITS + 1).forEach(this::execute);
}

private void execute(int numOfBits) {
try {
this.numOfBits = numOfBits;
this.sparseBitSet = new SparseBitSet();

createData();
fillSparseBitSet();
write();

this.sparseBitSet = null;
sortData();
read();

verify();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

private void verify() {
for (int i = sparseBitSet.nextSetBit(0), j = 0; i >= 0; i = sparseBitSet.nextSetBit(i + 1), j++) {
assertEquals(data[j], i);
}
}

private void createData() {
Set<Integer> s = new HashSet<>();
Random r = new Random();
while (s.size() < numOfBits) {
s.add(r.nextInt(Integer.MAX_VALUE));
}
data = s.stream().mapToInt(i -> i).toArray();
}

private void sortData() {
Arrays.sort(data);
}

private void fillSparseBitSet() {
IntStream.of(data).forEach(sparseBitSet::set);
}

private void write() throws Exception {
try (ObjectOutputStream s = new ObjectOutputStream(new FileOutputStream(DST.toFile()))) {
s.writeObject(sparseBitSet);
}
}

private void read() throws Exception {
try (ObjectInputStream s = new ObjectInputStream(new FileInputStream(DST.toFile()))) {
sparseBitSet = (SparseBitSet) s.readObject();
}
}
}