Skip to content

Instantly share code, notes, and snippets.

@SocraticPhoenix
Created October 26, 2017 19:08
Show Gist options
  • Save SocraticPhoenix/e28a3769cb988ab1e3c6b3827624f505 to your computer and use it in GitHub Desktop.
Save SocraticPhoenix/e28a3769cb988ab1e3c6b3827624f505 to your computer and use it in GitHub Desktop.
package com.gmail.socraticphoenix.bill;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.zip.Deflater;
public class TioFormatter {
public static final Deflater DEFLATER = new Deflater();
private URL url;
public TioFormatter() {
try {
this.url = new URL("https://tio.run/cgi-bin/run/api/");
} catch (MalformedURLException e) {
throw new IllegalStateException(e);
}
}
private String lang;
private String code;
private String input;
private String[] compFlags;
private String[] cmdOpts;
private String[] args;
public TioFormatter setLang(String lang) {
this.lang = lang;
return this;
}
public TioFormatter setCode(String code) {
this.code = code;
return this;
}
public TioFormatter setInput(String input) {
this.input = input;
return this;
}
public TioFormatter setCompFlags(String... compFlags) {
this.compFlags = compFlags;
return this;
}
public TioFormatter setCmdOpts(String... cmdOpts) {
this.cmdOpts = cmdOpts;
return this;
}
public TioFormatter setArgs(String... args) {
this.args = args;
return this;
}
public byte[] format() {
ByteArrayOutputStream cache = new ByteArrayOutputStream();
try {
writeVariable(cache, "lang", this.lang);
writeVariable(cache, "args", this.args);
writeVariable(cache, "TIO_CFLAGS", this.compFlags);
writeVariable(cache, "TIO_OPTIONS", this.cmdOpts);
writeFile(cache, ".code.tio", this.code.getBytes(StandardCharsets.UTF_8));
writeFile(cache, ".input.tio", this.code.getBytes(StandardCharsets.UTF_8));
return cache.toByteArray();
} catch (IOException e) {
throw new IllegalStateException("ByteArrayOutputStream threw IOException", e);
}
}
private void writeVariable(ByteArrayOutputStream cache, String name, String... values) throws IOException {
if (values.length > 0) {
cache.write(("V" + name).getBytes(StandardCharsets.UTF_8));
cache.write(0);
cache.write(values.length);
for (String v : values) {
cache.write(v.getBytes(StandardCharsets.UTF_8));
cache.write(0);
}
}
}
private void writeFile(ByteArrayOutputStream cache, String name, byte[] file) throws IOException {
cache.write(("F" + name).getBytes(StandardCharsets.UTF_8));
cache.write(0);
cache.write(file.length);
cache.write(file);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment