-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathSentencePieceBaseModel.cs
More file actions
798 lines (660 loc) · 30.8 KB
/
Copy pathSentencePieceBaseModel.cs
File metadata and controls
798 lines (660 loc) · 30.8 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Sentencepiece;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Microsoft.ML.Tokenizers
{
internal abstract class SentencePieceBaseModel
{
internal SentencePieceBaseModel(ModelProto modelProto, bool addBos = false, bool addEos = false, IReadOnlyDictionary<string, int>? specialTokens = null)
{
if (modelProto is null)
{
throw new ArgumentNullException(nameof(modelProto));
}
AddBeginningOfSentence = addBos;
AddEndOfSentence = addEos;
BeginningOfSentenceToken = modelProto.TrainerSpec.BosPiece ?? "<s>";
BeginningOfSentenceId = Math.Max(0, modelProto.TrainerSpec.BosId);
EndOfSentenceToken = modelProto.TrainerSpec.EosPiece ?? "</s>";
EndOfSentenceId = Math.Max(0, modelProto.TrainerSpec.EosId);
UnknownToken = modelProto.TrainerSpec.UnkPiece ?? "<unk>";
UnknownId = Math.Max(0, modelProto.TrainerSpec.UnkId);
AddDummyPrefix = modelProto.NormalizerSpec.AddDummyPrefix;
EscapeWhiteSpaces = modelProto.NormalizerSpec.EscapeWhitespaces;
TreatWhitespaceAsSuffix = modelProto.TrainerSpec.TreatWhitespaceAsSuffix;
ByteFallback = modelProto.TrainerSpec.ByteFallback;
SpecialTokens = specialTokens;
if (specialTokens is not null && specialTokens.Count > 0)
{
InternalSpecialTokens = new Dictionary<StringSpanOrdinalKey, int>();
SpecialTokensReverse = new Dictionary<int, string>();
foreach (var item in specialTokens)
{
InternalSpecialTokens.Add(new StringSpanOrdinalKey(item.Key), item.Value);
SpecialTokensReverse.Add(item.Value, item.Key);
}
// We create this Regex object without a timeout, as we expect the match operation to complete in O(N) time complexity. Note that `specialTokens` are treated as constants after the tokenizer is created.
SpecialTokensRegex = new Regex(string.Join("|", specialTokens.Keys.Select(s => Regex.Escape(s))), RegexOptions.Compiled);
}
Normalizer = new SentencePieceNormalizer(
modelProto.NormalizerSpec.PrecompiledCharsmap.Span,
modelProto.NormalizerSpec.RemoveExtraWhitespaces,
AddDummyPrefix, EscapeWhiteSpaces,
modelProto.TrainerSpec.TreatWhitespaceAsSuffix,
specialTokens);
}
internal SentencePieceBaseModel(
bool addBos, bool addEos,
string bosToken, int bosId,
string eosToken, int eosId,
string unkToken, int unkId,
bool addDummyPrefix, bool escapeWhiteSpaces,
bool treatWhitespaceAsSuffix, bool byteFallback,
ReadOnlySpan<byte> precompiledCharsmap, bool removeExtraWhitespaces,
IReadOnlyDictionary<string, int>? specialTokens)
{
AddBeginningOfSentence = addBos;
AddEndOfSentence = addEos;
BeginningOfSentenceToken = bosToken;
BeginningOfSentenceId = Math.Max(0, bosId);
EndOfSentenceToken = eosToken;
EndOfSentenceId = Math.Max(0, eosId);
UnknownToken = unkToken;
UnknownId = Math.Max(0, unkId);
AddDummyPrefix = addDummyPrefix;
EscapeWhiteSpaces = escapeWhiteSpaces;
TreatWhitespaceAsSuffix = treatWhitespaceAsSuffix;
ByteFallback = byteFallback;
SpecialTokens = specialTokens;
if (specialTokens is not null && specialTokens.Count > 0)
{
InternalSpecialTokens = new Dictionary<StringSpanOrdinalKey, int>();
SpecialTokensReverse = new Dictionary<int, string>();
foreach (var item in specialTokens)
{
InternalSpecialTokens.Add(new StringSpanOrdinalKey(item.Key), item.Value);
SpecialTokensReverse.Add(item.Value, item.Key);
}
SpecialTokensRegex = new Regex(string.Join("|", specialTokens.Keys.Select(s => Regex.Escape(s))), RegexOptions.Compiled);
}
Normalizer = new SentencePieceNormalizer(
precompiledCharsmap, removeExtraWhitespaces,
addDummyPrefix, escapeWhiteSpaces,
treatWhitespaceAsSuffix, specialTokens);
}
internal Regex? SpecialTokensRegex { get; }
internal Dictionary<StringSpanOrdinalKey, int>? InternalSpecialTokens { get; }
internal Dictionary<int, string>? SpecialTokensReverse { get; }
internal int MaxByteId { get; set; } // the maximum value of the byte id.;
internal int ByteCodeToIdOffset { get; set; } // offset of mapping byte code to the to the Ids.
internal int OneByteUtf8EncodingMaxId { get; set; } // the maximum value of the one byte UTF-8 character.
public IReadOnlyDictionary<string, int>? SpecialTokens { get; }
public bool ByteFallback { get; }
public bool AddDummyPrefix { get; }
public bool EscapeWhiteSpaces { get; }
public bool TreatWhitespaceAsSuffix { get; internal set; }
public bool AddBeginningOfSentence { get; }
public bool AddEndOfSentence { get; }
public string BeginningOfSentenceToken { get; }
public string EndOfSentenceToken { get; }
public string UnknownToken { get; }
public int BeginningOfSentenceId { get; set; }
public int EndOfSentenceId { get; set; }
public int UnknownId { get; set; }
public SentencePieceNormalizer? Normalizer { get; }
public abstract IReadOnlyDictionary<string, int> Vocabulary { get; }
public abstract IReadOnlyList<EncodedToken> EncodeToTokens(
string? text,
ReadOnlySpan<char> textSpan,
out string? normalizedText,
bool addBeginningOfSentence,
bool addEndOfSentence,
bool considerNormalization);
public abstract IReadOnlyList<int> EncodeToIds(
string? text,
ReadOnlySpan<char> textSpan,
bool addBeginningOfSentence,
bool addEndOfSentence,
bool considerNormalization,
out string? normalizedText,
out int charsConsumed,
int maxTokenCount = int.MaxValue);
public abstract int CountTokens(
string? text,
ReadOnlySpan<char> textSpan,
bool addBeginningOfSentence,
bool addEndOfSentence,
bool considerNormalization,
out string? normalizedText,
out int charsConsumed,
int maxTokenCount = int.MaxValue);
public abstract int GetIndexByTokenCountFromEnd(
string? text,
ReadOnlySpan<char> textSpan,
bool addBeginningOfSentence,
bool addEndOfSentence,
int maxTokenCount,
bool considerNormalization,
out string? normalizedText,
out int tokenCount);
public abstract bool TryMapIdToToken(int id, out string? token);
private const int ApproximatedMaxEncodedBytesCount = 50;
public virtual string Decode(IEnumerable<int> ids, bool considerSpecialTokens)
{
if (ids is null)
{
throw new ArgumentNullException(nameof(ids));
}
using IEnumerator<int> enumerator = ids.GetEnumerator();
if (!enumerator.MoveNext())
{
return string.Empty;
}
ValueStringBuilder sb = new(stackalloc char[256]);
int bytesCount = -1;
byte[]? bytesPoolArray = null;
bool prefixRemoved = false;
int suffixIndex = -1;
char prefixSuffixChar = EscapeWhiteSpaces ? SentencePieceNormalizer.DummyPrefix : ' ';
int current = enumerator.Current;
if (current <= MaxByteId && ByteFallback)
{
// First token is a byte token.
while (current < ByteCodeToIdOffset)
{
// It is possible listing some special tokens before the byte tokens in the tokenizer's data.
TryDecodeAsSpecialToken(this, current, considerSpecialTokens, ref sb);
// Skip control tokens.
if (!enumerator.MoveNext())
{
return sb.ToString();
}
current = enumerator.Current;
}
if (current <= MaxByteId && ByteFallback)
{
EncodeByte(current, OneByteUtf8EncodingMaxId, ByteCodeToIdOffset, ref bytesCount, ref bytesPoolArray, ref sb);
}
else if (!TryDecodeAsSpecialToken(this, current, considerSpecialTokens, ref sb) && TryMapIdToToken(current, out string? token))
{
AppendTokenWithCheckingPrefix(AddDummyPrefix, TreatWhitespaceAsSuffix, token!, prefixSuffixChar, ref sb, ref prefixRemoved, ref suffixIndex);
}
}
else if (!TryDecodeAsSpecialToken(this, current, considerSpecialTokens, ref sb) && TryMapIdToToken(current, out string? token))
{
AppendTokenWithCheckingPrefix(AddDummyPrefix, TreatWhitespaceAsSuffix, token!, prefixSuffixChar, ref sb, ref prefixRemoved, ref suffixIndex);
}
char[]? charPoolArray = null;
while (enumerator.MoveNext())
{
current = enumerator.Current;
if (current < ByteCodeToIdOffset)
{
if (bytesCount >= 1)
{
FlushBytes(ref bytesCount, ref bytesPoolArray, ref charPoolArray, ref sb);
}
// It is possible listing some special tokens before the byte tokens in the tokenizer's data.
TryDecodeAsSpecialToken(this, current, considerSpecialTokens, ref sb);
continue;
}
if (current <= MaxByteId && ByteFallback)
{
if (bytesCount >= 1)
{
Debug.Assert(bytesPoolArray is not null);
if (bytesCount >= bytesPoolArray!.Length)
{
Helpers.ArrayPoolGrow(ref bytesPoolArray, bytesCount * 2);
}
bytesPoolArray![bytesCount++] = (byte)(current - ByteCodeToIdOffset);
}
else
{
EncodeByte(current, OneByteUtf8EncodingMaxId, ByteCodeToIdOffset, ref bytesCount, ref bytesPoolArray, ref sb);
}
}
else
{
if (bytesCount >= 1)
{
FlushBytes(ref bytesCount, ref bytesPoolArray, ref charPoolArray, ref sb);
}
if (!TryDecodeAsSpecialToken(this, current, considerSpecialTokens, ref sb) && TryMapIdToToken(current, out string? token))
{
AppendTokenWithCheckingPrefix(AddDummyPrefix, TreatWhitespaceAsSuffix, token!, prefixSuffixChar, ref sb, ref prefixRemoved, ref suffixIndex);
}
}
}
if (bytesCount >= 1)
{
FlushBytes(ref bytesCount, ref bytesPoolArray, ref charPoolArray, ref sb);
}
if (AddDummyPrefix && TreatWhitespaceAsSuffix && suffixIndex >= 0 && sb.Length > 0)
{
Debug.Assert(sb[suffixIndex] == SentencePieceNormalizer.DummyPrefix);
Debug.Assert(sb.Length > suffixIndex);
sb.Remove(suffixIndex, 1);
}
if (bytesPoolArray is not null)
{
ArrayPool<byte>.Shared.Return(bytesPoolArray);
}
if (charPoolArray is not null)
{
ArrayPool<char>.Shared.Return(charPoolArray);
}
return EscapeWhiteSpaces ? sb.ToString(SentencePieceNormalizer.DummyPrefix, ' ') : sb.ToString();
static void FlushBytes(ref int bytesCount, ref byte[]? bytesPoolArray, ref char[]? charPoolArray, ref ValueStringBuilder sb)
{
Debug.Assert(bytesCount >= 1);
Debug.Assert(bytesPoolArray is not null);
int len = Encoding.UTF8.GetMaxCharCount(bytesCount);
charPoolArray ??= ArrayPool<char>.Shared.Rent(Math.Max(len, ApproximatedMaxEncodedBytesCount >> 1));
if (len > charPoolArray.Length)
{
Helpers.ArrayPoolGrow(ref charPoolArray, len);
}
int charCount = Helpers.GetChars(bytesPoolArray.AsSpan(0, bytesCount), charPoolArray);
sb.Append(charPoolArray.AsSpan(0, charCount));
bytesCount = -1;
}
static void EncodeByte(int id, int oneByteUtf8EncodingMaxId, int byteCodeToIdOffset, ref int bytesCount, ref byte[]? bytesPoolArray, ref ValueStringBuilder sb)
{
if (id <= oneByteUtf8EncodingMaxId)
{
sb.Append((char)(id - byteCodeToIdOffset));
}
else
{
bytesCount = 1;
bytesPoolArray ??= ArrayPool<byte>.Shared.Rent(ApproximatedMaxEncodedBytesCount);
bytesPoolArray[0] = (byte)(id - byteCodeToIdOffset);
}
}
static void AppendTokenWithCheckingPrefix(bool addDummyPrefix, bool treatWhitespaceAsSuffix, string token, char prefixSuffixChar, ref ValueStringBuilder sb, ref bool prefixRemoved, ref int suffixIndex)
{
if (token.Length == 0)
{
return;
}
if (!addDummyPrefix)
{
sb.Append(token);
return;
}
if (treatWhitespaceAsSuffix)
{
sb.Append(token);
if (token[token.Length - 1] == prefixSuffixChar)
{
suffixIndex = sb.Length - 1;
}
}
else
{
sb.Append(!prefixRemoved && token[0] == prefixSuffixChar ? token.AsSpan(1) : token.AsSpan());
}
prefixRemoved = true;
}
static bool TryDecodeAsSpecialToken(SentencePieceBaseModel model, int id, bool considerSpecialTokens, ref ValueStringBuilder sb)
{
string? token = null;
if (id == model.BeginningOfSentenceId)
{
token = model.BeginningOfSentenceToken;
}
else if (id == model.EndOfSentenceId)
{
token = model.EndOfSentenceToken;
}
else if (id == model.UnknownId)
{
token = model.UnknownToken;
}
else if (model.SpecialTokensReverse?.TryGetValue(id, out string? specialToken) is true)
{
token = specialToken;
}
if (token is not null && considerSpecialTokens)
{
sb.Append(token);
}
return token is not null;
}
}
public virtual OperationStatus Decode(IEnumerable<int> ids, Span<char> destination, bool considerSpecialTokens, out int idsConsumed, out int charsWritten)
{
idsConsumed = 0;
charsWritten = 0;
if (ids is null)
{
throw new ArgumentNullException(nameof(ids));
}
using IEnumerator<int> enumerator = ids.GetEnumerator();
if (!enumerator.MoveNext())
{
return OperationStatus.Done;
}
Span<char> buffer = destination;
int bytesCount = -1;
byte[]? bytesPoolArray = null;
bool prefixRemoved = false;
int suffixIndex = -1;
char prefixSuffixChar = EscapeWhiteSpaces ? SentencePieceNormalizer.DummyPrefix : ' ';
int current = enumerator.Current;
if (current <= MaxByteId && ByteFallback)
{
// First token is a byte token.
while (current < ByteCodeToIdOffset)
{
OperationStatus status = TryDecodeAsSpecialToken(this, current, considerSpecialTokens, buffer, ref charsWritten, out bool isSpecialToken);
if (status != OperationStatus.Done)
{
return status;
}
buffer = destination.Slice(charsWritten);
// Skip control tokens.
idsConsumed++;
if (!enumerator.MoveNext())
{
return OperationStatus.Done;
}
current = enumerator.Current;
}
if (current <= MaxByteId && ByteFallback)
{
if (!EncodeByte(enumerator.Current, OneByteUtf8EncodingMaxId, ByteCodeToIdOffset, ref bytesCount, buffer, ref charsWritten, ref idsConsumed, ref bytesPoolArray))
{
return OperationStatus.DestinationTooSmall;
}
}
else
{
OperationStatus status = TryDecodeAsSpecialToken(this, current, considerSpecialTokens, buffer, ref charsWritten, out bool isSpecialToken);
if (status != OperationStatus.Done)
{
return status;
}
if (!isSpecialToken && TryMapIdToToken(current, out string? token))
{
if (!AppendTokenWithCheckingPrefix(AddDummyPrefix, TreatWhitespaceAsSuffix, token!, prefixSuffixChar, destination, ref prefixRemoved, ref suffixIndex, ref idsConsumed, ref charsWritten))
{
return OperationStatus.DestinationTooSmall;
}
}
else
{
idsConsumed++;
}
}
}
else
{
OperationStatus status = TryDecodeAsSpecialToken(this, current, considerSpecialTokens, buffer, ref charsWritten, out bool isSpecialToken);
if (status != OperationStatus.Done)
{
return status;
}
if (!isSpecialToken && TryMapIdToToken(current, out string? token))
{
if (!AppendTokenWithCheckingPrefix(AddDummyPrefix, TreatWhitespaceAsSuffix, token!, prefixSuffixChar, destination, ref prefixRemoved, ref suffixIndex, ref idsConsumed, ref charsWritten))
{
return OperationStatus.DestinationTooSmall;
}
}
else
{
idsConsumed++;
}
}
char[]? charPoolArray = null;
while (enumerator.MoveNext())
{
current = enumerator.Current;
buffer = destination.Slice(charsWritten);
if (current < ByteCodeToIdOffset)
{
if (bytesCount >= 1)
{
if (!FlushBytes(ref bytesCount, ref bytesPoolArray, ref charPoolArray, buffer, ref charsWritten, ref idsConsumed))
{
return OperationStatus.DestinationTooSmall;
}
}
OperationStatus status = TryDecodeAsSpecialToken(this, current, considerSpecialTokens, buffer, ref charsWritten, out bool isSpecialToken);
if (status != OperationStatus.Done)
{
return status;
}
idsConsumed++;
continue;
}
if (current <= MaxByteId && ByteFallback)
{
if (bytesCount >= 1)
{
Debug.Assert(bytesPoolArray is not null);
if (bytesCount >= bytesPoolArray!.Length)
{
Helpers.ArrayPoolGrow(ref bytesPoolArray, bytesCount * 2);
}
bytesPoolArray![bytesCount++] = (byte)(current - ByteCodeToIdOffset);
}
else
{
if (!EncodeByte(current, OneByteUtf8EncodingMaxId, ByteCodeToIdOffset, ref bytesCount, buffer, ref charsWritten, ref idsConsumed, ref bytesPoolArray))
{
return OperationStatus.DestinationTooSmall;
}
}
}
else
{
if (bytesCount >= 1)
{
if (!FlushBytes(ref bytesCount, ref bytesPoolArray, ref charPoolArray, buffer, ref charsWritten, ref idsConsumed))
{
return OperationStatus.DestinationTooSmall;
}
}
OperationStatus status = TryDecodeAsSpecialToken(this, current, considerSpecialTokens, buffer, ref charsWritten, out bool isSpecialToken);
if (status != OperationStatus.Done)
{
return status;
}
if (!isSpecialToken && TryMapIdToToken(current, out string? token))
{
if (!AppendTokenWithCheckingPrefix(AddDummyPrefix, TreatWhitespaceAsSuffix, token!, prefixSuffixChar, destination, ref prefixRemoved, ref suffixIndex, ref idsConsumed, ref charsWritten))
{
return OperationStatus.DestinationTooSmall;
}
}
else
{
idsConsumed++;
}
}
}
buffer = destination.Slice(charsWritten);
if (bytesCount >= 1)
{
if (!FlushBytes(ref bytesCount, ref bytesPoolArray, ref charPoolArray, buffer, ref charsWritten, ref idsConsumed))
{
return OperationStatus.DestinationTooSmall;
}
}
if (suffixIndex >= 0)
{
Debug.Assert(destination[suffixIndex] == ' ');
if (suffixIndex < charsWritten - 1)
{
destination.Slice(suffixIndex + 1, charsWritten - suffixIndex - 1).CopyTo(destination.Slice(suffixIndex));
}
charsWritten--;
}
if (bytesPoolArray is not null)
{
ArrayPool<byte>.Shared.Return(bytesPoolArray);
}
if (charPoolArray is not null)
{
ArrayPool<char>.Shared.Return(charPoolArray);
}
return OperationStatus.Done;
static OperationStatus TryDecodeAsSpecialToken(SentencePieceBaseModel model, int id, bool considerSpecialTokens, Span<char> buffer, ref int charsWritten, out bool isSpecialToken)
{
string? specialToken = null;
if (id == model.BeginningOfSentenceId)
{
specialToken = model.BeginningOfSentenceToken;
}
else if (id == model.EndOfSentenceId)
{
specialToken = model.EndOfSentenceToken;
}
else if (id == model.UnknownId)
{
specialToken = model.UnknownToken;
}
else
{
model.SpecialTokensReverse?.TryGetValue(id, out specialToken);
}
isSpecialToken = specialToken is not null;
if (considerSpecialTokens && isSpecialToken)
{
if (buffer.Length < specialToken!.Length)
{
return OperationStatus.DestinationTooSmall;
}
specialToken.AsSpan().CopyTo(buffer);
charsWritten += specialToken.Length;
}
return OperationStatus.Done;
}
static bool FlushBytes(ref int bytesCount, ref byte[]? bytesPoolArray, ref char[]? charPoolArray, Span<char> buffer, ref int charsWritten, ref int idsConsumed)
{
Debug.Assert(bytesCount >= 1);
Debug.Assert(bytesPoolArray is not null);
int len = Encoding.UTF8.GetMaxCharCount(bytesCount);
charPoolArray ??= ArrayPool<char>.Shared.Rent(Math.Max(len, ApproximatedMaxEncodedBytesCount >> 1));
if (len > charPoolArray.Length)
{
Helpers.ArrayPoolGrow(ref charPoolArray, len);
}
int charCount = Helpers.GetChars(bytesPoolArray.AsSpan(0, bytesCount), charPoolArray);
if (charCount > buffer.Length)
{
return false;
}
charPoolArray.AsSpan(0, charCount).CopyTo(buffer);
charsWritten += charCount;
idsConsumed += bytesCount;
bytesCount = -1;
return true;
}
static bool EncodeByte(int id, int oneByteUtf8EncodingMaxId, int byteCodeToIdOffset, ref int bytesCount, Span<char> buffer, ref int charsWritten, ref int idsConsumed, ref byte[]? bytesPoolArray)
{
if (id <= oneByteUtf8EncodingMaxId)
{
if (buffer.Length < 1)
{
return false;
}
buffer[0] = (char)(id - byteCodeToIdOffset);
charsWritten++;
idsConsumed++;
}
else
{
bytesCount = 1;
bytesPoolArray ??= ArrayPool<byte>.Shared.Rent(ApproximatedMaxEncodedBytesCount);
bytesPoolArray[0] = (byte)(id - byteCodeToIdOffset);
}
return true;
}
static bool AppendTokenWithCheckingPrefix(bool addDummyPrefix, bool treatWhitespaceAsSuffix, string token, char prefixSuffixChar, Span<char> destination, ref bool prefixRemoved, ref int suffixIndex, ref int idsConsumed, ref int charsConsumed)
{
if (token.Length == 0)
{
return true;
}
Span<char> buffer = destination.Slice(charsConsumed);
ReadOnlySpan<char> tokenSpan = token.AsSpan();
if (!addDummyPrefix)
{
if (tokenSpan.Length > buffer.Length)
{
return false;
}
if (prefixSuffixChar != ' ')
{
Helpers.Replace(tokenSpan, buffer, prefixSuffixChar, ' ');
}
else
{
tokenSpan.CopyTo(buffer);
}
buffer = buffer.Slice(tokenSpan.Length);
charsConsumed += tokenSpan.Length;
idsConsumed++;
return true;
}
if (treatWhitespaceAsSuffix)
{
if (tokenSpan[tokenSpan.Length - 1] == prefixSuffixChar)
{
suffixIndex = charsConsumed + tokenSpan.Length - 1;
}
if (tokenSpan.Length > buffer.Length)
{
return false;
}
if (prefixSuffixChar != ' ')
{
Helpers.Replace(tokenSpan, buffer, prefixSuffixChar, ' ');
}
else
{
tokenSpan.CopyTo(buffer);
}
charsConsumed += tokenSpan.Length;
idsConsumed++;
}
else
{
int delta = !prefixRemoved && token[0] == prefixSuffixChar ? 1 : 0;
if (buffer.Length < token.Length - delta)
{
return false;
}
tokenSpan = tokenSpan.Slice(delta);
if (prefixSuffixChar != ' ')
{
Helpers.Replace(tokenSpan, buffer, prefixSuffixChar, ' ');
}
else
{
tokenSpan.CopyTo(buffer);
}
charsConsumed += tokenSpan.Length;
idsConsumed++;
if (!prefixRemoved && delta == 1)
{
prefixRemoved = true;
}
}
return true;
}
}
}
}