-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAbstractPolylineEncoder.cs
More file actions
310 lines (251 loc) · 12.6 KB
/
AbstractPolylineEncoder.cs
File metadata and controls
310 lines (251 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
//
// Copyright © Pete Sramek. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace PolylineAlgorithm.Abstraction;
using Microsoft.Extensions.Logging;
using PolylineAlgorithm;
using PolylineAlgorithm.Internal;
using PolylineAlgorithm.Internal.Logging;
using PolylineAlgorithm.Properties;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Provides functionality to encode a collection of geographic coordinates into an encoded polyline string.
/// Implements the <see cref="IPolylineEncoder{TCoordinate, TPolyline}"/> interface.
/// </summary>
/// <remarks>
/// This abstract class serves as a base for specific polyline encoders, allowing customization of the encoding process.
/// </remarks>
public abstract class AbstractPolylineEncoder<TCoordinate, TPolyline> : IPolylineEncoder<TCoordinate, TPolyline>, IAsyncPolylineEncoder<TCoordinate, TPolyline>, IPolylinePipeEncoder<TCoordinate> {
/// <summary>
/// Initializes a new instance of the <see cref="AbstractPolylineEncoder{TCoordinate, TPolyline}"/> class with default encoding options.
/// </summary>
protected AbstractPolylineEncoder()
: this(new PolylineEncodingOptions()) { }
/// <summary>
/// Initializes a new instance of the <see cref="AbstractPolylineEncoder{TCoordinate, TPolyline}"/> class with the specified encoding options.
/// </summary>
/// <param name="options">
/// The <see cref="PolylineEncodingOptions"/> to use for encoding operations.
/// </param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="options"/> is <see langword="null" /></exception>
protected AbstractPolylineEncoder(PolylineEncodingOptions options) {
Options = options ?? throw new ArgumentNullException(nameof(options));
}
/// <summary>
/// Gets the encoding options used by this polyline encoder.
/// </summary>
public PolylineEncodingOptions Options { get; }
/// <summary>
/// Encodes a collection of <typeparamref name="TCoordinate"/> instances into an encoded <typeparamref name="TPolyline"/> string.
/// </summary>
/// <param name="coordinates">
/// The collection of <typeparamref name="TCoordinate"/> objects to encode.
/// </param>
/// <returns>
/// An instance of <typeparamref name="TPolyline"/> representing the encoded coordinates.
/// Returns <see langword="default"/> if the input collection is empty or null.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="coordinates"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="coordinates"/> is an empty enumeration.
/// </exception>
public TPolyline Encode(IEnumerable<TCoordinate> coordinates) {
var logger = Options
.LoggerFactory
.CreateLogger<AbstractPolylineDecoder<TPolyline, TCoordinate>>();
logger
.LogOperationStartedInfo(nameof(Encode));
Debug.Assert(coordinates is not null, "Coordinates cannot be null.");
ValidateNullCoordinates(coordinates, logger);
int count = GetCount(coordinates);
Debug.Assert(count >= 0, "Count must be non-negative.");
ValidateEmptyCoordinates(logger, count);
CoordinateVariance variance = new();
int position = 0;
int consumed = 0;
int length = GetMaxBufferLength(count);
Span<char> buffer = stackalloc char[length];
using var enumerator = coordinates.GetEnumerator();
while (enumerator.MoveNext()) {
variance
.Next(
PolylineEncoding.Normalize(GetLatitude(enumerator.Current), CoordinateValueType.Latitude),
PolylineEncoding.Normalize(GetLongitude(enumerator.Current), CoordinateValueType.Longitude)
);
ValidateBuffer(logger, variance, position, buffer);
if (!PolylineEncoding.TryWriteValue(variance.Latitude, ref buffer, ref position)
|| !PolylineEncoding.TryWriteValue(variance.Longitude, ref buffer, ref position)
) {
// This shouldn't happen, but if it does, log the error and throw an exception.
logger
.LogCannotWriteValueToBufferWarning(position, consumed);
logger
.LogOperationFailedInfo(nameof(Encode));
throw new InvalidOperationException(ExceptionMessageResource.CouldNotWriteEncodedValueToTheBuffer);
}
consumed++;
}
logger
.LogOperationFinishedInfo(nameof(Encode));
return CreatePolyline(buffer[..position].ToString().AsMemory());
static int GetCount(IEnumerable<TCoordinate> coordinates) => coordinates switch {
ICollection collection => collection.Count,
_ => coordinates.Count(),
};
static int GetRequiredLength(CoordinateVariance variance) =>
PolylineEncoding.GetCharCount(variance.Latitude) + PolylineEncoding.GetCharCount(variance.Longitude);
static int GetRemainingBufferSize(int position, int length) {
Debug.Assert(length > 0, "Buffer length must be greater than zero.");
Debug.Assert(position >= 0, "Position must be non-negative.");
Debug.Assert(position < length, "Position must be less than buffer length.");
Debug.Assert(length - position >= 0, "Remaining length must be non-negative.");
return length - position;
}
int GetMaxBufferLength(int count) {
Debug.Assert(count > 0, "Count must be greater than zero.");
int requestedBufferLength = count * Defaults.Polyline.Block.Length.Max;
Debug.Assert(Options.MaxBufferLength > 0, "Max buffer length must be greater than zero.");
Debug.Assert(requestedBufferLength > 0, "Requested buffer length must be greater than zero.");
if (requestedBufferLength > Options.MaxBufferLength) {
logger
.LogRequestedBufferSizeExceedsMaxBufferLengthWarning(requestedBufferLength, Options.MaxBufferLength);
return Options.MaxBufferLength;
}
return requestedBufferLength;
}
static void ValidateNullCoordinates(IEnumerable<TCoordinate> coordinates, ILogger<AbstractPolylineDecoder<TPolyline, TCoordinate>> logger) {
if (coordinates is null) {
logger
.LogNullArgumentWarning(nameof(coordinates));
logger
.LogOperationFailedInfo(nameof(Encode));
throw new ArgumentNullException(nameof(coordinates));
}
}
static void ValidateEmptyCoordinates(ILogger<AbstractPolylineDecoder<TPolyline, TCoordinate>> logger, int count) {
if (count < 1) {
logger
.LogEmptyArgumentWarning(nameof(coordinates));
logger
.LogOperationFailedInfo(nameof(Encode));
throw new ArgumentException(ExceptionMessageResource.ArgumentCannotBeEmptyEnumerationMessage, nameof(coordinates));
}
}
static void ValidateBuffer(ILogger<AbstractPolylineDecoder<TPolyline, TCoordinate>> logger, CoordinateVariance variance, int position, Span<char> buffer) {
if (GetRemainingBufferSize(position, buffer.Length) < GetRequiredLength(variance)) {
logger
.LogInternalBufferOverflowWarning(position, buffer.Length, GetRequiredLength(variance));
logger
.LogOperationFailedInfo(nameof(Encode));
throw new InternalBufferOverflowException();
}
}
}
/// <summary>
/// Creates a polyline instance from the provided read-only sequence of characters.
/// </summary>
/// <param name="polyline">A <see cref="ReadOnlyMemory{T}"/> containing the encoded polyline characters.</param>
/// <returns>
/// An instance of <typeparamref name="TPolyline"/> representing the encoded polyline.
/// </returns>
protected abstract TPolyline CreatePolyline(ReadOnlyMemory<char> polyline);
/// <summary>
/// Extracts the longitude value from the specified coordinate.
/// </summary>
/// <param name="current">The coordinate from which to extract the longitude.</param>
/// <returns>
/// The longitude value as a <see cref="double"/>.
/// </returns>
protected abstract double GetLongitude(TCoordinate current);
/// <summary>
/// Extracts the latitude value from the specified coordinate.
/// </summary>
/// <param name="current">The coordinate from which to extract the latitude.</param>
/// <returns>
/// The latitude value as a <see cref="double"/>.
/// </returns>
protected abstract double GetLatitude(TCoordinate current);
/// <summary>
/// Asynchronously encodes a sequence of geographic coordinates into an encoded polyline by collecting all
/// coordinates from the <see cref="IAsyncEnumerable{T}"/> and then encoding them synchronously.
/// </summary>
/// <param name="coordinates">
/// The asynchronous collection of <typeparamref name="TCoordinate"/> instances to encode.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to observe while collecting coordinates.
/// </param>
/// <returns>
/// A <see cref="ValueTask{TResult}"/> containing the encoded <typeparamref name="TPolyline"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="coordinates"/> is <see langword="null"/>.
/// </exception>
public async ValueTask<TPolyline> EncodeAsync(
IAsyncEnumerable<TCoordinate> coordinates,
CancellationToken cancellationToken) {
if (coordinates is null) {
throw new ArgumentNullException(nameof(coordinates));
}
var list = new List<TCoordinate>();
await foreach (TCoordinate coordinate in coordinates.WithCancellation(cancellationToken).ConfigureAwait(false)) {
list.Add(coordinate);
}
return Encode(list);
}
/// <summary>
/// Asynchronously encodes a sequence of geographic coordinates and writes the encoded polyline bytes directly
/// into <paramref name="writer"/> with zero intermediate allocations.
/// </summary>
/// <remarks>
/// Each coordinate pair is encoded directly into the <see cref="PipeWriter"/>'s buffer using
/// <see cref="PolylineEncoding.WriteValue(int, System.Buffers.IBufferWriter{byte})"/>,
/// avoiding intermediate string or character-array allocations. The writer is flushed periodically
/// but is not completed by this method.
/// </remarks>
/// <param name="coordinates">
/// The asynchronous collection of <typeparamref name="TCoordinate"/> instances to encode.
/// </param>
/// <param name="writer">
/// The <see cref="PipeWriter"/> to which the encoded bytes are written.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to observe while iterating coordinates.
/// </param>
/// <returns>
/// A <see cref="ValueTask"/> representing the asynchronous encode-and-write operation.
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="coordinates"/> or <paramref name="writer"/> is <see langword="null"/>.
/// </exception>
public async ValueTask EncodeAsync(
IAsyncEnumerable<TCoordinate> coordinates,
PipeWriter writer,
CancellationToken cancellationToken) {
if (coordinates is null) {
throw new ArgumentNullException(nameof(coordinates));
}
if (writer is null) {
throw new ArgumentNullException(nameof(writer));
}
CoordinateVariance variance = new();
await foreach (TCoordinate coordinate in coordinates.WithCancellation(cancellationToken).ConfigureAwait(false)) {
variance.Next(
PolylineEncoding.Normalize(GetLatitude(coordinate), CoordinateValueType.Latitude),
PolylineEncoding.Normalize(GetLongitude(coordinate), CoordinateValueType.Longitude));
PolylineEncoding.WriteValue(variance.Latitude, writer);
PolylineEncoding.WriteValue(variance.Longitude, writer);
}
await writer.FlushAsync(cancellationToken).ConfigureAwait(false);
}
}