better API (#4810)

This commit is contained in:
Timbelom 2022-11-20 19:52:02 -08:00 committed by GitHub
parent 555303cf33
commit 3a6fe88db1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 76 additions and 1 deletions

View File

@ -0,0 +1,52 @@
package com.rusefi.stream;
import java.io.IOException;
import java.io.OutputStream;
public class LogicdataOutputStream {
private final OutputStream outputStream;
public LogicdataOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
// This is the main secret of this format! :)
public void writeVarLength(long value) throws IOException {
if (value < 0 || value > 0xFFFFFFFFL) {
writeAs(value, 8);
} else if (value == 0) {
writeByte(0);
} else if (value <= 0xff) {
writeAs(value, 1);
} else if (value <= 0xffff) {
writeAs(value, 2);
} else if (value <= 0xffffff) {
writeAs(value, 3);
} else {
writeAs(value, 4);
}
}
private void writeAs(long value, int numBytes) throws IOException {
if (value == 0) {
writeByte(0);
} else {
writeByte(numBytes);
for (int i = 0; i < numBytes; i++) {
writeByte((byte)((value >> (i * 8)) & 0xff));
}
}
}
public void close() throws IOException {
outputStream.close();
}
public void flush() throws IOException {
outputStream.flush();
}
public void writeByte(int i) throws IOException {
outputStream.write(i);
}
}

View File

@ -85,7 +85,7 @@ public class LogicdataStreamFile extends StreamFile {
// we need at least 2 records
if (events == null || events.size() < 2)
return;
long firstRecordTs = events.get(1).getTimestamp();
long firstRecordTs = events.get(1).getTimestamp(); // huh why not index '0'?
long lastRecordTs = events.get(events.size() - 1).getTimestamp();
// we don't know the total duration, so we create a margin after the last record which equals to the duration of the first event
// TODO: why do we jump from timestamps to samples?

View File

@ -6,6 +6,7 @@ import java.io.*;
import java.util.List;
public abstract class StreamFile {
// todo: always write into Writer since it has better API, it's insane to have to references into same stream
protected OutputStream stream;
protected Writer writer;

View File

@ -0,0 +1,22 @@
package com.rusefi.stream;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public class LogicdataStreamFileTest {
@Test
public void testWriteAs() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
LogicdataOutputStream logicdataOutputStream = new LogicdataOutputStream(baos);
logicdataOutputStream.writeVarLength(10);
byte[] bytes = baos.toByteArray();
assertEquals(2, bytes.length);
assertEquals(1, bytes[0]);
assertEquals(10, bytes[1]);
}
}