Skip to content

Commit ec6de9c

Browse files
authored
Add IPNetwork to cidr mapping (#5889)
Closes #5821
1 parent ea56478 commit ec6de9c

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#if NET8_0_OR_GREATER
2+
3+
using System.Net;
4+
5+
// ReSharper disable once CheckNamespace
6+
namespace Npgsql.Internal.Converters;
7+
8+
sealed class IPNetworkConverter : PgBufferedConverter<IPNetwork>
9+
{
10+
public override bool CanConvert(DataFormat format, out BufferRequirements bufferRequirements)
11+
=> CanConvertBufferedDefault(format, out bufferRequirements);
12+
13+
public override Size GetSize(SizeContext context, IPNetwork value, ref object? writeState)
14+
=> NpgsqlInetConverter.GetSizeImpl(context, value.BaseAddress, ref writeState);
15+
16+
protected override IPNetwork ReadCore(PgReader reader)
17+
{
18+
var (ip, netmask) = NpgsqlInetConverter.ReadImpl(reader, shouldBeCidr: true);
19+
return new(ip, netmask);
20+
}
21+
22+
protected override void WriteCore(PgWriter writer, IPNetwork value)
23+
=> NpgsqlInetConverter.WriteImpl(writer, (value.BaseAddress, (byte)value.PrefixLength), isCidr: true);
24+
}
25+
26+
#endif

src/Npgsql/Internal/ResolverFactories/NetworkTypeInfoResolverFactory.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,11 @@ static TypeInfoMappingCollection AddMappings(TypeInfoMappingCollection mappings)
5151
mappings.AddStructType<NpgsqlCidr>(DataTypeNames.Cidr,
5252
static (options, mapping, _) => mapping.CreateInfo(options, new NpgsqlCidrConverter()), isDefault: true);
5353

54+
#if NET8_0_OR_GREATER
55+
mappings.AddStructType<IPNetwork>(DataTypeNames.Cidr,
56+
static (options, mapping, _) => mapping.CreateInfo(options, new IPNetworkConverter()));
57+
#endif
58+
5459
return mappings;
5560
}
5661
}
@@ -76,6 +81,10 @@ static TypeInfoMappingCollection AddMappings(TypeInfoMappingCollection mappings)
7681
// cidr
7782
mappings.AddStructArrayType<NpgsqlCidr>(DataTypeNames.Cidr);
7883

84+
#if NET8_0_OR_GREATER
85+
mappings.AddStructArrayType<IPNetwork>(DataTypeNames.Cidr);
86+
#endif
87+
7988
return mappings;
8089
}
8190
}

test/Npgsql.Tests/Types/NetworkTypeTests.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,16 @@ public Task Cidr()
6161
NpgsqlDbType.Cidr,
6262
isDefaultForWriting: false);
6363

64+
[Test]
65+
public Task IPNetwork_as_cidr()
66+
=> AssertType(
67+
new IPNetwork(IPAddress.Parse("192.168.1.0"), 24),
68+
"192.168.1.0/24",
69+
"cidr",
70+
NpgsqlDbType.Cidr,
71+
isDefaultForWriting: false,
72+
isDefaultForReading: false);
73+
6474
[Test]
6575
public Task Inet_v4_as_NpgsqlInet()
6676
=> AssertType(

0 commit comments

Comments
 (0)