forked from ldmud/ldmud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray.c
3547 lines (3010 loc) · 101 KB
/
array.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
/*---------------------------------------------------------------------------
* Array handling functions.
*
*---------------------------------------------------------------------------
* TODO: Rewrite the low-level functions (like allocate_array()) to return
* TODO:: failure codes (errno like) instead of throwing errors. In addition,
* TODO:: provide wrapper functions which do throw errorf()s, so that every
* TODO:: caller can handle the errors himself (like the swapper).
* The structure of an array ("vector") is defined in datatypes.h as this:
*
* vector_t_s {
* p_int size;
* p_int ref;
* p_int extra_ref; (ifdef DEBUG)
* wiz_list_t *user;
* svalue_t item[1...];
* };
*
* .size is the number of elements in the vector.
*
* .ref is the number of references to the vector. If this number
* reaches 0, the vector can (and should) be deallocated. This scheme
* breaks down with circular references, but those are caught by
* the garbage collector.
*
* .extra_ref exists when the driver is compiled for DEBUGging, and
* is used to countercheck the the .ref count.
*
* .user records which wizard's object created the vector, and is used
* to keep the wizlist statistics (array usage) up to date.
*
* .item[] is the array of elements in indexing order. The structure
* itself declares just an array of one element, it is task of the user
* to allocated a big enough memory block.
*
*
* Some macros help with the use of vector variables:
*
* VEC_SIZE(v): Return the number of elements in v.
*
* VEC_HEAD(size): Expand to the initializers of a vector with
* <size> elements and 1 ref. This does not include the
* element initialisers.
*
* This module contains both low-level and efun-level functions.
* The latter are collected in the lower half of the source.
*---------------------------------------------------------------------------
*/
#include "driver.h"
#include "typedefs.h"
#include "my-alloca.h"
#include <assert.h>
#include <stddef.h>
#include "array.h"
#include "backend.h"
#include "closure.h" /* closure_cmp(), closure_eq() */
#include "interpret.h"
#include "main.h"
#include "mapping.h"
#include "mempools.h"
#include "mstrings.h"
#include "object.h"
#include "stdstrings.h"
#include "simulate.h"
#include "svalue.h"
#include "swap.h"
#include "wiz_list.h"
#include "xalloc.h"
#include "i-current_object.h"
#include "i-svalue_cmp.h"
/*-------------------------------------------------------------------------*/
#define ALLOC_VECTOR(nelem) \
((size_t)nelem > (SSIZE_MAX - sizeof(vector_t)) / sizeof(svalue_t)) \
? NULL \
: (vector_t *)xalloc_pass(sizeof(vector_t) + \
sizeof(svalue_t) * (nelem))
/* ALLOC_VECTOR(size,file,line): Allocate dynamically the memory for
* a vector of <size> elements.
* TODO: Use SIZET_MAX instead of SSIZE_MAX, see port.h
*/
/*-------------------------------------------------------------------------*/
int num_arrays;
/* Total number of allocated arrays */
vector_t null_vector = { VEC_HEAD(0) };
/* The global empty array ({}).
* Reusing it is cheaper than repeated allocations/deallocations.
*/
void (*allocate_array_error_handler) (const char *, ...)
= errorf; /* from simulate.c */
/* This handler is called if an allocation fails.
* Usually it points to simulate::errorf(), but the swapper
* replaces it temporarily with its own dummy handler when
* swapping in an object.
*/
/*-------------------------------------------------------------------------*/
vector_t *
_allocate_array(mp_int n MTRACE_DECL)
/* Allocate an array for <n> elements (but not more than the current
* maximum) and return the pointer.
* The elements are initialised to the svalue 0.
*
* If the allocations fails (and errorf() does return), a 0 pointer
* may be returned. This is usually only possible when arrays
* are allocated from the swapper.
*
* Allocating an array of size 0 will return a reference to the
* globally shared empty array.
*
* If possible, annotate the allocations with <malloc_trace> and <...line>
*/
{
mp_int i;
vector_t *p;
svalue_t *svp;
if (n < 0 || (max_array_size && (size_t)n > max_array_size))
errorf("Illegal array size: %"PRIdMPINT".\n", n);
if (n == 0) {
p = ref_array(&null_vector);
return p;
}
num_arrays++;
p = ALLOC_VECTOR(n);
if (!p) {
#ifndef MALLOC_TRACE
(*allocate_array_error_handler)
("Out of memory: array[%"PRIdMPINT"]\n", n);
#else
(*allocate_array_error_handler)
("(%s:%d) Out of memory: array[%"PRIdMPINT"]\n"
MTRACE_PASS, n);
#endif
return 0;
}
p->ref = 1;
p->size = n;
p->user = get_current_user();
if (!p->user)
p->user = &default_wizlist_entry;
p->user->size_array += n;
svp = p->item;
for (i = n; --i >= 0; )
*svp++ = const0;
return p;
}
/*-------------------------------------------------------------------------*/
vector_t *
_allocate_array_unlimited(mp_int n MTRACE_DECL)
/* Allocate an array for <n> elements and return the pointer.
* The elements are initialised to the svalue 0.
*
* If the allocations fails (and errorf() does return), a 0 pointer
* may be returned. This is usually only possible when arrays
* are allocated from the swapper.
*
* Allocating an array of size 0 will return a reference to the
* globally shared empty array.
*
* If possible, annotate the allocations with <malloc_trace_file> and <...line>
*/
{
mp_int i;
vector_t *p;
svalue_t *svp;
if (n < 0)
errorf("Illegal array size: %"PRIdMPINT".\n", n);
if (n == 0) {
p = ref_array(&null_vector);
return p;
}
num_arrays++;
p = ALLOC_VECTOR(n);
if (!p) {
#ifndef MALLOC_TRACE
(*allocate_array_error_handler)
("Out of memory: unlimited array[%"PRIdMPINT"]\n", n);
#else
(*allocate_array_error_handler)
("(%s:%d) Out of memory: unlimited array[%"PRIdMPINT"]\n"
MTRACE_PASS, n);
#endif
return 0;
}
p->ref = 1;
p->size = n;
p->user = get_current_user();
if (!p->user)
p->user = &default_wizlist_entry;
p->user->size_array += n;
svp = p->item;
for (i = n; --i >= 0; )
*svp++ = const0;
return p;
}
/*-------------------------------------------------------------------------*/
vector_t *
_allocate_uninit_array (mp_int n MTRACE_DECL)
/* Allocate an array for <n> elements (but no more than the current
* maximum) and return the pointer.
* The elements are not initialised.
* If the allocations fails (and errorf() does return), a 0 pointer
* may be returned.
*
* Allocating an array of size 0 will return a reference to the
* globally shared empty array.
*
* If possible, annotate the allocations with <malloc_trace_file> and <...line>
*/
{
vector_t *p;
if (n < 0 || (max_array_size && (size_t)n > max_array_size))
errorf("Illegal array size: %"PRIdMPINT".\n", n);
if (n == 0) {
p = ref_array(&null_vector);
return p;
}
num_arrays++;
p = ALLOC_VECTOR(n);
if (!p) {
#ifndef MALLOC_TRACE
(*allocate_array_error_handler)
("Out of memory: uninited array[%"PRIdMPINT"]\n", n);
#else
(*allocate_array_error_handler)
("(%s:%d) Out of memory: uninited array[%"PRIdMPINT"]\n"
MTRACE_PASS, n);
#endif
return 0;
}
p->ref = 1;
p->size = n;
p->user = get_current_user();
if (!p->user)
p->user = &default_wizlist_entry;
p->user->size_array += n;
return p;
}
/*-------------------------------------------------------------------------*/
void
_free_vector (vector_t *p)
/* Deallocate the vector <p>, properly freeing the contained elements.
* The refcount is supposed to be zero at the time of call.
*/
{
mp_uint i;
svalue_t *svp;
#ifdef DEBUG
if (p->ref > 0)
fatal("Vector with %"PRIdPINT" refs passed to _free_vector()\n",
p->ref);
if (p == &null_vector)
fatal("Tried to free the zero-size shared vector.\n");
#endif
i = VEC_SIZE(p);
num_arrays--;
p->user->size_array -= i;
svp = p->item;
do {
free_svalue(svp++);
} while (--i);
xfree(p);
} /* _free_vector() */
/*-------------------------------------------------------------------------*/
void
free_empty_vector (vector_t *p)
/* Deallocate the vector <p> without regard of refcount or contained
* elements. Just the statistics are cared for.
*/
{
mp_uint i;
i = VEC_SIZE(p);
p->user->size_array -= i;
num_arrays--;
xfree((char *)p);
}
/*-------------------------------------------------------------------------*/
void
check_for_destr (vector_t *v)
/* Check the vector <v> for destructed objects and closures on destructed
* objects and replace them with svalue 0s. Subvectors are not checked,
* though.
*
* This function is used by certain efuns (parse_command(), unique_array(),
* map_array()) to make sure that the data passed to the efuns is valid,
* avoiding game crashes (though this won't happen on simple operations
* like assign_svalue).
* TODO: The better way is to make the affected efuns resistant against
* TODO:: destructed objects, and keeping this only as a safeguard and
* TODO:: to save memory.
*/
{
mp_int i;
svalue_t *p;
for (p = v->item, i = (mp_int)VEC_SIZE(v); --i >= 0 ; p++ )
{
if (destructed_object_ref(p))
assign_svalue(p, &const0);
}
} /* check_for_destr() */
/*-------------------------------------------------------------------------*/
long
total_array_size (void)
/* Statistics for the command 'status [tables]'.
* Return the total memory used for all vectors in the game.
*/
{
wiz_list_t *wl;
long total;
total = default_wizlist_entry.size_array;
for (wl = all_wiz; wl; wl = wl->next)
total += wl->size_array;
total *= sizeof(svalue_t);
total += num_arrays * sizeof(vector_t);
return total;
}
/*-------------------------------------------------------------------------*/
#if defined(GC_SUPPORT)
void
clear_array_size (void)
/* Clear the statistics about the number and memory usage of all vectors
* in the game.
*/
{
wiz_list_t *wl;
num_arrays = 0;
default_wizlist_entry.size_array = 0;
for (wl = all_wiz; wl; wl = wl->next)
wl->size_array = 0;
} /* clear_array_size(void) */
/*-------------------------------------------------------------------------*/
void
count_array_size (vector_t *vec)
/* Add the vector <vec> to the statistics.
*/
{
num_arrays++;
vec->user->size_array += VEC_SIZE(vec);
} /* count_array_size(void) */
#endif /* GC_SUPPORT */
/*-------------------------------------------------------------------------*/
vector_t *
explode_string (string_t *str, string_t *del)
/* Explode the string <str> by delimiter string <del> and return an array
* of the (unshared) strings found between the delimiters.
* They are unshared because they are most likely short-lived.
*
* TODO: At some later point in the execution thread, all the longlived
* unshared strings should maybe be converted into shared strings.
*
* This is the new, logical behaviour: nothing is assumed.
* The relation implode(explode(x,y),y) == x holds.
*
* explode("xyz", "") -> { "x", "y", "z" }
* explode("###", "##") -> { "", "#" }
* explode(" the fox ", " ") -> { "", "the", "", "", "fox", ""}
* explode("", whatever) -> { "" }
*/
{
char *p, *beg;
long num;
long len, left;
vector_t *ret;
string_t *buff;
const ph_int stringtype = (str->info.unicode == STRING_BYTES) ? T_BYTES : T_STRING;
/* Special case: str is an empty string. */
if (mstrsize(str) == 0)
{
ret = allocate_array(1);
ret->item->u.str = new_n_mstring("", 0, str->info.unicode);
ret->item->type = stringtype;
return ret;
}
len = (long)mstrsize(del);
/* Delimiter is empty: return an array which holds all characters as
* single-character strings.
*/
if (len < 1)
{
svalue_t *svp;
if (str->info.unicode == STRING_UTF8)
{
size_t size = mstrsize(str);
bool error = false;
len = byte_to_char_index(get_txt(str), size, &error);
if (error)
errorf("Invalid character in string at byte %ld.\n", len);
ret = allocate_array(len);
for (svp = ret->item, p = get_txt(str); size > 0; svp++)
{
size_t chlen = char_to_byte_index(p, size, 1, &error);
if (!chlen)
chlen = 1;
buff = new_n_mstring(p, chlen, chlen == 1 ? STRING_ASCII : STRING_UTF8);
if (!buff)
{
free_array(ret);
outofmem(1, "explode() on a string");
}
put_string(svp, buff);
p += chlen;
size -= chlen;
}
}
else
{
len = (long)mstrsize(str);
ret = allocate_array(len);
for ( svp = ret->item, p = get_txt(str)
; --len >= 0
; svp++, p++ )
{
buff = new_n_mstring(p, 1, str->info.unicode);
if (!buff)
{
free_array(ret);
outofmem(1, "explode() on a string");
}
svp->u.str = buff;
svp->type = stringtype;
}
}
return ret;
}
if (len <= 1)
{
/* Delimiter is one-char string: speedy implementation which uses
* direct character comparisons instead of calls to memcmp().
*/
char c;
char * txt;
svalue_t *svp;
txt = get_txt(str);
len = (long)mstrsize(str);
c = get_txt(del)[0];
/* TODO: Remember positions here */
/* Determine the number of delimiters in the string. */
for (num = 1, p = txt
; p < txt + len && NULL != (p = memchr(p, c, len - (p - txt)))
; p++, num++) NOOP;
ret = allocate_array(num);
for ( svp = ret->item, left = len
; NULL != (p = memchr(txt, c, left))
; left -= (p + 1 - txt), txt = p + 1, svp++)
{
len = p - txt;
buff = new_n_mstring(txt, (size_t)len, str->info.unicode);
if (!buff)
{
free_array(ret);
outofmem(len, "explode() on a string");
}
svp->u.str = buff;
svp->type = stringtype;
}
/* txt now points to the (possibly empty) remains after
* the last delimiter.
*/
len = get_txt(str) + mstrsize(str) - txt;
buff = new_n_mstring(txt, (size_t)len, str->info.unicode);
if (!buff)
{
free_array(ret);
outofmem(len, "explode() on a string");
}
if (buff->info.unicode == STRING_UTF8 && is_ascii(txt, len))
buff->info.unicode = STRING_ASCII;
svp->u.str = buff;
svp->type = stringtype;
return ret;
}
/* Find the number of occurrences of the delimiter 'del' by doing
* a first scan of the string.
*
* The number of array items is then one more than the number of
* delimiters, hence the 'num=1'.
* TODO: Implement a strncmp() which returns the number of matching
* characters in case of a mismatch.
* TODO: Remember the found positions so that we don't have to
* do the comparisons again.
*/
for (p = get_txt(str), left = mstrsize(str), num=1 ; left > 0; )
{
if (left >= len && memcmp(p, get_txt(del), (size_t)len) == 0) {
p += len;
left -= len;
num++;
}
else
{
p += 1;
left -= 1;
}
}
ret = allocate_array(num);
/* Extract the <num> strings into the result array <ret>.
* <buff> serves as temporary buffer for the copying.
*/
for (p = get_txt(str), beg = get_txt(str), num = 0, left = mstrsize(str)
; left > 0; )
{
if (left >= len && memcmp(p, get_txt(del), (size_t)len) == 0)
{
ptrdiff_t bufflen;
bufflen = p - beg;
buff = new_n_mstring(beg, (size_t)bufflen, str->info.unicode);
if (!buff)
{
free_array(ret);
outofmem(bufflen, "buffer for explode()");
}
if (buff->info.unicode == STRING_UTF8 && is_ascii(beg, (size_t)bufflen))
buff->info.unicode = STRING_ASCII;
ret->item[num].u.str = buff;
ret->item[num].type = stringtype;
num++;
beg = p + len;
p = beg;
left -= len;
} else {
p += 1;
left -= 1;
}
}
/* Copy the last occurence (may be empty). */
len = get_txt(str) + mstrsize(str) - beg;
buff = new_n_mstring(beg, (size_t)len, str->info.unicode);
if (!buff)
{
free_array(ret);
outofmem(len, "last fragment in explode()");
}
if (buff->info.unicode == STRING_UTF8 && is_ascii(beg, (size_t)len))
buff->info.unicode = STRING_ASCII;
ret->item[num].u.str = buff;
ret->item[num].type = stringtype;
return ret;
} /* explode_string() */
/*-------------------------------------------------------------------------*/
string_t *
arr_implode_string (vector_t *arr, string_t *del MTRACE_DECL)
/* Implode the string vector <arr> by <del>, i.e. all strings from <arr>
* with <del> interspersed are concatenated into one string. The
* resulting string is returned. The function will return at least
* the empty string "".
*
* Non-string elements are ignored; elements referencing destructed
* objects are replaced by the svalue number 0.
*
* implode({"The", "fox", ""}, " ") -> "The fox "
*
* If possible, annotate the allocations with <file> and <line>
*/
{
mp_int size, i, arr_size;
size_t del_len;
char *deltxt;
char *p;
string_t *result;
svalue_t *svp;
bool first = true;
ph_int stringtype = (del->info.unicode == STRING_BYTES) ? T_BYTES : T_STRING;
bool isutf8 = false;
del_len = mstrsize(del);
deltxt = get_txt(del);
/* Compute the <size> of the final string
*/
size = -(mp_int)del_len;
for (i = (arr_size = (mp_int)VEC_SIZE(arr)), svp = arr->item; --i >= 0; svp++)
{
svalue_t *elem = get_rvalue(svp, NULL);
if (elem == NULL)
{
/* This is a range. */
assert(svp->type == T_LVALUE);
if (svp->x.lvalue_type == LVALUE_PROTECTED_RANGE)
{
struct protected_range_lvalue *r = svp->u.protected_range_lvalue;
if (r->vec.type == stringtype)
size += (mp_int)del_len + r->index2 - r->index1;
}
}
else if (elem->type == stringtype)
size += (mp_int)del_len + mstrsize(elem->u.str);
}
/* Allocate the string; cop out if there's nothing to implode.
*/
if (size <= 0)
return ref_mstring(stringtype == T_STRING ? STR_EMPTY : empty_byte_string);
result = mstring_alloc_string(size MTRACE_PASS);
if (!result)
{
/* caller raises the errorf() */
return NULL;
}
p = get_txt(result);
/* Concatenate the result string.
*
* <i> is the number of elements left to check,
* <svp> is the next element to check,
* <p> points to the current end of the result string.
*/
svp = arr->item;
i = arr_size;
while (i-- > 0)
{
svalue_t *elem = get_rvalue(svp, NULL);
if (elem == NULL)
{
/* This is a range. */
assert(svp->type == T_LVALUE);
if (svp->x.lvalue_type == LVALUE_PROTECTED_RANGE)
{
struct protected_range_lvalue *r = svp->u.protected_range_lvalue;
if (r->vec.type == stringtype)
{
if (first)
first = false;
else
{
memcpy(p, deltxt, del_len);
p += del_len;
}
memcpy(p, get_txt(r->vec.u.str) + r->index1, r->index2 - r->index1);
if (!isutf8 && stringtype == T_STRING && r->vec.u.str->info.unicode == STRING_UTF8 && !is_ascii(p, r->index2 - r->index1))
isutf8 = true;
p += r->index2 - r->index1;
}
}
}
else if (elem->type == stringtype)
{
if (first)
first = false;
else
{
memcpy(p, deltxt, del_len);
p += del_len;
}
memcpy(p, get_txt(elem->u.str), mstrsize(elem->u.str));
p += mstrsize(elem->u.str);
if (elem->u.str->info.unicode == STRING_UTF8)
isutf8 = true;
}
svp++;
}
result->info.unicode = (stringtype == T_BYTES) ? STRING_BYTES : isutf8 ? STRING_UTF8 : STRING_ASCII;
assert(p - get_txt(result) == size);
return result;
} /* implode_array() */
/*-------------------------------------------------------------------------*/
vector_t *
slice_array (vector_t *p, mp_int from, mp_int to)
/* Create a vector slice from vector <p>, range <from> to <to> inclusive,
* and return it.
*
* <to> is guaranteed to not exceed the size of <p>.
* If <from> is greater than <to>, the empty array is returned.
*/
{
vector_t *d;
int cnt;
if (from < 0)
from = 0;
if (to < from)
return allocate_array(0);
d = allocate_array(to-from+1);
for (cnt = from; cnt <= to; cnt++)
assign_rvalue_no_free(&d->item[cnt-from], &p->item[cnt]);
return d;
}
/*-------------------------------------------------------------------------*/
vector_t *
add_array (vector_t *p, vector_t *q)
/* Concatenate the vectors <p> and <q> and return the resulting vector.
* <p> and <q> are not modified.
*/
{
mp_int cnt;
svalue_t *s, *d;
mp_int q_size;
s = p->item;
p = allocate_array((cnt = (mp_int)VEC_SIZE(p)) + (q_size = (mp_int)VEC_SIZE(q)));
d = p->item;
for ( ; --cnt >= 0; ) {
assign_svalue_no_free (d++, s++);
}
s = q->item;
for (cnt = q_size; --cnt >= 0; ) {
assign_svalue_no_free (d++, s++);
}
return p;
} /* add_array() */
/*-------------------------------------------------------------------------*/
static INLINE void
sanitize_array (vector_t * vec)
/* In the given array, make all strings tabled, and replace destructed
* object references by svalue 0s.
* Used for example in preparation for ordering the array.
*/
{
size_t j, keynum;
svalue_t * inpnt;
keynum = VEC_SIZE(vec);
for ( j = 0, inpnt = vec->item; j < keynum; j++, inpnt++)
{
if (inpnt->type == T_STRING || inpnt->type == T_BYTES)
{
if (!mstr_tabled(inpnt->u.str))
{
inpnt->u.str = make_tabled(inpnt->u.str);
}
}
else if (destructed_object_ref(inpnt))
{
free_svalue(inpnt);
put_number(inpnt, 0);
}
}
} /* sanitize_array() */
/*-------------------------------------------------------------------------*/
ptrdiff_t *
get_array_order (vector_t * vec )
/* Determine the order of the elements in vector <vec> and return the
* sorted indices (actually svalue_t* pointer diffs). The order is
* determined by rvalue_cmp() (which happens to be high-to-low).
*
* As a side effect, strings in the vector are made shared, and
* destructed objects in the vector are replaced by svalue 0s.
*/
{
ptrdiff_t * sorted;
/* The vector elements in sorted order, given as the offsets of the array
* element in question to the start of the vector. This way,
* sorted[] needs only to be <keynum> elements long.
* sorted[] is created from root[] after sorting.
*/
svalue_t **root;
/* Auxiliary array with the sorted keys as svalue* into vec.
* This way the sorting is given by the order of the pointers, while
* the original position is given by (pointer - vec->item).
* The very first element is a dummy (heapsort uses array indexing
* starting with index 1), the next <keynum> elements are scratch
* area, the final <keynum> elements hold the sorted keys in reverse
* order.
*/
svalue_t **root2; /* Aux pointer into *root. */
svalue_t *inpnt; /* Pointer to the value to copy into the result */
mp_int keynum; /* Number of keys */
int j;
keynum = (mp_int)VEC_SIZE(vec);
xallocate(sorted, keynum * sizeof(ptrdiff_t) + sizeof(ptrdiff_t)
, "sorted index array");
/* The extra sizeof(ptrdiff_t) is just to have something in
* case keynum is 0.
*/
sanitize_array(vec);
/* For small arrays, use something else but Heapsort - trading
* less overhead for worse complexity.
* TODO: The limit of '6' is arbitrary (it was the transition point
* TODO:: on my machine) - a better way would be to test the system
* TODO:: speed at startup.
*/
if (keynum <= 6)
{
switch (keynum)
{
case 0:
/* Do nothing */
break;
case 1:
sorted[0] = 0;
break;
case 2:
if (rvalue_cmp(vec->item, vec->item + 1) > 0)
{
sorted[0] = 0;
sorted[1] = 1;
}
else
{
sorted[0] = 1;
sorted[1] = 0;
}
break;
case 3:
{
int d;
sorted[0] = 0;
sorted[1] = 1;
sorted[2] = 2;
d = rvalue_cmp(vec->item, vec->item + 1);
if (d < 0)
{
sorted[1] = 0;
sorted[0] = 1;
}
d = rvalue_cmp(vec->item + sorted[0], vec->item + 2);
if (d < 0)
{
ptrdiff_t tmp = sorted[2];
sorted[2] = sorted[0];
sorted[0] = tmp;
}
d = rvalue_cmp(vec->item + sorted[1], vec->item + sorted[2]);
if (d < 0)
{
ptrdiff_t tmp = sorted[2];
sorted[2] = sorted[1];
sorted[1] = tmp;
}
break;
} /* case 3 */
default:
{
size_t start; /* Index of the next position to set */
/* Initialise the sorted[] array */
for (start = 0; (mp_int)start < keynum; start++)
sorted[start] = (ptrdiff_t)start;
/* Outer loop: walk start through the array, being the position
* where the next highest element has to go.
*/
for (start = 0; (mp_int)start < keynum-1; start++)
{
size_t max_idx; /* Index (in sorted[]) of the current max */
svalue_t *max; /* Pointer to the current max svalue */
size_t test_idx; /* Index of element to test */
/* Find the highest element in the remaining vector */
max_idx = start;
max = vec->item + sorted[start];
for (test_idx = start+1; (mp_int)test_idx < keynum; test_idx++)
{
svalue_t *test = vec->item + sorted[test_idx];
if (rvalue_cmp(max, test) < 0)
{
max_idx = test_idx;
max = test;
}
}
/* Put the found maximum at position start */
if (max_idx != start)
{
ptrdiff_t tmp = sorted[max_idx];
sorted[max_idx] = sorted[start];
sorted[start] = tmp;
}
}
break;
} /* case default */
} /* switch(keynum) */
return sorted;
}