summaryrefslogtreecommitdiff
path: root/bzrlib/_static_tuple_c.c
blob: 1a8826988851a6e8e92f4a84dd9050e1e0d58585 (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
/* Copyright (C) 2009, 2010 Canonical Ltd
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/* Must be defined before importing _static_tuple_c.h so that we get the right
 * linkage.
 */
#define STATIC_TUPLE_MODULE

#include <Python.h>
#include "python-compat.h"

#include "_static_tuple_c.h"
#include "_export_c_api.h"

/* Pyrex 0.9.6.4 exports _simple_set_pyx_api as
 * import__simple_set_pyx(), while Pyrex 0.9.8.5 and Cython 0.11.3 export them
 * as import_bzrlib___simple_set_pyx(). As such, we just #define one to be
 * equivalent to the other in our internal code.
 */
#define import__simple_set_pyx import_bzrlib___simple_set_pyx
#include "_simple_set_pyx_api.h"

#if defined(__GNUC__)
#   define inline __inline__
#elif defined(_MSC_VER)
#   define inline __inline
#else
#   define inline
#endif


/* The one and only StaticTuple with no values */
static StaticTuple *_empty_tuple = NULL;
static PyObject *_interned_tuples = NULL;


static inline int
_StaticTuple_is_interned(StaticTuple *self)
{
    return self->flags & STATIC_TUPLE_INTERNED_FLAG;
}



static PyObject *
StaticTuple_as_tuple(StaticTuple *self)
{
    PyObject *tpl = NULL, *obj = NULL;
    int i, len;

    len = self->size;
    tpl = PyTuple_New(len);
    if (!tpl) {
        /* Malloc failure */
        return NULL;
    }
    for (i = 0; i < len; ++i) {
        obj = (PyObject *)self->items[i];
        Py_INCREF(obj);
        PyTuple_SET_ITEM(tpl, i, obj);
    }
    return tpl;
}


static char StaticTuple_as_tuple_doc[] = "as_tuple() => tuple";

static StaticTuple *
StaticTuple_Intern(StaticTuple *self)
{
    PyObject *canonical_tuple = NULL;

    if (_interned_tuples == NULL || _StaticTuple_is_interned(self)) {
        Py_INCREF(self);
        return self;
    }
    /* SimpleSet_Add returns whatever object is present at self
     * or the new object if it needs to add it.
     */
    canonical_tuple = SimpleSet_Add(_interned_tuples, (PyObject *)self);
    if (!canonical_tuple) {
        // Some sort of exception, propogate it.
        return NULL;
    }
    if (canonical_tuple != (PyObject *)self) {
        // There was already a tuple with that value
        return (StaticTuple *)canonical_tuple;
    }
    self->flags |= STATIC_TUPLE_INTERNED_FLAG;
    // The two references in the dict do not count, so that the StaticTuple
    // object does not become immortal just because it was interned.
    Py_REFCNT(self) -= 1;
    return self;
}

static char StaticTuple_Intern_doc[] = "intern() => unique StaticTuple\n"
    "Return a 'canonical' StaticTuple object.\n"
    "Similar to intern() for strings, this makes sure there\n"
    "is only one StaticTuple object for a given value\n."
    "Common usage is:\n"
    "  key = StaticTuple('foo', 'bar').intern()\n";


static void
StaticTuple_dealloc(StaticTuple *self)
{
    int i, len;

    if (_StaticTuple_is_interned(self)) {
        /* revive dead object temporarily for Discard */
        Py_REFCNT(self) = 2;
        if (SimpleSet_Discard(_interned_tuples, (PyObject*)self) != 1)
            Py_FatalError("deletion of interned StaticTuple failed");
        self->flags &= ~STATIC_TUPLE_INTERNED_FLAG;
    }
    len = self->size;
    for (i = 0; i < len; ++i) {
        Py_XDECREF(self->items[i]);
    }
    Py_TYPE(self)->tp_free((PyObject *)self);
}


/* Similar to PyTuple_New() */
static StaticTuple *
StaticTuple_New(Py_ssize_t size)
{
    StaticTuple *stuple;

    if (size < 0 || size > 255) {
        /* Too big or too small */
        PyErr_SetString(PyExc_ValueError, "StaticTuple(...)"
            " takes from 0 to 255 items");
        return NULL;
    }
    if (size == 0 && _empty_tuple != NULL) {
        Py_INCREF(_empty_tuple);
        return _empty_tuple;
    }
    /* Note that we use PyObject_NewVar because we want to allocate a variable
     * width entry. However we *aren't* truly a PyVarObject because we don't
     * use a long for ob_size. Instead we use a plain 'size' that is an int,
     * and will be overloaded with flags in the future.
     * As such we do the alloc, and then have to clean up anything it does
     * incorrectly.
     */
    stuple = PyObject_NewVar(StaticTuple, &StaticTuple_Type, size);
    if (stuple == NULL) {
        return NULL;
    }
    stuple->size = size;
    stuple->flags = 0;
    stuple->_unused0 = 0;
    stuple->_unused1 = 0;
    if (size > 0) {
        memset(stuple->items, 0, sizeof(PyObject *) * size);
    }
#if STATIC_TUPLE_HAS_HASH
    stuple->hash = -1;
#endif
    return stuple;
}


static StaticTuple *
StaticTuple_FromSequence(PyObject *sequence)
{
    StaticTuple *new = NULL;
    PyObject *as_tuple = NULL;
    PyObject *item;
    Py_ssize_t i, size;

    if (StaticTuple_CheckExact(sequence)) {
        Py_INCREF(sequence);
        return (StaticTuple *)sequence;
    }
    if (!PySequence_Check(sequence)) {
        as_tuple = PySequence_Tuple(sequence);
        if (as_tuple == NULL)
            goto done;
        sequence = as_tuple;
    }
    size = PySequence_Size(sequence);
    if (size == -1) {
        goto done;
    }
    new = StaticTuple_New(size);
    if (new == NULL) {
        goto done;
    }
    for (i = 0; i < size; ++i) {
        // This returns a new reference, which we then 'steal' with 
        // StaticTuple_SET_ITEM
        item = PySequence_GetItem(sequence, i);
        if (item == NULL) {
            Py_DECREF(new);
            new = NULL;
            goto done;
        }
        StaticTuple_SET_ITEM(new, i, item);
    }
done:
    Py_XDECREF(as_tuple);
    return (StaticTuple *)new;
}

static StaticTuple *
StaticTuple_from_sequence(PyObject *self, PyObject *args, PyObject *kwargs)
{
    PyObject *sequence;
    if (!PyArg_ParseTuple(args, "O", &sequence))
        return NULL;
    return StaticTuple_FromSequence(sequence);
}


/* Check that all items we point to are 'valid' */
static int
StaticTuple_check_items(StaticTuple *self)
{
    int i;
    PyObject *obj;

    for (i = 0; i < self->size; ++i) {
        obj = self->items[i];
        if (obj == NULL) {
            PyErr_SetString(PyExc_RuntimeError, "StaticTuple(...)"
                " should not have a NULL entry.");
            return 0;
        }
        if (PyString_CheckExact(obj)
            || StaticTuple_CheckExact(obj)
            || obj == Py_None
            || PyBool_Check(obj)
            || PyInt_CheckExact(obj)
            || PyLong_CheckExact(obj)
            || PyFloat_CheckExact(obj)
            || PyUnicode_CheckExact(obj)
            ) continue;
        PyErr_Format(PyExc_TypeError, "StaticTuple(...)"
            " requires that all items are one of"
            " str, StaticTuple, None, bool, int, long, float, or unicode"
            " not %s.", Py_TYPE(obj)->tp_name);
        return 0;
    }
    return 1;
}

static PyObject *
StaticTuple_new_constructor(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    StaticTuple *self;
    PyObject *obj = NULL;
    Py_ssize_t i, len = 0;

    if (type != &StaticTuple_Type) {
        PyErr_SetString(PyExc_TypeError, "we only support creating StaticTuple");
        return NULL;
    }
    if (!PyTuple_CheckExact(args)) {
        PyErr_SetString(PyExc_TypeError, "args must be a tuple");
        return NULL;
    }
    len = PyTuple_GET_SIZE(args);
    if (len < 0 || len > 255) {
        /* Check the length here so we can raise a TypeError instead of
         * StaticTuple_New's ValueError.
         */
        PyErr_SetString(PyExc_TypeError, "StaticTuple(...)"
            " takes from 0 to 255 items");
        return NULL;
    }
    self = (StaticTuple *)StaticTuple_New(len);
    if (self == NULL) {
        return NULL;
    }
    for (i = 0; i < len; ++i) {
        obj = PyTuple_GET_ITEM(args, i);
        Py_INCREF(obj);
        self->items[i] = obj;
    }
    if (!StaticTuple_check_items(self)) {
        type->tp_dealloc((PyObject *)self);
        return NULL;
    }
    return (PyObject *)self;
}

static PyObject *
StaticTuple_repr(StaticTuple *self)
{
    PyObject *as_tuple, *tuple_repr, *result;

    as_tuple = StaticTuple_as_tuple(self);
    if (as_tuple == NULL) {
        return NULL;
    }
    tuple_repr = PyObject_Repr(as_tuple);
    Py_DECREF(as_tuple);
    if (tuple_repr == NULL) {
        return NULL;
    }
    result = PyString_FromFormat("StaticTuple%s",
                                 PyString_AsString(tuple_repr));
    return result;
}

static long
StaticTuple_hash(StaticTuple *self)
{
    /* adapted from tuplehash(), is the specific hash value considered
     * 'stable'?
     */
    register long x, y;
    Py_ssize_t len = self->size;
    PyObject **p;
    long mult = 1000003L;

#if STATIC_TUPLE_HAS_HASH
    if (self->hash != -1) {
        return self->hash;
    }
#endif
    x = 0x345678L;
    p = self->items;
    // TODO: We could set specific flags if we know that, for example, all the
    //       items are strings. I haven't seen a real-world benefit to that
    //       yet, though.
    while (--len >= 0) {
        y = PyObject_Hash(*p++);
        if (y == -1) /* failure */
            return -1;
        x = (x ^ y) * mult;
        /* the cast might truncate len; that doesn't change hash stability */
        mult += (long)(82520L + len + len);
    }
    x += 97531L;
    if (x == -1)
        x = -2;
#if STATIC_TUPLE_HAS_HASH
    self->hash = x;
#endif
    return x;
}

static PyObject *
StaticTuple_richcompare_to_tuple(StaticTuple *v, PyObject *wt, int op)
{
    PyObject *vt;
    PyObject *result = NULL;
    
    vt = StaticTuple_as_tuple((StaticTuple *)v);
    if (vt == NULL) {
        goto done;
    }
    if (!PyTuple_Check(wt)) {
        PyErr_BadInternalCall();
        goto done;
    }
    /* Now we have 2 tuples to compare, do it */
    result = PyTuple_Type.tp_richcompare(vt, wt, op);
done:
    Py_XDECREF(vt);
    return result;
}

/** Compare two objects to determine if they are equivalent.
 * The basic flow is as follows
 *  1) First make sure that both objects are StaticTuple instances. If they
 *     aren't then cast self to a tuple, and have the tuple do the comparison.
 *  2) Special case comparison to Py_None, because it happens to occur fairly
 *     often in the test suite.
 *  3) Special case when v and w are the same pointer. As we know the answer to
 *     all queries without walking individual items.
 *  4) For all operations, we then walk the items to find the first paired
 *     items that are not equal.
 *  5) If all items found are equal, we then check the length of self and
 *     other to determine equality.
 *  6) If an item differs, then we apply "op" to those last two items. (eg.
 *     StaticTuple(A, B) > StaticTuple(A, C) iff B > C)
 */

static PyObject *
StaticTuple_richcompare(PyObject *v, PyObject *w, int op)
{
    StaticTuple *v_st, *w_st;
    Py_ssize_t vlen, wlen, min_len, i;
    PyObject *v_obj, *w_obj;
    richcmpfunc string_richcompare;

    if (!StaticTuple_CheckExact(v)) {
        /* This has never triggered, according to python-dev it seems this
         * might trigger if '__op__' is defined but '__rop__' is not, sort of
         * case. Such as "None == StaticTuple()"
         */
        fprintf(stderr, "self is not StaticTuple\n");
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }
    v_st = (StaticTuple *)v;
    if (StaticTuple_CheckExact(w)) {
        /* The most common case */
        w_st = (StaticTuple*)w;
    } else if (PyTuple_Check(w)) {
        /* One of v or w is a tuple, so we go the 'slow' route and cast up to
         * tuples to compare.
         */
        /* TODO: This seems to be triggering more than I thought it would...
         *       We probably want to optimize comparing self to other when
         *       other is a tuple.
         */
        return StaticTuple_richcompare_to_tuple(v_st, w, op);
    } else if (w == Py_None) {
        // None is always less than the object
        switch (op) {
        case Py_NE:case Py_GT:case Py_GE:
            Py_INCREF(Py_True);
            return Py_True;
        case Py_EQ:case Py_LT:case Py_LE:
            Py_INCREF(Py_False);
            return Py_False;
    default: // Should never happen
        return Py_NotImplemented;
        }
    } else {
        /* We don't special case this comparison, we just let python handle
         * it.
         */
         Py_INCREF(Py_NotImplemented);
         return Py_NotImplemented;
    }
    /* Now we know that we have 2 StaticTuple objects, so let's compare them.
     * This code is inspired from tuplerichcompare, except we know our
     * objects are limited in scope, so we can inline some comparisons.
     */
    if (v == w) {
        /* Identical pointers, we can shortcut this easily. */
        switch (op) {
        case Py_EQ:case Py_LE:case Py_GE:
            Py_INCREF(Py_True);
            return Py_True;
        case Py_NE:case Py_LT:case Py_GT:
            Py_INCREF(Py_False);
            return Py_False;
        }
    }
    if (op == Py_EQ
        && _StaticTuple_is_interned(v_st)
        && _StaticTuple_is_interned(w_st))
    {
        /* If both objects are interned, we know they are different if the
         * pointer is not the same, which would have been handled by the
         * previous if. No need to compare the entries.
         */
        Py_INCREF(Py_False);
        return Py_False;
    }

    /* The only time we are likely to compare items of different lengths is in
     * something like the interned_keys set. However, the hash is good enough
     * that it is rare. Note that 'tuple_richcompare' also does not compare
     * lengths here.
     */
    vlen = v_st->size;
    wlen = w_st->size;
    min_len = (vlen < wlen) ? vlen : wlen;
    string_richcompare = PyString_Type.tp_richcompare;
    for (i = 0; i < min_len; i++) {
        PyObject *result = NULL;
        v_obj = StaticTuple_GET_ITEM(v_st, i);
        w_obj = StaticTuple_GET_ITEM(w_st, i);
        if (v_obj == w_obj) {
            /* Shortcut case, these must be identical */
            continue;
        }
        if (PyString_CheckExact(v_obj) && PyString_CheckExact(w_obj)) {
            result = string_richcompare(v_obj, w_obj, Py_EQ);
        } else if (StaticTuple_CheckExact(v_obj) &&
                   StaticTuple_CheckExact(w_obj))
        {
            /* Both are StaticTuple types, so recurse */
            result = StaticTuple_richcompare(v_obj, w_obj, Py_EQ);
        } else {
            /* Fall back to generic richcompare */
            result = PyObject_RichCompare(v_obj, w_obj, Py_EQ);
        }
        if (result == NULL) {
            return NULL; /* There seems to be an error */
        }
        if (result == Py_False) {
            // This entry is not identical, Shortcut for Py_EQ
            if (op == Py_EQ) {
                return result;
            }
            Py_DECREF(result);
            break;
        }
        if (result != Py_True) {
            /* We don't know *what* richcompare is returning, but it
             * isn't something we recognize
             */
            PyErr_BadInternalCall();
            Py_DECREF(result);
            return NULL;
        }
        Py_DECREF(result);
    }
    if (i >= min_len) {
        /* We walked off one of the lists, but everything compared equal so
         * far. Just compare the size.
         */
        int cmp;
        PyObject *res;
        switch (op) {
        case Py_LT: cmp = vlen <  wlen; break;
        case Py_LE: cmp = vlen <= wlen; break;
        case Py_EQ: cmp = vlen == wlen; break;
        case Py_NE: cmp = vlen != wlen; break;
        case Py_GT: cmp = vlen >  wlen; break;
        case Py_GE: cmp = vlen >= wlen; break;
        default: return NULL; /* cannot happen */
        }
        if (cmp)
            res = Py_True;
        else
            res = Py_False;
        Py_INCREF(res);
        return res;
    }
    /* The last item differs, shortcut the Py_NE case */
    if (op == Py_NE) {
        Py_INCREF(Py_True);
        return Py_True;
    }
    /* It is some other comparison, go ahead and do the real check. */
    if (PyString_CheckExact(v_obj) && PyString_CheckExact(w_obj))
    {
        return string_richcompare(v_obj, w_obj, op);
    } else if (StaticTuple_CheckExact(v_obj) &&
               StaticTuple_CheckExact(w_obj))
    {
        /* Both are StaticTuple types, so recurse */
        return StaticTuple_richcompare(v_obj, w_obj, op);
    } else {
        return PyObject_RichCompare(v_obj, w_obj, op);
    }
}


static Py_ssize_t
StaticTuple_length(StaticTuple *self)
{
    return self->size;
}


static PyObject *
StaticTuple__is_interned(StaticTuple *self)
{
    if (_StaticTuple_is_interned(self)) {
        Py_INCREF(Py_True);
        return Py_True;
    }
    Py_INCREF(Py_False);
    return Py_False;
}

static char StaticTuple__is_interned_doc[] = "_is_interned() => True/False\n"
    "Check to see if this tuple has been interned.\n";


static PyObject *
StaticTuple_reduce(StaticTuple *self)
{
    PyObject *result = NULL, *as_tuple = NULL;

    result = PyTuple_New(2);
    if (!result) {
        return NULL;
    }
    as_tuple = StaticTuple_as_tuple(self);
    if (as_tuple == NULL) {
        Py_DECREF(result);
        return NULL;
    }
    Py_INCREF(&StaticTuple_Type);
    PyTuple_SET_ITEM(result, 0, (PyObject *)&StaticTuple_Type);
    PyTuple_SET_ITEM(result, 1, as_tuple);
    return result;
}

static char StaticTuple_reduce_doc[] = "__reduce__() => tuple\n";


static PyObject *
StaticTuple_add(PyObject *v, PyObject *w)
{
    Py_ssize_t i, len_v, len_w;
    PyObject *item;
    StaticTuple *result;
     /* StaticTuples and plain tuples may be added (concatenated) to
      * StaticTuples.
      */
    if (StaticTuple_CheckExact(v)) {
        len_v = ((StaticTuple*)v)->size;
    } else if (PyTuple_Check(v)) {
        len_v = PyTuple_GET_SIZE(v);
    } else {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }
    if (StaticTuple_CheckExact(w)) {
        len_w = ((StaticTuple*)w)->size;
    } else if (PyTuple_Check(w)) {
        len_w = PyTuple_GET_SIZE(w);
    } else {
        Py_INCREF(Py_NotImplemented);
        return Py_NotImplemented;
    }
    result = StaticTuple_New(len_v + len_w);
    if (result == NULL)
        return NULL;
    for (i = 0; i < len_v; ++i) {
        // This returns a new reference, which we then 'steal' with 
        // StaticTuple_SET_ITEM
        item = PySequence_GetItem(v, i);
        if (item == NULL) {
            Py_DECREF(result);
            return NULL;
        }
        StaticTuple_SET_ITEM(result, i, item);
    }
    for (i = 0; i < len_w; ++i) {
        item = PySequence_GetItem(w, i);
        if (item == NULL) {
            Py_DECREF(result);
            return NULL;
        }
        StaticTuple_SET_ITEM(result, i+len_v, item);
    }
    if (!StaticTuple_check_items(result)) {
        Py_DECREF(result);
        return NULL;
    }
    return (PyObject *)result;
}

static PyObject *
StaticTuple_item(StaticTuple *self, Py_ssize_t offset)
{
    PyObject *obj;
    /* We cast to (int) to avoid worrying about whether Py_ssize_t is a
     * long long, etc. offsets should never be >2**31 anyway.
     */
    if (offset < 0) {
        PyErr_Format(PyExc_IndexError, "StaticTuple_item does not support"
            " negative indices: %d\n", (int)offset);
    } else if (offset >= self->size) {
        PyErr_Format(PyExc_IndexError, "StaticTuple index out of range"
            " %d >= %d", (int)offset, (int)self->size);
        return NULL;
    }
    obj = (PyObject *)self->items[offset];
    Py_INCREF(obj);
    return obj;
}

static PyObject *
StaticTuple_slice(StaticTuple *self, Py_ssize_t ilow, Py_ssize_t ihigh)
{
    PyObject *as_tuple, *result;

    as_tuple = StaticTuple_as_tuple(self);
    if (as_tuple == NULL) {
        return NULL;
    }
    result = PyTuple_Type.tp_as_sequence->sq_slice(as_tuple, ilow, ihigh);
    Py_DECREF(as_tuple);
    return result;
}

static int
StaticTuple_traverse(StaticTuple *self, visitproc visit, void *arg)
{
    Py_ssize_t i;
    for (i = self->size; --i >= 0;) {
        Py_VISIT(self->items[i]);
    }
    return 0;
}


static PyObject *
StaticTuple_sizeof(StaticTuple *self)
{
	Py_ssize_t res;

	res = _PyObject_SIZE(&StaticTuple_Type) + (int)self->size * sizeof(void*);
	return PyInt_FromSsize_t(res);
}



static char StaticTuple_doc[] =
    "C implementation of a StaticTuple structure."
    "\n This is used as StaticTuple(item1, item2, item3)"
    "\n This is similar to tuple, less flexible in what it"
    "\n supports, but also lighter memory consumption."
    "\n Note that the constructor mimics the () form of tuples"
    "\n Rather than the 'tuple()' constructor."
    "\n  eg. StaticTuple(a, b) == (a, b) == tuple((a, b))";

static PyMethodDef StaticTuple_methods[] = {
    {"as_tuple", (PyCFunction)StaticTuple_as_tuple, METH_NOARGS, StaticTuple_as_tuple_doc},
    {"intern", (PyCFunction)StaticTuple_Intern, METH_NOARGS, StaticTuple_Intern_doc},
    {"_is_interned", (PyCFunction)StaticTuple__is_interned, METH_NOARGS,
     StaticTuple__is_interned_doc},
    {"from_sequence", (PyCFunction)StaticTuple_from_sequence,
     METH_STATIC | METH_VARARGS,
     "Create a StaticTuple from a given sequence. This functions"
     " the same as the tuple() constructor."},
    {"__reduce__", (PyCFunction)StaticTuple_reduce, METH_NOARGS, StaticTuple_reduce_doc},
    {"__sizeof__",  (PyCFunction)StaticTuple_sizeof, METH_NOARGS}, 
    {NULL, NULL} /* sentinel */
};


static PyNumberMethods StaticTuple_as_number = {
    (binaryfunc) StaticTuple_add,   /* nb_add */
    0,                              /* nb_subtract */
    0,                              /* nb_multiply */
    0,                              /* nb_divide */
    0,                              /* nb_remainder */
    0,                              /* nb_divmod */
    0,                              /* nb_power */
    0,                              /* nb_negative */
    0,                              /* nb_positive */
    0,                              /* nb_absolute */
    0,                              /* nb_nonzero */
    0,                              /* nb_invert */
    0,                              /* nb_lshift */
    0,                              /* nb_rshift */
    0,                              /* nb_and */
    0,                              /* nb_xor */
    0,                              /* nb_or */
    0,                              /* nb_coerce */
};
    

static PySequenceMethods StaticTuple_as_sequence = {
    (lenfunc)StaticTuple_length,            /* sq_length */
    0,                              /* sq_concat */
    0,                              /* sq_repeat */
    (ssizeargfunc)StaticTuple_item,         /* sq_item */
    (ssizessizeargfunc)StaticTuple_slice,   /* sq_slice */
    0,                              /* sq_ass_item */
    0,                              /* sq_ass_slice */
    0,                              /* sq_contains */
};

/* TODO: Implement StaticTuple_as_mapping.
 *       The only thing we really want to support from there is mp_subscript,
 *       so that we could support extended slicing (foo[::2]). Not worth it
 *       yet, though.
 */


PyTypeObject StaticTuple_Type = {
    PyObject_HEAD_INIT(NULL)
    0,                                           /* ob_size */
    "bzrlib._static_tuple_c.StaticTuple",        /* tp_name */
    sizeof(StaticTuple),                         /* tp_basicsize */
    sizeof(PyObject *),                          /* tp_itemsize */
    (destructor)StaticTuple_dealloc,             /* tp_dealloc */
    0,                                           /* tp_print */
    0,                                           /* tp_getattr */
    0,                                           /* tp_setattr */
    0,                                           /* tp_compare */
    (reprfunc)StaticTuple_repr,                  /* tp_repr */
    &StaticTuple_as_number,                      /* tp_as_number */
    &StaticTuple_as_sequence,                    /* tp_as_sequence */
    0,                                           /* tp_as_mapping */
    (hashfunc)StaticTuple_hash,                  /* tp_hash */
    0,                                           /* tp_call */
    0,                                           /* tp_str */
    0,                                           /* tp_getattro */
    0,                                           /* tp_setattro */
    0,                                           /* tp_as_buffer */
    /* Py_TPFLAGS_CHECKTYPES tells the number operations that they shouldn't
     * try to 'coerce' but instead stuff like 'add' will check it arguments.
     */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES,  /* tp_flags*/
    StaticTuple_doc,                             /* tp_doc */
    /* gc.get_referents checks the IS_GC flag before it calls tp_traverse
     * And we don't include this object in the garbage collector because we
     * know it doesn't create cycles. However, 'meliae' will follow
     * tp_traverse, even if the object isn't GC, and we want that.
     */
    (traverseproc)StaticTuple_traverse,          /* tp_traverse */
    0,                                           /* tp_clear */
    StaticTuple_richcompare,                     /* tp_richcompare */
    0,                                           /* tp_weaklistoffset */
    // without implementing tp_iter, Python will fall back to PySequence*
    // which seems to work ok, we may need something faster/lighter in the
    // future.
    0,                                           /* tp_iter */
    0,                                           /* tp_iternext */
    StaticTuple_methods,                         /* tp_methods */
    0,                                           /* tp_members */
    0,                                           /* tp_getset */
    0,                                           /* tp_base */
    0,                                           /* tp_dict */
    0,                                           /* tp_descr_get */
    0,                                           /* tp_descr_set */
    0,                                           /* tp_dictoffset */
    0,                                           /* tp_init */
    0,                                           /* tp_alloc */
    StaticTuple_new_constructor,                 /* tp_new */
};


static PyMethodDef static_tuple_c_methods[] = {
    {NULL, NULL}
};


static void
setup_interned_tuples(PyObject *m)
{
    _interned_tuples = (PyObject *)SimpleSet_New();
    if (_interned_tuples != NULL) {
        Py_INCREF(_interned_tuples);
        PyModule_AddObject(m, "_interned_tuples", _interned_tuples);
    }
}


static void
setup_empty_tuple(PyObject *m)
{
    StaticTuple *stuple;
    if (_interned_tuples == NULL) {
        fprintf(stderr, "You need to call setup_interned_tuples() before"
                " setup_empty_tuple, because we intern it.\n");
    }
    // We need to create the empty tuple
    stuple = (StaticTuple *)StaticTuple_New(0);
    _empty_tuple = StaticTuple_Intern(stuple);
    assert(_empty_tuple == stuple);
    // At this point, refcnt is 2: 1 from New(), and 1 from the return from
    // intern(). We will keep 1 for the _empty_tuple global, and use the other
    // for the module reference.
    PyModule_AddObject(m, "_empty_tuple", (PyObject *)_empty_tuple);
}

static int
_StaticTuple_CheckExact(PyObject *obj)
{
    return StaticTuple_CheckExact(obj);
}

static void
setup_c_api(PyObject *m)
{
    _export_function(m, "StaticTuple_New", StaticTuple_New,
        "StaticTuple *(Py_ssize_t)");
    _export_function(m, "StaticTuple_Intern", StaticTuple_Intern,
        "StaticTuple *(StaticTuple *)");
    _export_function(m, "StaticTuple_FromSequence", StaticTuple_FromSequence,
        "StaticTuple *(PyObject *)");
    _export_function(m, "_StaticTuple_CheckExact", _StaticTuple_CheckExact,
        "int(PyObject *)");
}


static int
_workaround_pyrex_096(void)
{
    /* Work around an incompatibility in how pyrex 0.9.6 exports a module,
     * versus how pyrex 0.9.8 and cython 0.11 export it.
     * Namely 0.9.6 exports import__simple_set_pyx and tries to
     * "import _simple_set_pyx" but it is available only as
     * "import bzrlib._simple_set_pyx"
     * It is a shame to hack up sys.modules, but that is what we've got to do.
     */
    PyObject *sys_module = NULL, *modules = NULL, *set_module = NULL;
    int retval = -1;

    /* Clear out the current ImportError exception, and try again. */
    PyErr_Clear();
    /* Note that this only seems to work if somewhere else imports
     * bzrlib._simple_set_pyx before importing bzrlib._static_tuple_c
     */
    set_module = PyImport_ImportModule("bzrlib._simple_set_pyx");
    if (set_module == NULL) {
        goto end;
    }
    /* Add the _simple_set_pyx into sys.modules at the appropriate location. */
    sys_module = PyImport_ImportModule("sys");
    if (sys_module == NULL) {
        goto end;
    }
    modules = PyObject_GetAttrString(sys_module, "modules");
    if (modules == NULL || !PyDict_Check(modules)) {
        goto end;
    }
    PyDict_SetItemString(modules, "_simple_set_pyx", set_module);
    /* Now that we have hacked it in, try the import again. */
    retval = import_bzrlib___simple_set_pyx();
end:
    Py_XDECREF(set_module);
    Py_XDECREF(sys_module);
    Py_XDECREF(modules);
    return retval;
}


PyMODINIT_FUNC
init_static_tuple_c(void)
{
    PyObject* m;

    StaticTuple_Type.tp_getattro = PyObject_GenericGetAttr;
    if (PyType_Ready(&StaticTuple_Type) < 0)
        return;

    m = Py_InitModule3("_static_tuple_c", static_tuple_c_methods,
                       "C implementation of a StaticTuple structure");
    if (m == NULL)
      return;

    Py_INCREF(&StaticTuple_Type);
    PyModule_AddObject(m, "StaticTuple", (PyObject *)&StaticTuple_Type);
    if (import_bzrlib___simple_set_pyx() == -1
        && _workaround_pyrex_096() == -1)
    {
        return;
    }
    setup_interned_tuples(m);
    setup_empty_tuple(m);
    setup_c_api(m);
}

// vim: tabstop=4 sw=4 expandtab