package io.trygvis.rules.network; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; @JsonSerialize(using = Ipv4Cidr.Serializer.class) public class Ipv4Cidr { public final int network; public final int netmask; public final int size; public final int bits; public Ipv4Cidr(int network, int netmask, int size, int bits) { this.network = network; this.netmask = netmask; this.size = size; this.bits = bits; } @Override public String toString() { return "%d.%d.%d.%d/%d".formatted( network >> 24 & 0xff, network >> 16 & 0xff, network >> 8 & 0xff, network & 0xff, bits); } public Collection addresses() { var end = network + size; var addresses = new ArrayList(size); for (int address = network; address < end; address++) { addresses.add(new Ipv4Address(address)); } return addresses; } public static class Serializer extends JsonSerializer { @Override public void serialize(Ipv4Cidr value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeObjectField("value", value.toString()); gen.writeEndObject(); } } }