blob: 4ec9ce17305dc6349f75d6aa17367a60e070164a [file] [log] [blame]
package com.example.g8backend.util;
import com.example.g8backend.dto.AnnounceResponseDTO;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class BencodeUtil {
public static byte[] encodeAnnounceResponse(AnnounceResponseDTO dto) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
out.write('d'); // dictionary start
writeString(out, "interval");
writeInt(out, dto.getInterval());
writeString(out, "peers");
out.write('l'); // list start
for (Map<String, Object> peer : dto.getPeers()) {
out.write('d');
writeString(out, "ip");
writeString(out, (String) peer.get("ip"));
writeString(out, "port");
writeInt(out, ((Number) peer.get("port")).intValue());
out.write('e');
}
out.write('e'); // list end
out.write('e'); // dictionary end
} catch (Exception e) {
throw new RuntimeException("Bencoding failed", e);
}
return out.toByteArray();
}
private static void writeString(ByteArrayOutputStream out, String str) throws Exception {
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
out.write(String.valueOf(bytes.length).getBytes(StandardCharsets.UTF_8));
out.write(':');
out.write(bytes);
}
private static void writeInt(ByteArrayOutputStream out, int i) throws Exception {
out.write('i');
out.write(String.valueOf(i).getBytes(StandardCharsets.UTF_8));
out.write('e');
}
}