aboutsummaryrefslogtreecommitdiffstats
path: root/libparc/parc/algol/parc_Buffer.c
blob: 20520f9ccb085e99a8c56e3ab2e06272aab3400c (plain)
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
/*
 * Copyright (c) 2017 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 */
#include <config.h>
#include <ctype.h>

#include <parc/assert/parc_Assert.h>

#include <parc/algol/parc_Object.h>
#include <parc/algol/parc_Buffer.h>
#include <parc/algol/parc_ByteArray.h>
#include <parc/algol/parc_Memory.h>
#include <parc/algol/parc_DisplayIndented.h>
#include <parc/algol/parc_HashCode.h>

struct parc_buffer {
    PARCByteArray *array;

    size_t capacity;

    size_t arrayOffset;  // The offset within this buffer's backing PARCByteArray of the first element.

    size_t position;      // The index, relative to arrayOffset, of the next byte to be read from or written to this buffer.

    /**
     * The index, relative to arrayOffset, of the last position that cannot be read or written.
     */
    size_t limit;
    /**
     * A buffer's mark is the index, relative to arrayOffset, to which its position will be set when the reset function is invoked.
     * The mark is not always defined, but when it is defined it is never negative and is never greater than the position.
     * If the mark is defined then it is discarded when the position or the limit is adjusted to a value smaller than the mark.
     * If the mark is not defined then invoking the reset function causes a trap.
     */
    size_t mark;
};

static inline void
_discardMark(PARCBuffer *buffer)
{
    buffer->mark = SIZE_MAX;
}

static inline bool
_markIsDiscarded(const PARCBuffer *buffer)
{
    return buffer->mark == SIZE_MAX;
}

static inline void
_trapIfIndexExceedsLimit(const PARCBuffer *buffer, const size_t index)
{
    //parcTrapOutOfBoundsIf(index > buffer->limit, "PARCBuffer limit at %zd, attempted to access at %zd",
    //                  parcBuffer_Limit(buffer), index);
}

static inline void
_trapIfBufferUnderflow(const PARCBuffer *buffer, const size_t requiredRemaining)
{
    _trapIfIndexExceedsLimit(buffer, buffer->position + requiredRemaining);
}

static inline size_t
_effectiveIndex(const PARCBuffer *buffer, const size_t index)
{
    return buffer->arrayOffset + index;
}

static inline size_t
_effectivePosition(const PARCBuffer *buffer)
{
    return buffer->arrayOffset + parcBuffer_Position(buffer);
}

#ifdef PARCLibrary_DISABLE_VALIDATION
#  define _optionalAssertInvariants(_instance_)
#else
#  define _optionalAssertInvariants(_instance_) _assertInvariants(_instance_)

static inline void
_assertInvariants(const PARCBuffer *buffer)
{
    // 0 <= mark <= position <= limit <= capacity
    parcAssertTrue(0 <= buffer->mark,
               "Expected 0 <= mark (%zd)", buffer->mark);
    parcAssertTrue(_markIsDiscarded(buffer) || buffer->mark <= buffer->position,
               "Expected mark (%zd) <= position (%zd)", buffer->mark, buffer->position);
    parcAssertTrue(buffer->position <= buffer->limit,
               "Expected position (%zd) <= limit (%zd)", buffer->position, buffer->limit);
    parcAssertTrue(buffer->limit <= buffer->capacity,
               "Expected limit (%zd) <= capacity (%zd)", buffer->limit, buffer->capacity);
    parcAssertTrue((buffer->arrayOffset + buffer->capacity) <= parcByteArray_Capacity(buffer->array),
               "Expected (%zd + %zd) <= %zd",
               buffer->arrayOffset, buffer->capacity, parcByteArray_Capacity(buffer->array));
}
#endif

static inline int
_digittoint(char digit)
{
    int result = -1;

    int value = digit - '0';

    if ((unsigned) value < 10) {
        result = value;
    } else {
        value = digit - 'a';
        if ((unsigned) value < 6) {
            result = value + 10;
        } else {
            value = digit - 'A';
            if ((unsigned) value < 6) {
                result = value + 10;
            }
        }
    }

    return result;
}

// This hexadecimal parsing code needs to be fixed - see FogBugz:3598

static char *_hexDigitsUpper = "0123456789ABCDEF";
static char *_hexDigitsLower = "0123456789abcdef";

static inline char
_fromHexDigit(char hexDigit)
{
    for (char i = 0; i < 16; i++) {
        if (hexDigit == _hexDigitsLower[(int) i] || hexDigit == _hexDigitsUpper[(int) i]) {
            return i;
        }
    }
    return -1;
}

static inline uint8_t
_hexByte(const char *hexByte)
{
    uint8_t result = (uint8_t) (_fromHexDigit(hexByte[0]) << 4) | _fromHexDigit(hexByte[1]);
    return result;
}

static inline char *
_parcBuffer_CheckValidity(const PARCBuffer *buffer)
{
    char *result = NULL;

    if (buffer != NULL) {
        if (parcObject_IsValid(buffer)) {
            if (parcByteArray_IsValid(buffer->array)) {
                // 0 <= mark <= position <= limit <= capacity
                if (_markIsDiscarded(buffer) || buffer->mark <= buffer->position) {
                    if (buffer->position <= buffer->limit) {
                        if (buffer->limit <= buffer->capacity) {
                            if ((buffer->arrayOffset + buffer->capacity) <= parcByteArray_Capacity(buffer->array)) {
                                result = NULL;
                            } else {
                                result = "PARCBuffer offset+capacity exceeds the capacity of the underlying PARCByteArray";
                            }
                        } else {
                            result = "PARCBuffer limit exceeds the capacity.";
                        }
                    } else {
                        result = "PARCBuffer position exceeds the limit.";
                    }
                } else {
                    result = "PARCBuffer mark exceeds the current position";
                }
            } else {
                result = "PARCBuffer underlying PARCByteArray is invalid";
            }
        } else {
            result = "PARCBuffer is an invalid PARCObject.";
        }
    } else {
        result = "PARCBuffer is NULL";
    }

    return result;
}

void
parcBuffer_AssertValid(const PARCBuffer *buffer)
{
    char *explanation = _parcBuffer_CheckValidity(buffer);

    parcTrapIllegalValueIf(explanation != NULL, "PARCBuffer@%p %s.", (void *) buffer, explanation);
}

bool
parcBuffer_IsValid(const PARCBuffer *buffer)
{
    bool result = false;

    if (buffer != NULL) {
        if (parcObject_IsValid(buffer)) {
            if (parcByteArray_IsValid(buffer->array)) {
                // 0 <= mark <= position <= limit <= capacity
                if (_markIsDiscarded(buffer) || buffer->mark <= buffer->position) {
                    if (buffer->position <= buffer->limit) {
                        if (buffer->limit <= buffer->capacity) {
                            if ((buffer->arrayOffset + buffer->capacity) <= parcByteArray_Capacity(buffer->array)) {
                                result = true;
                            }
                        }
                    }
                }
            }
        }
    }

    return result;
}

static bool
_parcBuffer_Destructor(PARCBuffer **bufferPtr)
{
    PARCBuffer *buffer = *bufferPtr;

    parcByteArray_Release(&buffer->array);
    return true;
}

parcObject_Override(PARCBuffer, PARCObject,
                    .destructor = (PARCObjectDestructor *) _parcBuffer_Destructor,
                    .copy = (PARCObjectCopy *) parcBuffer_Copy,
                    .toString = (PARCObjectToString *) parcBuffer_ToString,
                    .equals = (PARCObjectEquals *) parcBuffer_Equals,
                    .compare = (PARCObjectCompare *) parcBuffer_Compare,
                    .hashCode = (PARCObjectHashCode *) parcBuffer_HashCode,
                    .display = (PARCObjectDisplay *) parcBuffer_Display);

/**
 * Initialise a parcBuffer instance.
 *
 * The buffer's offset, position, limit and capacity are set to the given values.
 * The mark is made invalid.
 *
 * @return The same pointer as `result`.
 */
static PARCBuffer *
_parcBuffer_Init(PARCBuffer *result, PARCByteArray *array, size_t offset, size_t position, size_t limit, size_t capacity)
{
    result->array = array;
    result->arrayOffset = offset;
    result->position = position;
    result->limit = limit;
    result->capacity = capacity;
    _discardMark(result);

    parcBuffer_OptionalAssertValid(result);

    return result;
}

static inline PARCBuffer *
_parcBuffer_getInstance(void)
{
    PARCBuffer *result = parcObject_CreateInstance(PARCBuffer);

    return result;
}

static inline size_t
_computeNewLimit(size_t oldCapacity, size_t oldLimit, size_t newCapacity)
{
    size_t result = newCapacity;

    bool limitIsAtCapacity = (oldLimit == oldCapacity);

    if (newCapacity > oldCapacity) {
        if (limitIsAtCapacity) {
            result = newCapacity;
        } else {
            result = oldLimit;
        }
    } else {
        if (limitIsAtCapacity) {
            result = newCapacity;
        } else {
            result = (oldLimit < newCapacity) ? oldLimit : newCapacity;
        }
    }

    return result;
}

static inline size_t
_computeNewMark(size_t oldMark, size_t newLimit, size_t newCapacity)
{
    size_t result = oldMark;

    if (oldMark != SIZE_MAX) {
        if (oldMark > newCapacity) {
            result = SIZE_MAX;
        } else {
            result = oldMark;
        }

        if (result > newLimit) {
            result = SIZE_MAX;
        }
    }

    return result;
}

PARCBuffer *
parcBuffer_WrapByteArray(PARCByteArray *byteArray, size_t position, size_t limit)
{
    PARCBuffer *result = NULL;

    // The limit cannot exceed the capacity of the PARCByteArray.
    if (limit > parcByteArray_Capacity(byteArray)) {
        return NULL;
    }
    if (byteArray != NULL) {
        result = _parcBuffer_getInstance();

        if (result != NULL) {
            return _parcBuffer_Init(result,
                                    parcByteArray_Acquire(byteArray),
                                    0, position, limit,
                                    parcByteArray_Capacity(byteArray));
        }
    }

    return result;
}

PARCBuffer *
parcBuffer_Resize(PARCBuffer *buffer, size_t newCapacity)
{
    parcBuffer_OptionalAssertValid(buffer);

    PARCByteArray *newArray = parcByteArray_Allocate(newCapacity);
    if (newArray == NULL) {
        return NULL;
    }

    size_t numberOfBytesToCopy = parcBuffer_Capacity(buffer);
    if (numberOfBytesToCopy > newCapacity) {
        numberOfBytesToCopy = newCapacity;
    }

    parcByteArray_PutBytes(newArray, 0, numberOfBytesToCopy, &parcByteArray_Array(buffer->array)[buffer->arrayOffset]);

    parcByteArray_Release(&buffer->array);

    buffer->array = newArray;
    buffer->arrayOffset = 0;
    buffer->limit = _computeNewLimit(buffer->capacity, buffer->limit, newCapacity);
    buffer->mark = _computeNewMark(buffer->mark, buffer->limit, newCapacity);
    buffer->capacity = newCapacity;
    buffer->position = (buffer->position < buffer->limit) ? buffer->position : buffer->limit;

    parcBuffer_OptionalAssertValid(buffer);

    return buffer;
}

PARCBuffer *
parcBuffer_Allocate(size_t capacity)
{
    PARCByteArray *array = parcByteArray_Allocate(capacity);

    if (array != NULL) {
        PARCBuffer *result = _parcBuffer_getInstance();
        if (result != NULL) {
            return _parcBuffer_Init(result, array, 0, 0, capacity, capacity);
        }
        parcByteArray_Release(&array);
    }

    return NULL;
}

PARCBuffer *
parcBuffer_Wrap(void *array, size_t arrayLength, size_t position, size_t limit)
{
    PARCBuffer *result = NULL;

    if (array != NULL) {
        PARCByteArray *byteArray = parcByteArray_Wrap(arrayLength, array);

        if (byteArray != NULL) {
            result = parcBuffer_WrapByteArray(byteArray, position, limit);
            parcByteArray_Release(&byteArray);
        }
    }

    return result;
}

PARCBuffer *
parcBuffer_WrapCString(char *string)
{
    size_t length = strlen(string);
    return parcBuffer_Wrap(string, length, 0, length);
}

PARCBuffer *
parcBuffer_AllocateCString(const char *string)
{
    size_t length = strlen(string);
    PARCBuffer *buffer = parcBuffer_Allocate(length + 1);
    parcBuffer_PutArray(buffer, length, (const uint8_t *) string);
    parcBuffer_PutUint8(buffer, 0);
    parcBuffer_SetPosition(buffer, buffer->position - 1);
    parcBuffer_Flip(buffer);

    return buffer;
}

PARCBuffer *
parcBuffer_ParseHexString(const char *hexString)
{
    size_t length = strlen(hexString);

    // The hex string must be an even length greater than zero.
    if (length > 0 && (length % 2) == 1) {
        return NULL;
    }

    PARCBuffer *result = parcBuffer_Allocate(length);
    for (size_t i = 0; i < length; i += 2) {
        parcBuffer_PutUint8(result, _hexByte(&hexString[i]));
    }

    return result;
}

PARCBuffer *
parcBuffer_CreateFromArray(const void *bytes, const size_t length)
{
    parcAssertTrue(length == 0 || bytes != NULL,
               "If the byte array is NULL, then length MUST be zero.");

    PARCBuffer *result = parcBuffer_Allocate(length);
    parcBuffer_PutArray(result, length, bytes);

    return result;
}

parcObject_ImplementAcquire(parcBuffer, PARCBuffer);

parcObject_ImplementRelease(parcBuffer, PARCBuffer);

size_t
parcBuffer_Capacity(const PARCBuffer *buffer)
{
    parcBuffer_OptionalAssertValid(buffer);

    return buffer->capacity;
}

PARCBuffer *
parcBuffer_Clear(PARCBuffer *buffer)
{
    parcBuffer_SetPosition(buffer, 0);
    parcBuffer_SetLimit(buffer, parcBuffer_Capacity(buffer));
    _discardMark(buffer);
    return buffer;
}

bool
parcBuffer_Equals(const PARCBuffer *x, const PARCBuffer *y)
{
    if (x == y) {
        return true;
    }
    if (x == NULL || y == NULL) {
        return false;
    }

    return (parcBuffer_Compare(x, y) == 0);
}

int
parcBuffer_Compare(const PARCBuffer *x, const PARCBuffer *y)
{
    if (x == y) {
        return 0;
    }

    if (x == NULL) {
        return -1;
    }

    if (y == NULL) {
        return +1;
    }

    size_t count = parcBuffer_Remaining(x);
    if (count > parcBuffer_Remaining(y)) {
        count = parcBuffer_Remaining(y);
    }

    int result = 0;

    if (count > 0) {
        result = memcmp(parcBuffer_Overlay((PARCBuffer *) x, 0), parcBuffer_Overlay((PARCBuffer *) y, 0), count);
    }

    if (result == 0) {
        // This is when one buffer is longer than the other, and they are equivalent thus far.
        ssize_t difference = parcBuffer_Remaining(x) - parcBuffer_Remaining(y);
        if (difference > 0) {
            result = +1;
        } else if (difference < 0) {
            result = -1;
        }
    }

    return result;
}

PARCByteArray *
parcBuffer_Array(const PARCBuffer *buffer)
{
    parcBuffer_OptionalAssertValid(buffer);

    return buffer->array;
}

PARCBuffer *
parcBuffer_Duplicate(const PARCBuffer *original)
{
    PARCBuffer *result = _parcBuffer_getInstance();
    if (result != NULL) {
        _parcBuffer_Init(result,
                         parcByteArray_Acquire(original->array),
                         original->arrayOffset,
                         original->position,
                         parcBuffer_Limit(original),
                         original->capacity);

        _optionalAssertInvariants(result);
    }
    return result;
}

PARCBuffer *
parcBuffer_Slice(const PARCBuffer *original)
{
    PARCBuffer *result = _parcBuffer_getInstance();
    if (result != NULL) {
        _parcBuffer_Init(result,
                         parcByteArray_Acquire(original->array),
                         original->arrayOffset + parcBuffer_Position(original),
                         0,
                         parcBuffer_Limit(original) - parcBuffer_Position(original),
                         parcBuffer_Limit(original) - parcBuffer_Position(original));

        _optionalAssertInvariants(result);
    }
    return result;
}

size_t
parcBuffer_ArrayOffset(const PARCBuffer *buffer)
{
    parcBuffer_OptionalAssertValid(buffer);

    return buffer->arrayOffset;
}

PARCBuffer *
parcBuffer_Reset(PARCBuffer *buffer)
{
    parcBuffer_OptionalAssertValid(buffer);

    parcAssertFalse(_markIsDiscarded(buffer),
                "The mark has not been set");
    buffer->position = buffer->mark;

    _optionalAssertInvariants(buffer);

    return buffer;
}

size_t
parcBuffer_Limit(const PARCBuffer *buffer)
{
    parcBuffer_OptionalAssertValid(buffer);

    return buffer->limit;
}

PARCBuffer *
parcBuffer_Mark(PARCBuffer *buffer)
{
    parcBuffer_OptionalAssertValid(buffer);

    buffer->mark = buffer->position;
    _optionalAssertInvariants(buffer);
    return buffer;
}

PARCBuffer *
parcBuffer_SetLimit(PARCBuffer *buffer, size_t newLimit)
{
    parcBuffer_OptionalAssertValid(buffer);
    parcAssertTrue(newLimit <= parcBuffer_Capacity(buffer),
               "new limit cannot be larger than the capacity");

    if (_markIsDiscarded(buffer)) {
        buffer->limit = newLimit;
        _discardMark(buffer);
    } else {
        if (newLimit < buffer->position) {
            buffer->position = newLimit;
        }
        if (newLimit < buffer->mark) {
            _discardMark(buffer);
        }
        buffer->limit = newLimit;
    }
    _optionalAssertInvariants(buffer);
    return buffer;
}

size_t
parcBuffer_Position(const PARCBuffer *buffer)
{
    parcBuffer_OptionalAssertValid(buffer);

    return buffer->position;
}

size_t
parcBuffer_Remaining(const PARCBuffer *buffer)
{
    parcBuffer_OptionalAssertValid(buffer);

    return buffer->limit - buffer->position;
}

bool
parcBuffer_HasRemaining(const PARCBuffer *buffer)
{
    parcBuffer_OptionalAssertValid(buffer);

    return parcBuffer_Remaining(buffer) != 0;
}

PARCBuffer *
parcBuffer_SetPosition(PARCBuffer *buffer, size_t newPosition)
{
    parcBuffer_OptionalAssertValid(buffer);

    parcAssertFalse(newPosition > buffer->limit,
                "new position cannot be greater the buffer's limit");

    buffer->position = newPosition;
    if (!_markIsDiscarded(buffer) && newPosition < buffer->mark) {
        _discardMark(buffer);
    }

    _optionalAssertInvariants(buffer);
    return buffer;
}

PARCBuffer *
parcBuffer_Rewind(PARCBuffer *buffer)
{
    parcBuffer_OptionalAssertValid(buffer);

    buffer->position = 0;
    _discardMark(buffer);

    _optionalAssertInvariants(buffer);
    return buffer;
}

PARCBuffer *
parcBuffer_Copy(const PARCBuffer *original)
{
    parcBuffer_OptionalAssertValid(original);

    PARCBuffer *result = _parcBuffer_getInstance();

    if (result != NULL) {
        PARCByteArray *array = parcByteArray_Copy(original->array);
        if (array != NULL) {
            _parcBuffer_Init(result,
                             array,
                             parcBuffer_ArrayOffset(original),
                             parcBuffer_Position(original),
                             parcBuffer_Limit(original),
                             parcBuffer_Capacity(original));
        } else {
            parcBuffer_Release(&result);
        }
    }

    return result;
}

PARCBuffer *
parcBuffer_Flip(PARCBuffer *result)
{
    parcBuffer_OptionalAssertValid(result);

    size_t position = result->position;
    result->position = 0;
    result->limit = position;

    _optionalAssertInvariants(result);

    return result;
}

uint8_t
parcBuffer_GetAtIndex(const PARCBuffer *buffer, size_t index)
{
    parcBuffer_OptionalAssertValid(buffer);

    _trapIfIndexExceedsLimit(buffer, index);

    return parcByteArray_GetByte(buffer->array, _effectiveIndex(buffer, index));
}

void *
parcBuffer_Overlay(PARCBuffer *buffer, size_t length)
{
    parcBuffer_OptionalAssertValid(buffer);
    _trapIfBufferUnderflow(buffer, length);

    uint8_t *result = parcByteArray_AddressOfIndex(buffer->array, _effectiveIndex(buffer, parcBuffer_Position(buffer)));
    buffer->position += length;
    return result;
}

uint8_t
parcBuffer_GetUint8(PARCBuffer *buffer)
{
    parcBuffer_OptionalAssertValid(buffer);
    _trapIfBufferUnderflow(buffer, 1);

    uint8_t result = parcByteArray_GetByte(buffer->array, _effectivePosition(buffer));
    buffer->position++;

    return result;
}

PARCBuffer *
parcBuffer_GetBytes(PARCBuffer *buffer, size_t length, uint8_t array[length])
{
    parcBuffer_OptionalAssertValid(buffer);
    _trapIfBufferUnderflow(buffer, length);

    parcByteArray_GetBytes(buffer->array, _effectivePosition(buffer), length, array);
    buffer->position += length;

    return buffer;
}

uint16_t
parcBuffer_GetUint16(PARCBuffer *buffer)
{
    uint8_t high = parcBuffer_GetUint8(buffer);
    uint8_t low = parcBuffer_GetUint8(buffer);

    uint16_t result = (high << 8) | low;

    return result;
}

uint32_t
parcBuffer_GetUint32(PARCBuffer *buffer)
{
    uint32_t result = 0;
    for (int i = 0; i < sizeof(uint32_t); i++) {
        result = result << 8 | parcBuffer_GetUint8(buffer);
    }
    return result;
}

uint64_t
parcBuffer_GetUint64(PARCBuffer *buffer)
{
    uint64_t result = 0;
    for (int i = 0; i < sizeof(uint64_t); i++) {
        result = result << 8 | parcBuffer_GetUint8(buffer);
    }
    return result;
}

PARCBuffer *
parcBuffer_PutUint8(PARCBuffer *buffer, uint8_t value)
{
    parcBuffer_OptionalAssertValid(buffer);
    parcAssertTrue(parcBuffer_Remaining(buffer) >= 1,
               "Buffer overflow");

    parcByteArray_PutByte(buffer->array, _effectivePosition(buffer), value);
    buffer->position++;
    return buffer;
}

PARCBuffer *
parcBuffer_PutUint16(PARCBuffer *buffer, uint16_t value)
{
    parcAssertTrue(parcBuffer_Remaining(buffer) >= sizeof(uint16_t),
               "Buffer overflow");

    parcBuffer_PutUint8(buffer, (value >> 8) & 0xFF);
    parcBuffer_PutUint8(buffer, value & 0xFF);
    return buffer;
}

PARCBuffer *
parcBuffer_PutUint32(PARCBuffer *buffer, uint32_t value)
{
    parcAssertTrue(parcBuffer_Remaining(buffer) >= sizeof(uint32_t),
               "Buffer overflow");
    for (int i = sizeof(uint32_t) - 1; i > 0; i--) {
        uint8_t b = value >> (i * 8) & 0xFF;
        parcBuffer_PutUint8(buffer, b);
    }
    parcBuffer_PutUint8(buffer, value & 0xFF);
    return buffer;
}

PARCBuffer *
parcBuffer_PutUint64(PARCBuffer *buffer, uint64_t value)
{
    parcAssertTrue(parcBuffer_Remaining(buffer) >= sizeof(uint64_t),
               "Buffer overflow");
    for (int i = sizeof(uint64_t) - 1; i > 0; i--) {
        uint8_t b = value >> (i * 8) & 0xFF;
        parcBuffer_PutUint8(buffer, b);
    }
    parcBuffer_PutUint8(buffer, value & 0xFF);
    return buffer;
}

PARCBuffer *
parcBuffer_PutAtIndex(PARCBuffer *buffer, size_t index, uint8_t value)
{
    parcBuffer_OptionalAssertValid(buffer);
    parcAssertTrue(_effectiveIndex(buffer, index) < parcBuffer_Limit(buffer), "Buffer overflow");

    parcByteArray_PutByte(buffer->array, _effectiveIndex(buffer, index), value);
    return buffer;
}

PARCBuffer *
parcBuffer_PutArray(PARCBuffer *buffer, size_t arrayLength, const uint8_t array[arrayLength])
{
    parcBuffer_OptionalAssertValid(buffer);
    parcAssertTrue(parcBuffer_Remaining(buffer) >= arrayLength,
               "Buffer overflow");

    parcByteArray_PutBytes(buffer->array, _effectivePosition(buffer), arrayLength, array);
    return parcBuffer_SetPosition(buffer, parcBuffer_Position(buffer) + arrayLength);
}

PARCBuffer *
parcBuffer_PutCString(PARCBuffer *buffer, const char *string)
{
    return parcBuffer_PutArray(buffer, strlen(string) + 1, (const uint8_t *) string);
}

PARCBuffer *
parcBuffer_PutBuffer(PARCBuffer *result, const PARCBuffer *buffer)
{
    parcBuffer_OptionalAssertValid(buffer);
    parcAssertTrue(parcBuffer_Remaining(result) >= parcBuffer_Remaining(buffer),
               "Buffer overflow. %zd bytes remaining, %zd required.", parcBuffer_Remaining(result), parcBuffer_Remaining(buffer));

    size_t length = parcBuffer_Remaining(buffer);
    parcByteArray_ArrayCopy(result->array, _effectivePosition(result), buffer->array, _effectivePosition(buffer), length);
    parcBuffer_SetPosition(result, parcBuffer_Position(result) + length);
    return result;
}

PARCHashCode
parcBuffer_HashCode(const PARCBuffer *buffer)
{
    PARCHashCode result = 0;

    size_t remaining = parcBuffer_Remaining(buffer);
    if (remaining > 0) {
        result = parcHashCode_Hash(parcBuffer_Overlay((PARCBuffer *) buffer, 0), parcBuffer_Remaining(buffer));
    }
    return result;
}

size_t
parcBuffer_FindUint8(const PARCBuffer *buffer, uint8_t byte)
{
    for (size_t i = parcBuffer_Position(buffer); i < parcBuffer_Limit(buffer); i++) {
        if (parcBuffer_GetAtIndex(buffer, i) == byte) {
            return i;
        }
    }
    return SIZE_MAX;
}

char *
parcBuffer_ToString(const PARCBuffer *buffer)
{
    size_t remaining = parcBuffer_Remaining(buffer);

    char *result = parcMemory_Allocate(remaining + 1);
    if (remaining > 0) {
        parcAssertNotNull(result, "parcMemory_Allocate returned NULL");
        if (result != NULL) {
            memcpy(result, parcBuffer_Overlay((PARCBuffer *) buffer, 0), remaining);
        }
    }
    result[remaining] = 0;
    return result;
}

void
parcBuffer_Display(const PARCBuffer *buffer, int indentation)
{
    if (buffer == NULL) {
        parcDisplayIndented_PrintLine(indentation, "PARCBuffer@NULL");
    } else {
        parcDisplayIndented_PrintLine(indentation, "PARCBuffer@%p {", (void *) buffer);
        parcDisplayIndented_PrintLine(indentation + 1,
                                      ".arrayOffset=%zd .position=%zd .limit=%zd .mark=%zd",
                                      buffer->arrayOffset, buffer->position, buffer->limit, buffer->mark);
        parcByteArray_Display(buffer->array, indentation + 1);
        parcDisplayIndented_PrintLine(indentation, "}");
    }
}

// Given a value, return the low nibble as a hex character.
static char
_toHexDigit(const char value)
{
    return "0123456789ABCDEF"[value & 0xF];
}

char *
parcBuffer_ToHexString(const PARCBuffer *buffer)
{
    if (buffer == NULL) {
        return parcMemory_StringDuplicate("null", 4);
    }

    size_t length = parcBuffer_Remaining(buffer);
    // Hopefully length is less than (2^(sizeof(size_t)*8) / 2)

    char *result = parcMemory_AllocateAndClear((length * 2) + 1);
    parcAssertNotNull(result, "parcMemory_AllocateAndClear(%zu) returned NULL", (length * 2) + 1);

    for (size_t i = 0; i < length; i++) {
        unsigned char byte = parcBuffer_GetAtIndex(buffer, i);
        result[i * 2] = _toHexDigit(byte >> 4);
        result[i * 2 + 1] = _toHexDigit(byte);
    }
    result[length * 2] = 0;

    return result;
}

bool
parcBuffer_SkipOver(PARCBuffer *buffer, size_t length, const uint8_t bytesToSkipOver[length])
{
    while (parcBuffer_Remaining(buffer) > 0) {
        uint8_t character = parcBuffer_GetUint8(buffer);
        if (memchr(bytesToSkipOver, character, length) == NULL) {
            parcBuffer_SetPosition(buffer, parcBuffer_Position(buffer) - 1);
            return true;
        }
    }
    return false;
}

bool
parcBuffer_SkipTo(PARCBuffer *buffer, size_t length, const uint8_t bytesToSkipTo[length])
{
    bool result = false;

    while (parcBuffer_Remaining(buffer) > 0) {
        uint8_t character = parcBuffer_GetUint8(buffer);
        if (memchr(bytesToSkipTo, character, length) != NULL) {
            parcBuffer_SetPosition(buffer, parcBuffer_Position(buffer) - 1);
            result = true;
            break;
        }
    }
    return result;
}

uint8_t
parcBuffer_PeekByte(const PARCBuffer *buffer)
{
    return parcBuffer_GetAtIndex(buffer, parcBuffer_Position(buffer));
}

uint64_t
parcBuffer_ParseHexNumber(PARCBuffer *buffer)
{
    char *bytes = parcBuffer_Overlay(buffer, 0);

    int start = 0;
    if (parcBuffer_Remaining(buffer) > 2) {
        if (bytes[0] == '0' && bytes[1] == 'x') {
            start = 2;
        }
    }

    unsigned count = 0;
    uint64_t result = 0;
    for (int i = start; i < parcBuffer_Remaining(buffer) && isxdigit(bytes[i]); i++) {
        result = (result * 16) + _digittoint(bytes[i]);
        count++;
    }

    parcBuffer_SetPosition(buffer, parcBuffer_Position(buffer) + start + count);

    return result;
}

uint64_t
parcBuffer_ParseDecimalNumber(PARCBuffer *buffer)
{
    char *bytes = parcBuffer_Overlay(buffer, 0);

    int start = 0;

    unsigned count = 0;
    uint64_t result = 0;
    for (int i = start; i < parcBuffer_Remaining(buffer) && isdigit(bytes[i]); i++) {
        result = (result * 10) + _digittoint(bytes[i]);
        count++;
    }

    parcBuffer_SetPosition(buffer, parcBuffer_Position(buffer) + count);

    return result;
}

uint64_t
parcBuffer_ParseNumeric(PARCBuffer *buffer)
{
    uint64_t result = 0;

    char *bytes = parcBuffer_Overlay(buffer, 0);

    if (parcBuffer_Remaining(buffer) > 2 && bytes[0] == '0' && bytes[1] == 'x') {
        result = parcBuffer_ParseHexNumber(buffer);
    } else {
        result = parcBuffer_ParseDecimalNumber(buffer);
    }

    return result;
}