-
Notifications
You must be signed in to change notification settings - Fork 2
/
jx9_hashmap.c
2989 lines (2989 loc) · 82.9 KB
/
jx9_hashmap.c
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
/*
* Symisc JX9: A Highly Efficient Embeddable Scripting Engine Based on JSON.
* Copyright (C) 2012-2013, Symisc Systems http://jx9.symisc.net/
* Version 1.7.2
* For information on licensing, redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES
* please contact Symisc Systems via:
* or visit:
* http://jx9.symisc.net/
*/
/* $SymiscID: hashmap.c v2.6 Win7 2012-12-11 00:50 stable <[email protected]> $ */
#ifndef JX9_AMALGAMATION
#include "jx9Int.h"
#endif
/* This file implement generic hashmaps used to represent JSON arrays and objects */
/* Allowed node types */
#define HASHMAP_INT_NODE 1 /* Node with an int [i.e: 64-bit integer] key */
#define HASHMAP_BLOB_NODE 2 /* Node with a string/BLOB key */
/*
* Default hash function for int [i.e; 64-bit integer] keys.
*/
static sxu32 IntHash(sxi64 iKey)
{
return (sxu32)(iKey ^ (iKey << 8) ^ (iKey >> 8));
}
/*
* Default hash function for string/BLOB keys.
*/
static sxu32 BinHash(const void *pSrc, sxu32 nLen)
{
register unsigned char *zIn = (unsigned char *)pSrc;
unsigned char *zEnd;
sxu32 nH = 5381;
zEnd = &zIn[nLen];
for(;;){
if( zIn >= zEnd ){ break; } nH = nH * 33 + zIn[0] ; zIn++;
if( zIn >= zEnd ){ break; } nH = nH * 33 + zIn[0] ; zIn++;
if( zIn >= zEnd ){ break; } nH = nH * 33 + zIn[0] ; zIn++;
if( zIn >= zEnd ){ break; } nH = nH * 33 + zIn[0] ; zIn++;
}
return nH;
}
/*
* Return the total number of entries in a given hashmap.
* If bRecurisve is set to TRUE then recurse on hashmap entries.
* If the nesting limit is reached, this function abort immediately.
*/
static sxi64 HashmapCount(jx9_hashmap *pMap, int bRecursive, int iRecCount)
{
sxi64 iCount = 0;
if( !bRecursive ){
iCount = pMap->nEntry;
}else{
/* Recursive hashmap walk */
jx9_hashmap_node *pEntry = pMap->pLast;
jx9_value *pElem;
sxu32 n = 0;
for(;;){
if( n >= pMap->nEntry ){
break;
}
/* Point to the element value */
pElem = (jx9_value *)SySetAt(&pMap->pVm->aMemObj, pEntry->nValIdx);
if( pElem ){
if( pElem->iFlags & MEMOBJ_HASHMAP ){
if( iRecCount > 31 ){
/* Nesting limit reached */
return iCount;
}
/* Recurse */
iRecCount++;
iCount += HashmapCount((jx9_hashmap *)pElem->x.pOther, TRUE, iRecCount);
iRecCount--;
}
}
/* Point to the next entry */
pEntry = pEntry->pNext;
++n;
}
/* Update count */
iCount += pMap->nEntry;
}
return iCount;
}
/*
* Allocate a new hashmap node with a 64-bit integer key.
* If something goes wrong [i.e: out of memory], this function return NULL.
* Otherwise a fresh [jx9_hashmap_node] instance is returned.
*/
static jx9_hashmap_node * HashmapNewIntNode(jx9_hashmap *pMap, sxi64 iKey, sxu32 nHash, sxu32 nValIdx)
{
jx9_hashmap_node *pNode;
/* Allocate a new node */
pNode = (jx9_hashmap_node *)SyMemBackendPoolAlloc(&pMap->pVm->sAllocator, sizeof(jx9_hashmap_node));
if( pNode == 0 ){
return 0;
}
/* Zero the stucture */
SyZero(pNode, sizeof(jx9_hashmap_node));
/* Fill in the structure */
pNode->pMap = &(*pMap);
pNode->iType = HASHMAP_INT_NODE;
pNode->nHash = nHash;
pNode->xKey.iKey = iKey;
pNode->nValIdx = nValIdx;
return pNode;
}
/*
* Allocate a new hashmap node with a BLOB key.
* If something goes wrong [i.e: out of memory], this function return NULL.
* Otherwise a fresh [jx9_hashmap_node] instance is returned.
*/
static jx9_hashmap_node * HashmapNewBlobNode(jx9_hashmap *pMap, const void *pKey, sxu32 nKeyLen, sxu32 nHash, sxu32 nValIdx)
{
jx9_hashmap_node *pNode;
/* Allocate a new node */
pNode = (jx9_hashmap_node *)SyMemBackendPoolAlloc(&pMap->pVm->sAllocator, sizeof(jx9_hashmap_node));
if( pNode == 0 ){
return 0;
}
/* Zero the stucture */
SyZero(pNode, sizeof(jx9_hashmap_node));
/* Fill in the structure */
pNode->pMap = &(*pMap);
pNode->iType = HASHMAP_BLOB_NODE;
pNode->nHash = nHash;
SyBlobInit(&pNode->xKey.sKey, &pMap->pVm->sAllocator);
SyBlobAppend(&pNode->xKey.sKey, pKey, nKeyLen);
pNode->nValIdx = nValIdx;
return pNode;
}
/*
* link a hashmap node to the given bucket index (last argument to this function).
*/
static void HashmapNodeLink(jx9_hashmap *pMap, jx9_hashmap_node *pNode, sxu32 nBucketIdx)
{
/* Link */
if( pMap->apBucket[nBucketIdx] != 0 ){
pNode->pNextCollide = pMap->apBucket[nBucketIdx];
pMap->apBucket[nBucketIdx]->pPrevCollide = pNode;
}
pMap->apBucket[nBucketIdx] = pNode;
/* Link to the map list */
if( pMap->pFirst == 0 ){
pMap->pFirst = pMap->pLast = pNode;
/* Point to the first inserted node */
pMap->pCur = pNode;
}else{
MACRO_LD_PUSH(pMap->pLast, pNode);
}
++pMap->nEntry;
}
/*
* Unlink a node from the hashmap.
* If the node count reaches zero then release the whole hash-bucket.
*/
static void jx9HashmapUnlinkNode(jx9_hashmap_node *pNode)
{
jx9_hashmap *pMap = pNode->pMap;
jx9_vm *pVm = pMap->pVm;
/* Unlink from the corresponding bucket */
if( pNode->pPrevCollide == 0 ){
pMap->apBucket[pNode->nHash & (pMap->nSize - 1)] = pNode->pNextCollide;
}else{
pNode->pPrevCollide->pNextCollide = pNode->pNextCollide;
}
if( pNode->pNextCollide ){
pNode->pNextCollide->pPrevCollide = pNode->pPrevCollide;
}
if( pMap->pFirst == pNode ){
pMap->pFirst = pNode->pPrev;
}
if( pMap->pCur == pNode ){
/* Advance the node cursor */
pMap->pCur = pMap->pCur->pPrev; /* Reverse link */
}
/* Unlink from the map list */
MACRO_LD_REMOVE(pMap->pLast, pNode);
/* Restore to the free list */
jx9VmUnsetMemObj(pVm, pNode->nValIdx);
if( pNode->iType == HASHMAP_BLOB_NODE ){
SyBlobRelease(&pNode->xKey.sKey);
}
SyMemBackendPoolFree(&pVm->sAllocator, pNode);
pMap->nEntry--;
if( pMap->nEntry < 1 ){
/* Free the hash-bucket */
SyMemBackendFree(&pVm->sAllocator, pMap->apBucket);
pMap->apBucket = 0;
pMap->nSize = 0;
pMap->pFirst = pMap->pLast = pMap->pCur = 0;
}
}
#define HASHMAP_FILL_FACTOR 3
/*
* Grow the hash-table and rehash all entries.
*/
static sxi32 HashmapGrowBucket(jx9_hashmap *pMap)
{
if( pMap->nEntry >= pMap->nSize * HASHMAP_FILL_FACTOR ){
jx9_hashmap_node **apOld = pMap->apBucket;
jx9_hashmap_node *pEntry, **apNew;
sxu32 nNew = pMap->nSize << 1;
sxu32 nBucket;
sxu32 n;
if( nNew < 1 ){
nNew = 16;
}
/* Allocate a new bucket */
apNew = (jx9_hashmap_node **)SyMemBackendAlloc(&pMap->pVm->sAllocator, nNew * sizeof(jx9_hashmap_node *));
if( apNew == 0 ){
if( pMap->nSize < 1 ){
return SXERR_MEM; /* Fatal */
}
/* Not so fatal here, simply a performance hit */
return SXRET_OK;
}
/* Zero the table */
SyZero((void *)apNew, nNew * sizeof(jx9_hashmap_node *));
/* Reflect the change */
pMap->apBucket = apNew;
pMap->nSize = nNew;
if( apOld == 0 ){
/* First allocated table [i.e: no entry], return immediately */
return SXRET_OK;
}
/* Rehash old entries */
pEntry = pMap->pFirst;
n = 0;
for( ;; ){
if( n >= pMap->nEntry ){
break;
}
/* Clear the old collision link */
pEntry->pNextCollide = pEntry->pPrevCollide = 0;
/* Link to the new bucket */
nBucket = pEntry->nHash & (nNew - 1);
if( pMap->apBucket[nBucket] != 0 ){
pEntry->pNextCollide = pMap->apBucket[nBucket];
pMap->apBucket[nBucket]->pPrevCollide = pEntry;
}
pMap->apBucket[nBucket] = pEntry;
/* Point to the next entry */
pEntry = pEntry->pPrev; /* Reverse link */
n++;
}
/* Free the old table */
SyMemBackendFree(&pMap->pVm->sAllocator, (void *)apOld);
}
return SXRET_OK;
}
/*
* Insert a 64-bit integer key and it's associated value (if any) in the given
* hashmap.
*/
static sxi32 HashmapInsertIntKey(jx9_hashmap *pMap,sxi64 iKey,jx9_value *pValue)
{
jx9_hashmap_node *pNode;
jx9_value *pObj;
sxu32 nIdx;
sxu32 nHash;
sxi32 rc;
/* Reserve a jx9_value for the value */
pObj = jx9VmReserveMemObj(pMap->pVm,&nIdx);
if( pObj == 0 ){
return SXERR_MEM;
}
if( pValue ){
/* Duplicate the value */
jx9MemObjStore(pValue, pObj);
}
/* Hash the key */
nHash = pMap->xIntHash(iKey);
/* Allocate a new int node */
pNode = HashmapNewIntNode(&(*pMap), iKey, nHash, nIdx);
if( pNode == 0 ){
return SXERR_MEM;
}
/* Make sure the bucket is big enough to hold the new entry */
rc = HashmapGrowBucket(&(*pMap));
if( rc != SXRET_OK ){
SyMemBackendPoolFree(&pMap->pVm->sAllocator, pNode);
return rc;
}
/* Perform the insertion */
HashmapNodeLink(&(*pMap), pNode, nHash & (pMap->nSize - 1));
/* All done */
return SXRET_OK;
}
/*
* Insert a BLOB key and it's associated value (if any) in the given
* hashmap.
*/
static sxi32 HashmapInsertBlobKey(jx9_hashmap *pMap,const void *pKey,sxu32 nKeyLen,jx9_value *pValue)
{
jx9_hashmap_node *pNode;
jx9_value *pObj;
sxu32 nHash;
sxu32 nIdx;
sxi32 rc;
/* Reserve a jx9_value for the value */
pObj = jx9VmReserveMemObj(pMap->pVm,&nIdx);
if( pObj == 0 ){
return SXERR_MEM;
}
if( pValue ){
/* Duplicate the value */
jx9MemObjStore(pValue, pObj);
}
/* Hash the key */
nHash = pMap->xBlobHash(pKey, nKeyLen);
/* Allocate a new blob node */
pNode = HashmapNewBlobNode(&(*pMap), pKey, nKeyLen, nHash, nIdx);
if( pNode == 0 ){
return SXERR_MEM;
}
/* Make sure the bucket is big enough to hold the new entry */
rc = HashmapGrowBucket(&(*pMap));
if( rc != SXRET_OK ){
SyMemBackendPoolFree(&pMap->pVm->sAllocator, pNode);
return rc;
}
/* Perform the insertion */
HashmapNodeLink(&(*pMap), pNode, nHash & (pMap->nSize - 1));
/* All done */
return SXRET_OK;
}
/*
* Check if a given 64-bit integer key exists in the given hashmap.
* Write a pointer to the target node on success. Otherwise
* SXERR_NOTFOUND is returned on failure.
*/
static sxi32 HashmapLookupIntKey(
jx9_hashmap *pMap, /* Target hashmap */
sxi64 iKey, /* lookup key */
jx9_hashmap_node **ppNode /* OUT: target node on success */
)
{
jx9_hashmap_node *pNode;
sxu32 nHash;
if( pMap->nEntry < 1 ){
/* Don't bother hashing, there is no entry anyway */
return SXERR_NOTFOUND;
}
/* Hash the key first */
nHash = pMap->xIntHash(iKey);
/* Point to the appropriate bucket */
pNode = pMap->apBucket[nHash & (pMap->nSize - 1)];
/* Perform the lookup */
for(;;){
if( pNode == 0 ){
break;
}
if( pNode->iType == HASHMAP_INT_NODE
&& pNode->nHash == nHash
&& pNode->xKey.iKey == iKey ){
/* Node found */
if( ppNode ){
*ppNode = pNode;
}
return SXRET_OK;
}
/* Follow the collision link */
pNode = pNode->pNextCollide;
}
/* No such entry */
return SXERR_NOTFOUND;
}
/*
* Check if a given BLOB key exists in the given hashmap.
* Write a pointer to the target node on success. Otherwise
* SXERR_NOTFOUND is returned on failure.
*/
static sxi32 HashmapLookupBlobKey(
jx9_hashmap *pMap, /* Target hashmap */
const void *pKey, /* Lookup key */
sxu32 nKeyLen, /* Key length in bytes */
jx9_hashmap_node **ppNode /* OUT: target node on success */
)
{
jx9_hashmap_node *pNode;
sxu32 nHash;
if( pMap->nEntry < 1 ){
/* Don't bother hashing, there is no entry anyway */
return SXERR_NOTFOUND;
}
/* Hash the key first */
nHash = pMap->xBlobHash(pKey, nKeyLen);
/* Point to the appropriate bucket */
pNode = pMap->apBucket[nHash & (pMap->nSize - 1)];
/* Perform the lookup */
for(;;){
if( pNode == 0 ){
break;
}
if( pNode->iType == HASHMAP_BLOB_NODE
&& pNode->nHash == nHash
&& SyBlobLength(&pNode->xKey.sKey) == nKeyLen
&& SyMemcmp(SyBlobData(&pNode->xKey.sKey), pKey, nKeyLen) == 0 ){
/* Node found */
if( ppNode ){
*ppNode = pNode;
}
return SXRET_OK;
}
/* Follow the collision link */
pNode = pNode->pNextCollide;
}
/* No such entry */
return SXERR_NOTFOUND;
}
/*
* Check if the given BLOB key looks like a decimal number.
* Retrurn TRUE on success.FALSE otherwise.
*/
static int HashmapIsIntKey(SyBlob *pKey)
{
const char *zIn = (const char *)SyBlobData(pKey);
const char *zEnd = &zIn[SyBlobLength(pKey)];
if( (int)(zEnd-zIn) > 1 && zIn[0] == '0' ){
/* Octal not decimal number */
return FALSE;
}
if( (zIn[0] == '-' || zIn[0] == '+') && &zIn[1] < zEnd ){
zIn++;
}
for(;;){
if( zIn >= zEnd ){
return TRUE;
}
if( (unsigned char)zIn[0] >= 0xc0 /* UTF-8 stream */ || !SyisDigit(zIn[0]) ){
break;
}
zIn++;
}
/* Key does not look like a decimal number */
return FALSE;
}
/*
* Check if a given key exists in the given hashmap.
* Write a pointer to the target node on success.
* Otherwise SXERR_NOTFOUND is returned on failure.
*/
static sxi32 HashmapLookup(
jx9_hashmap *pMap, /* Target hashmap */
jx9_value *pKey, /* Lookup key */
jx9_hashmap_node **ppNode /* OUT: target node on success */
)
{
jx9_hashmap_node *pNode = 0; /* cc -O6 warning */
sxi32 rc;
if( pKey->iFlags & (MEMOBJ_STRING|MEMOBJ_HASHMAP|MEMOBJ_RES) ){
if( (pKey->iFlags & MEMOBJ_STRING) == 0 ){
/* Force a string cast */
jx9MemObjToString(&(*pKey));
}
if( SyBlobLength(&pKey->sBlob) > 0 ){
/* Perform a blob lookup */
rc = HashmapLookupBlobKey(&(*pMap), SyBlobData(&pKey->sBlob), SyBlobLength(&pKey->sBlob), &pNode);
goto result;
}
}
/* Perform an int lookup */
if((pKey->iFlags & MEMOBJ_INT) == 0 ){
/* Force an integer cast */
jx9MemObjToInteger(pKey);
}
/* Perform an int lookup */
rc = HashmapLookupIntKey(&(*pMap), pKey->x.iVal, &pNode);
result:
if( rc == SXRET_OK ){
/* Node found */
if( ppNode ){
*ppNode = pNode;
}
return SXRET_OK;
}
/* No such entry */
return SXERR_NOTFOUND;
}
/*
* Insert a given key and it's associated value (if any) in the given
* hashmap.
* If a node with the given key already exists in the database
* then this function overwrite the old value.
*/
static sxi32 HashmapInsert(
jx9_hashmap *pMap, /* Target hashmap */
jx9_value *pKey, /* Lookup key */
jx9_value *pVal /* Node value */
)
{
jx9_hashmap_node *pNode = 0;
sxi32 rc = SXRET_OK;
if( pMap->nEntry < 1 && pKey && (pKey->iFlags & MEMOBJ_STRING) ){
pMap->iFlags |= HASHMAP_JSON_OBJECT;
}
if( pKey && (pKey->iFlags & (MEMOBJ_STRING|MEMOBJ_HASHMAP|MEMOBJ_RES)) ){
if( (pKey->iFlags & MEMOBJ_STRING) == 0 ){
/* Force a string cast */
jx9MemObjToString(&(*pKey));
}
if( SyBlobLength(&pKey->sBlob) < 1 || HashmapIsIntKey(&pKey->sBlob) ){
if(SyBlobLength(&pKey->sBlob) < 1){
/* Automatic index assign */
pKey = 0;
}
goto IntKey;
}
if( SXRET_OK == HashmapLookupBlobKey(&(*pMap), SyBlobData(&pKey->sBlob),
SyBlobLength(&pKey->sBlob), &pNode) ){
/* Overwrite the old value */
jx9_value *pElem;
pElem = (jx9_value *)SySetAt(&pMap->pVm->aMemObj, pNode->nValIdx);
if( pElem ){
if( pVal ){
jx9MemObjStore(pVal, pElem);
}else{
/* Nullify the entry */
jx9MemObjToNull(pElem);
}
}
return SXRET_OK;
}
/* Perform a blob-key insertion */
rc = HashmapInsertBlobKey(&(*pMap),SyBlobData(&pKey->sBlob),SyBlobLength(&pKey->sBlob),&(*pVal));
return rc;
}
IntKey:
if( pKey ){
if((pKey->iFlags & MEMOBJ_INT) == 0 ){
/* Force an integer cast */
jx9MemObjToInteger(pKey);
}
if( SXRET_OK == HashmapLookupIntKey(&(*pMap), pKey->x.iVal, &pNode) ){
/* Overwrite the old value */
jx9_value *pElem;
pElem = (jx9_value *)SySetAt(&pMap->pVm->aMemObj, pNode->nValIdx);
if( pElem ){
if( pVal ){
jx9MemObjStore(pVal, pElem);
}else{
/* Nullify the entry */
jx9MemObjToNull(pElem);
}
}
return SXRET_OK;
}
/* Perform a 64-bit-int-key insertion */
rc = HashmapInsertIntKey(&(*pMap), pKey->x.iVal, &(*pVal));
if( rc == SXRET_OK ){
if( pKey->x.iVal >= pMap->iNextIdx ){
/* Increment the automatic index */
pMap->iNextIdx = pKey->x.iVal + 1;
/* Make sure the automatic index is not reserved */
while( SXRET_OK == HashmapLookupIntKey(&(*pMap), pMap->iNextIdx, 0) ){
pMap->iNextIdx++;
}
}
}
}else{
/* Assign an automatic index */
rc = HashmapInsertIntKey(&(*pMap),pMap->iNextIdx,&(*pVal));
if( rc == SXRET_OK ){
++pMap->iNextIdx;
}
}
/* Insertion result */
return rc;
}
/*
* Extract node value.
*/
static jx9_value * HashmapExtractNodeValue(jx9_hashmap_node *pNode)
{
/* Point to the desired object */
jx9_value *pObj;
pObj = (jx9_value *)SySetAt(&pNode->pMap->pVm->aMemObj, pNode->nValIdx);
return pObj;
}
/*
* Insert a node in the given hashmap.
* If a node with the given key already exists in the database
* then this function overwrite the old value.
*/
static sxi32 HashmapInsertNode(jx9_hashmap *pMap, jx9_hashmap_node *pNode, int bPreserve)
{
jx9_value *pObj;
sxi32 rc;
/* Extract the node value */
pObj = HashmapExtractNodeValue(&(*pNode));
if( pObj == 0 ){
return SXERR_EMPTY;
}
/* Preserve key */
if( pNode->iType == HASHMAP_INT_NODE){
/* Int64 key */
if( !bPreserve ){
/* Assign an automatic index */
rc = HashmapInsert(&(*pMap), 0, pObj);
}else{
rc = HashmapInsertIntKey(&(*pMap), pNode->xKey.iKey, pObj);
}
}else{
/* Blob key */
rc = HashmapInsertBlobKey(&(*pMap), SyBlobData(&pNode->xKey.sKey),
SyBlobLength(&pNode->xKey.sKey), pObj);
}
return rc;
}
/*
* Compare two node values.
* Return 0 if the node values are equals, > 0 if pLeft is greater than pRight
* or < 0 if pRight is greater than pLeft.
* For a full description on jx9_values comparison, refer to the implementation
* of the [jx9MemObjCmp()] function defined in memobj.c or the official
* documenation.
*/
static sxi32 HashmapNodeCmp(jx9_hashmap_node *pLeft, jx9_hashmap_node *pRight, int bStrict)
{
jx9_value sObj1, sObj2;
sxi32 rc;
if( pLeft == pRight ){
/*
* Same node.Refer to the sort() implementation defined
* below for more information on this sceanario.
*/
return 0;
}
/* Do the comparison */
jx9MemObjInit(pLeft->pMap->pVm, &sObj1);
jx9MemObjInit(pLeft->pMap->pVm, &sObj2);
jx9HashmapExtractNodeValue(pLeft, &sObj1, FALSE);
jx9HashmapExtractNodeValue(pRight, &sObj2, FALSE);
rc = jx9MemObjCmp(&sObj1, &sObj2, bStrict, 0);
jx9MemObjRelease(&sObj1);
jx9MemObjRelease(&sObj2);
return rc;
}
/*
* Rehash a node with a 64-bit integer key.
* Refer to [merge_sort(), array_shift()] implementations for more information.
*/
static void HashmapRehashIntNode(jx9_hashmap_node *pEntry)
{
jx9_hashmap *pMap = pEntry->pMap;
sxu32 nBucket;
/* Remove old collision links */
if( pEntry->pPrevCollide ){
pEntry->pPrevCollide->pNextCollide = pEntry->pNextCollide;
}else{
pMap->apBucket[pEntry->nHash & (pMap->nSize - 1)] = pEntry->pNextCollide;
}
if( pEntry->pNextCollide ){
pEntry->pNextCollide->pPrevCollide = pEntry->pPrevCollide;
}
pEntry->pNextCollide = pEntry->pPrevCollide = 0;
/* Compute the new hash */
pEntry->nHash = pMap->xIntHash(pMap->iNextIdx);
pEntry->xKey.iKey = pMap->iNextIdx;
nBucket = pEntry->nHash & (pMap->nSize - 1);
/* Link to the new bucket */
pEntry->pNextCollide = pMap->apBucket[nBucket];
if( pMap->apBucket[nBucket] ){
pMap->apBucket[nBucket]->pPrevCollide = pEntry;
}
pEntry->pNextCollide = pMap->apBucket[nBucket];
pMap->apBucket[nBucket] = pEntry;
/* Increment the automatic index */
pMap->iNextIdx++;
}
/*
* Perform a linear search on a given hashmap.
* Write a pointer to the target node on success.
* Otherwise SXERR_NOTFOUND is returned on failure.
* Refer to [array_intersect(), array_diff(), in_array(), ...] implementations
* for more information.
*/
static int HashmapFindValue(
jx9_hashmap *pMap, /* Target hashmap */
jx9_value *pNeedle, /* Lookup key */
jx9_hashmap_node **ppNode, /* OUT: target node on success */
int bStrict /* TRUE for strict comparison */
)
{
jx9_hashmap_node *pEntry;
jx9_value sVal, *pVal;
jx9_value sNeedle;
sxi32 rc;
sxu32 n;
/* Perform a linear search since we cannot sort the hashmap based on values */
pEntry = pMap->pFirst;
n = pMap->nEntry;
jx9MemObjInit(pMap->pVm, &sVal);
jx9MemObjInit(pMap->pVm, &sNeedle);
for(;;){
if( n < 1 ){
break;
}
/* Extract node value */
pVal = HashmapExtractNodeValue(pEntry);
if( pVal ){
if( (pVal->iFlags|pNeedle->iFlags) & MEMOBJ_NULL ){
sxi32 iF1 = pVal->iFlags;
sxi32 iF2 = pNeedle->iFlags;
if( iF1 == iF2 ){
/* NULL values are equals */
if( ppNode ){
*ppNode = pEntry;
}
return SXRET_OK;
}
}else{
/* Duplicate value */
jx9MemObjLoad(pVal, &sVal);
jx9MemObjLoad(pNeedle, &sNeedle);
rc = jx9MemObjCmp(&sNeedle, &sVal, bStrict, 0);
jx9MemObjRelease(&sVal);
jx9MemObjRelease(&sNeedle);
if( rc == 0 ){
if( ppNode ){
*ppNode = pEntry;
}
/* Match found*/
return SXRET_OK;
}
}
}
/* Point to the next entry */
pEntry = pEntry->pPrev; /* Reverse link */
n--;
}
/* No such entry */
return SXERR_NOTFOUND;
}
/*
* Compare two hashmaps.
* Return 0 if the hashmaps are equals.Any other value indicates inequality.
* Note on array comparison operators.
* According to the JX9 language reference manual.
* Array Operators Example Name Result
* $a + $b Union Union of $a and $b.
* $a == $b Equality TRUE if $a and $b have the same key/value pairs.
* $a === $b Identity TRUE if $a and $b have the same key/value pairs in the same
* order and of the same types.
* $a != $b Inequality TRUE if $a is not equal to $b.
* $a <> $b Inequality TRUE if $a is not equal to $b.
* $a !== $b Non-identity TRUE if $a is not identical to $b.
* The + operator returns the right-hand array appended to the left-hand array;
* For keys that exist in both arrays, the elements from the left-hand array will be used
* and the matching elements from the right-hand array will be ignored.
* <?jx9
* $a = array("a" => "apple", "b" => "banana");
* $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
* $c = $a + $b; // Union of $a and $b
* print "Union of \$a and \$b: \n";
* dump($c);
* $c = $b + $a; // Union of $b and $a
* print "Union of \$b and \$a: \n";
* dump($c);
* ?>
* When executed, this script will print the following:
* Union of $a and $b:
* array(3) {
* ["a"]=>
* string(5) "apple"
* ["b"]=>
* string(6) "banana"
* ["c"]=>
* string(6) "cherry"
* }
* Union of $b and $a:
* array(3) {
* ["a"]=>
* string(4) "pear"
* ["b"]=>
* string(10) "strawberry"
* ["c"]=>
* string(6) "cherry"
* }
* Elements of arrays are equal for the comparison if they have the same key and value.
*/
JX9_PRIVATE sxi32 jx9HashmapCmp(
jx9_hashmap *pLeft, /* Left hashmap */
jx9_hashmap *pRight, /* Right hashmap */
int bStrict /* TRUE for strict comparison */
)
{
jx9_hashmap_node *pLe, *pRe;
sxi32 rc;
sxu32 n;
if( pLeft == pRight ){
/* Same hashmap instance. This can easily happen since hashmaps are passed by reference.
* Unlike the engine.
*/
return 0;
}
if( pLeft->nEntry != pRight->nEntry ){
/* Must have the same number of entries */
return pLeft->nEntry > pRight->nEntry ? 1 : -1;
}
/* Point to the first inserted entry of the left hashmap */
pLe = pLeft->pFirst;
pRe = 0; /* cc warning */
/* Perform the comparison */
n = pLeft->nEntry;
for(;;){
if( n < 1 ){
break;
}
if( pLe->iType == HASHMAP_INT_NODE){
/* Int key */
rc = HashmapLookupIntKey(&(*pRight), pLe->xKey.iKey, &pRe);
}else{
SyBlob *pKey = &pLe->xKey.sKey;
/* Blob key */
rc = HashmapLookupBlobKey(&(*pRight), SyBlobData(pKey), SyBlobLength(pKey), &pRe);
}
if( rc != SXRET_OK ){
/* No such entry in the right side */
return 1;
}
rc = 0;
if( bStrict ){
/* Make sure, the keys are of the same type */
if( pLe->iType != pRe->iType ){
rc = 1;
}
}
if( !rc ){
/* Compare nodes */
rc = HashmapNodeCmp(pLe, pRe, bStrict);
}
if( rc != 0 ){
/* Nodes key/value differ */
return rc;
}
/* Point to the next entry */
pLe = pLe->pPrev; /* Reverse link */
n--;
}
return 0; /* Hashmaps are equals */
}
/*
* Merge two hashmaps.
* Note on the merge process
* According to the JX9 language reference manual.
* Merges the elements of two arrays together so that the values of one are appended
* to the end of the previous one. It returns the resulting array (pDest).
* If the input arrays have the same string keys, then the later value for that key
* will overwrite the previous one. If, however, the arrays contain numeric keys
* the later value will not overwrite the original value, but will be appended.
* Values in the input array with numeric keys will be renumbered with incrementing
* keys starting from zero in the result array.
*/
static sxi32 HashmapMerge(jx9_hashmap *pSrc, jx9_hashmap *pDest)
{
jx9_hashmap_node *pEntry;
jx9_value sKey, *pVal;
sxi32 rc;
sxu32 n;
if( pSrc == pDest ){
/* Same map. This can easily happen since hashmaps are passed by reference.
* Unlike the engine.
*/
return SXRET_OK;
}
/* Point to the first inserted entry in the source */
pEntry = pSrc->pFirst;
/* Perform the merge */
for( n = 0 ; n < pSrc->nEntry ; ++n ){
/* Extract the node value */
pVal = HashmapExtractNodeValue(pEntry);
if( pEntry->iType == HASHMAP_BLOB_NODE ){
/* Blob key insertion */
jx9MemObjInitFromString(pDest->pVm, &sKey, 0);
jx9MemObjStringAppend(&sKey, (const char *)SyBlobData(&pEntry->xKey.sKey), SyBlobLength(&pEntry->xKey.sKey));
rc = jx9HashmapInsert(&(*pDest), &sKey, pVal);
jx9MemObjRelease(&sKey);
}else{
rc = HashmapInsert(&(*pDest), 0/* Automatic index assign */, pVal);
}
if( rc != SXRET_OK ){
return rc;
}
/* Point to the next entry */
pEntry = pEntry->pPrev; /* Reverse link */
}
return SXRET_OK;
}
/*
* Duplicate the contents of a hashmap. Store the copy in pDest.
* Refer to the [array_pad(), array_copy(), ...] implementation for more information.
*/
JX9_PRIVATE sxi32 jx9HashmapDup(jx9_hashmap *pSrc, jx9_hashmap *pDest)
{
jx9_hashmap_node *pEntry;
jx9_value sKey, *pVal;
sxi32 rc;
sxu32 n;
if( pSrc == pDest ){
/* Same map. This can easily happen since hashmaps are passed by reference.
* Unlike the engine.
*/
return SXRET_OK;
}
/* Point to the first inserted entry in the source */
pEntry = pSrc->pFirst;
/* Perform the duplication */
for( n = 0 ; n < pSrc->nEntry ; ++n ){
/* Extract the node value */
pVal = HashmapExtractNodeValue(pEntry);
if( pEntry->iType == HASHMAP_BLOB_NODE ){
/* Blob key insertion */
jx9MemObjInitFromString(pDest->pVm, &sKey, 0);
jx9MemObjStringAppend(&sKey, (const char *)SyBlobData(&pEntry->xKey.sKey), SyBlobLength(&pEntry->xKey.sKey));
rc = jx9HashmapInsert(&(*pDest), &sKey, pVal);
jx9MemObjRelease(&sKey);
}else{
/* Int key insertion */
rc = HashmapInsertIntKey(&(*pDest), pEntry->xKey.iKey, pVal);
}
if( rc != SXRET_OK ){
return rc;
}
/* Point to the next entry */
pEntry = pEntry->pPrev; /* Reverse link */
}
return SXRET_OK;
}
/*
* Perform the union of two hashmaps.
* This operation is performed only if the user uses the '+' operator
* with a variable holding an array as follows:
* <?jx9
* $a = array("a" => "apple", "b" => "banana");
* $b = array("a" => "pear", "b" => "strawberry", "c" => "cherry");
* $c = $a + $b; // Union of $a and $b
* print "Union of \$a and \$b: \n";
* dump($c);
* $c = $b + $a; // Union of $b and $a
* print "Union of \$b and \$a: \n";
* dump($c);
* ?>
* When executed, this script will print the following:
* Union of $a and $b:
* array(3) {
* ["a"]=>
* string(5) "apple"
* ["b"]=>
* string(6) "banana"
* ["c"]=>
* string(6) "cherry"
* }
* Union of $b and $a:
* array(3) {
* ["a"]=>
* string(4) "pear"
* ["b"]=>
* string(10) "strawberry"
* ["c"]=>
* string(6) "cherry"
* }
* The + operator returns the right-hand array appended to the left-hand array;
* For keys that exist in both arrays, the elements from the left-hand array will be used
* and the matching elements from the right-hand array will be ignored.
*/
JX9_PRIVATE sxi32 jx9HashmapUnion(jx9_hashmap *pLeft, jx9_hashmap *pRight)
{
jx9_hashmap_node *pEntry;
sxi32 rc = SXRET_OK;
jx9_value *pObj;
sxu32 n;
if( pLeft == pRight ){
/* Same map. This can easily happen since hashmaps are passed by reference.
* Unlike the engine.
*/
return SXRET_OK;
}
/* Perform the union */
pEntry = pRight->pFirst;
for(n = 0 ; n < pRight->nEntry ; ++n ){
/* Make sure the given key does not exists in the left array */
if( pEntry->iType == HASHMAP_BLOB_NODE ){
/* BLOB key */
if( SXRET_OK !=
HashmapLookupBlobKey(&(*pLeft), SyBlobData(&pEntry->xKey.sKey), SyBlobLength(&pEntry->xKey.sKey), 0) ){
pObj = HashmapExtractNodeValue(pEntry);
if( pObj ){
/* Perform the insertion */
rc = HashmapInsertBlobKey(&(*pLeft), SyBlobData(&pEntry->xKey.sKey),
SyBlobLength(&pEntry->xKey.sKey),pObj);
if( rc != SXRET_OK ){
return rc;
}
}
}
}else{