68 lines
1.9 KiB
C#
68 lines
1.9 KiB
C#
using System;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
using System.Text.Json.Serialization;
|
|
|
|
namespace BCG
|
|
{
|
|
/*
|
|
* PubSubPortRange.cs
|
|
*
|
|
* This class represents a range of ports that could be used by a server.
|
|
* Servers that wish to provide services ask the blue pages for a port they can use,
|
|
* and blue pages replies with a port.
|
|
*
|
|
* */
|
|
[JsonConverter(typeof(PubSubPortRangeJsonConverter))]
|
|
public class PubSubPortRange
|
|
{
|
|
|
|
public PubSubPortRange()
|
|
{
|
|
|
|
}
|
|
|
|
public PubSubPortRange(int min, int max)
|
|
{
|
|
minPort = min;
|
|
maxPort = max;
|
|
|
|
}
|
|
|
|
public int minPort;
|
|
public int maxPort;
|
|
|
|
}
|
|
|
|
public class PubSubPortRangeJsonConverter : JsonConverter<PubSubPortRange> {
|
|
public override PubSubPortRange? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
|
|
var rv = new PubSubPortRange();
|
|
var jsonObj = JsonSerializer.Deserialize<JsonObject>(ref reader, options);
|
|
if (jsonObj is null) {
|
|
return null;
|
|
}
|
|
ReadPrimitive("min_port", ref rv.minPort);
|
|
ReadPrimitive("max_port", ref rv.maxPort);
|
|
return rv;
|
|
|
|
void ReadPrimitive<T>(string key, ref T valueOut) where T : struct {
|
|
if (jsonObj.TryGetPropertyValue(key, out var valueJson)) {
|
|
var valueInt = valueJson?.GetValue<T>();
|
|
// Only (over)write valueOut if non-null
|
|
if (valueInt.HasValue) {
|
|
valueOut = valueInt.Value;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public override void Write(Utf8JsonWriter writer, PubSubPortRange value, JsonSerializerOptions options) {
|
|
var jsonObj = new JsonObject {
|
|
["min_port"] = value.minPort,
|
|
["max_port"] = value.maxPort,
|
|
};
|
|
JsonSerializer.Serialize(writer, jsonObj, options);
|
|
}
|
|
}
|
|
}
|