Merge lp:~jameinel/bzr/2.1-simple-set into lp:bzr

Proposed by John A Meinel
Status: Merged
Merged at revision: not available
Proposed branch: lp:~jameinel/bzr/2.1-simple-set
Merge into: lp:bzr
Diff against target: 1146 lines
8 files modified
.bzrignore (+3/-0)
NEWS (+7/-0)
bzrlib/_simple_set_pyx.pxd (+91/-0)
bzrlib/_simple_set_pyx.pyx (+600/-0)
bzrlib/python-compat.h (+5/-0)
bzrlib/tests/__init__.py (+1/-0)
bzrlib/tests/test__simple_set.py (+371/-0)
setup.py (+1/-0)
To merge this branch: bzr merge lp:~jameinel/bzr/2.1-simple-set
Reviewer Review Type Date Requested Status
Andrew Bennetts Approve
Review via email: mp+13039@code.launchpad.net
To post a comment you must log in.
Revision history for this message
John A Meinel (jameinel) wrote :
Download full text (3.6 KiB)

This is the first in my series of patches to lower memory overhead with StaticTuple objects.

I picked this first because it wasn't strictly dependent on the other code, but I use it in the implementation of StaticTuple's interning.

Anyway, this introduces a "SimpleSet" class. For now, I have a pyrex version but no pure-python version, as it is only currently used in StaticTuple. I may go to the point of implementing a python version, though it is fairly close in api to a set or a dict. The big thing is that we don't really have values like a dict, but a set() doesn't let you get access to the object which is stored in the internal table.

So the 2 primary wins for this class is:

1) Don't cache the hash of every object. For the types of object we are putting in here, the hash should be relatively cheap to compute. Even further, though, the times when you need the hash are:
  a) When inserting a new object, you need to know its hash, but you haven't cached it yet anyway.
  b) When resolving a collision, you compare the hash to the cached value as a 'cheap' comparison.
However, the number of collisions is based on the quality of your hash, your collision avoidance algorithm, and the size of your table. We can't really change the hash function. We could use 'quadratic hash', but what sets use seems pretty good anyway (it mixes in more of the upper bits, so you probably get divergence faster, but you also lose locality...)
As for the size of the table. It takes the same number of bytes to cache a 'long hash', as it takes to hold a 'PyObject *'. Which means that in the same memory, you could cache hashes *or* double your addressable space and halve the number of collisions.

2) Allow lookups, so we don't need to use a Dict, which has yet another pointer per address. (So for the same number of entries, this will generally be 1/3rd the size of the equivalent dict, and 1/2 the size of the equivalent set.)

3) Have a single function for the equivalent function 'key = dict.setdefault(key, key)'. At the C api, you could use dict->lookup which is a rather private function, or you would generally use PyDict_GetItem() followed by PyDict_SetItem().
With SimpleSet_Add(), it returns the object stored there, so you have a single lookup. (Only really important in the case of collisions, where you may have several steps that need to be repeated.)

Because of the memory savings, I may look into using this elsewhere in our code base. If I do, then I will certainly implement a Python version (probably just subclassing a dict and exposing an 'def add(self key): return self.setdefault(key, key)' function. (And whatever else I specifically need.

As for the specific memory savings here, dicts and sets are resized to average 50% full (resize at 67%, etc.), so is SimpleSet [theory says hash tables fall apart at about 80% full]. The idea is to start interning the StaticTuple objects I'm creating. (For every key, you average at least 2 references, one for the key, and one for all of its children.)
When loading all of launchpad, that translates into about 500k strings, and 1.1M interned StaticTuples (there are actually more, because of how the btree code uses tuples-of...

Read more...

Revision history for this message
Andrew Bennetts (spiv) wrote :
Download full text (10.0 KiB)

I'm very excited by this patch series!

This one is:

 review approve

Although there are some comments you should look at, especially regarding
licensing...

John A Meinel wrote:
[...]
> === added file 'bzrlib/_simple_set_pyx.pxd'
[...]
> +"""Interface definition of a class like PySet but without caching the hash.
> +
> +This is generally useful when you want to 'intern' objects, etc. Note that this
> +differs from Set in that we:
> + 1) Don't have all of the .intersection, .difference, etc functions
> + 2) Do return the object from the set via queries
> + eg. SimpleSet.add(key) => saved_key and SimpleSet[key] => saved_key
> +"""

I feel a bit unsure about a type that has both add and __getitem__/__delitem__.
It's a slightly unusual mix of dict-like and set-like APIs. I think it's fine
after some thinking about it, I'm just noting that it seems a bit funny at
first. Although maybe .remove would be more set-like than .__delitem__?

> +cdef api object SimpleSet_Add(object self, object key)
> +cdef api SimpleSet SimpleSet_New()
> +cdef api object SimpleSet_Add(object self, object key)

That appears to be a duplicate declaration of SimpleSet_Add.

> +cdef api int SimpleSet_Contains(object self, object key) except -1
> +cdef api int SimpleSet_Discard(object self, object key) except -1
> +cdef api PyObject *SimpleSet_Get(SimpleSet self, object key) except? NULL
> +cdef api Py_ssize_t SimpleSet_Size(object self) except -1
> +cdef api int SimpleSet_Next(object self, Py_ssize_t *pos, PyObject **key)
>
> === added file 'bzrlib/_simple_set_pyx.pyx'
[...]
> +cdef object _dummy_obj
> +cdef PyObject *_dummy
> +_dummy_obj = object()
> +_dummy = <PyObject *>_dummy_obj

It's not very clear what _dummy is used for. I guess what's missing is some
text giving an overview of the data structure, although I suppose that's what
you mean to convey by the docstrings saying it is similar to the builtin
dict/set types.

Anyway, it appears _dummy is used to avoid resizing/compacting the
table for every single discard. [Part of why it would be nice to have some text
describing the data structure is so that there's some clear terminology to
use... the code pretty clearly talks about “tables” and “slots”, which seem
fairly clear, but then what's an “entry”?]

> +cdef int _is_equal(PyObject *this, long this_hash, PyObject *other):
> + cdef long other_hash
> + cdef PyObject *res
> +
> + if this == other:
> + return 1
> + other_hash = Py_TYPE(other).tp_hash(other)

What happens if 'other' is not hashable?

> + if other_hash != this_hash:
> + return 0
> + res = Py_TYPE(this).tp_richcompare(this, other, Py_EQ)

Similarly, what if one the richcompare calls raise an exception?

> +cdef public api class SimpleSet [object SimpleSetObject, type SimpleSet_Type]:
[...]
> + cdef int _insert_clean(self, PyObject *key) except -1:
> + """Insert a key into self.table.
> +
> + This is only meant to be used during times like '_resize',
> + as it makes a lot of assuptions about keys not already being present,
> + and there being no dummy entries.
> + """
> + cdef size_t i, perturb, mask
> + cdef lon...

review: Approve
Revision history for this message
John A Meinel (jameinel) wrote :
Download full text (15.8 KiB)

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Andrew Bennetts wrote:
...

>> + 1) Don't have all of the .intersection, .difference, etc functions
>> + 2) Do return the object from the set via queries
>> + eg. SimpleSet.add(key) => saved_key and SimpleSet[key] => saved_key
>> +"""
>
> I feel a bit unsure about a type that has both add and __getitem__/__delitem__.
> It's a slightly unusual mix of dict-like and set-like APIs. I think it's fine
> after some thinking about it, I'm just noting that it seems a bit funny at
> first. Although maybe .remove would be more set-like than .__delitem__?

So at the moment, the only apis I need for interning are:
  add() and discard()

I could certainly remove the __getitem__ and __delitem__ if you are more
comfortable with it.

I want to have an api that fits what we need/want to use. As such, it
will probably be driven by actual use cases. And so far, there is only 1
of those...

I considered changing the semantics, such that "__getitem__" == "add()".
The main reason for that is because it avoids the getattr() overhead, as
__getitem__ is a slot in the type struct (tp_item) while .add() requires
an attribute lookup.

Which basically means that in an interning loop you would have:

for bar in group:
  bar = dedup[bar]

rather than

  bar = dedup.add(bar)

or the old form

  bar = dict.setdefault(bar, bar)

I would guess that doing

add = dedup.add
for bar in group:
  bar = add(bar)

Is going to perform the same as the dedup[bar] form. But both should do
better than setdefault. (At a minimum, setdefault takes 2 parameters,
and thus has to create a tuple, etc.)

I don't know if the interpreter has further internal benefits to using
the __getitem__ form, since it is a known api that has to conform in
certain ways.

The big concern is that "dedup[bar]" can mutate 'dedup' and that is
potentially unexpected.

>
>> +cdef api object SimpleSet_Add(object self, object key)
>> +cdef api SimpleSet SimpleSet_New()
>> +cdef api object SimpleSet_Add(object self, object key)
>
> That appears to be a duplicate declaration of SimpleSet_Add.

Thanks.

...

> [...]
>> +cdef object _dummy_obj
>> +cdef PyObject *_dummy
>> +_dummy_obj = object()
>> +_dummy = <PyObject *>_dummy_obj
>
> It's not very clear what _dummy is used for. I guess what's missing is some
> text giving an overview of the data structure, although I suppose that's what
> you mean to convey by the docstrings saying it is similar to the builtin
> dict/set types.
>
> Anyway, it appears _dummy is used to avoid resizing/compacting the
> table for every single discard. [Part of why it would be nice to have some text
> describing the data structure is so that there's some clear terminology to
> use... the code pretty clearly talks about “tables” and “slots”, which seem
> fairly clear, but then what's an “entry”?]

How's this:

 # Data structure definition:
 # This is a basic hash table using open addressing.
 # http://en.wikipedia.org/wiki/Open_addressing
 # Basically that means we keep an array of pointers to Python objects
 # (called a table). Each location in the array is called a 'slot'.
 #
 # An empty slot holds a NULL pointer, a ...

Revision history for this message
Andrew Bennetts (spiv) wrote :
Download full text (12.2 KiB)

John A Meinel wrote:
[...]
> I would guess that doing
>
> add = dedup.add
> for bar in group:
> bar = add(bar)
>
> Is going to perform the same as the dedup[bar] form. But both should do
> better than setdefault. (At a minimum, setdefault takes 2 parameters,
> and thus has to create a tuple, etc.)
>
> I don't know if the interpreter has further internal benefits to using
> the __getitem__ form, since it is a known api that has to conform in
> certain ways.

Right, I think you'd still see a bit of benefit in the __getitem__ form because
Python knows that that operator only takes one arg and so avoids packing and
unpacking an args tuple for it. (Like METH_O vs. METH_VARARGS.) ISTR some part
of the zope.interface C extension intentionally abuses an obscure no-arg
operator (maybe pos?) as that's the fastest way to invoke C code from Python.

> The big concern is that "dedup[bar]" can mutate 'dedup' and that is
> potentially unexpected.

Agreed. For readability my preference is .add, but obviously sufficiently large
performance benefits may override that. I don't *think* the boost from using
__getitem__ instead would be that much greater for this use, but I haven't
measured so I may be very wrong :)

[...]
> How's this:
>
> # Data structure definition:

Great!

> >> +cdef int _is_equal(PyObject *this, long this_hash, PyObject *other):
> >> + cdef long other_hash
> >> + cdef PyObject *res
> >> +
> >> + if this == other:
> >> + return 1
> >> + other_hash = Py_TYPE(other).tp_hash(other)
> >
> > What happens if 'other' is not hashable?
>
> Other will always be something that is already held in the internal
> structure, and thus has been hashed. 'this' has also already been hashed
> as part of inserting, and thus we've also checked that it can be hashed.
>
> I can change this to PyObject_Hash() if you feel strongly. I was
> avoiding a function call overhead, though it probably doesn't have a
> huge impact on performance.

Well, badly-behaved objects might successfully give a hash value the first time
and then get an error later. I do strongly lean towards paranoia in C code, so
I think PyObject_Hash is probably safest. You ought to be able to construct a
test that defines such a badly-behaved object to see just how bad the fallout
is. If segfaults are possible then definitely close that hole!

Also, PyObject_Hash is where Python implements the logic that an object with no
tp_hash in its type will use hash(id(obj)), so long as it doesn't have
tp_compare or tp_richcompare. I think this is pretty common, e.g. the module
type has no tp_hash. And given that you use the 'hash' global elsewhere in this
module there's definitely some chance for confusion here.

But for the case you're optimising for PyObject_Hash will just call the object's
tp_hash immediately and return the result, so it should be a minimal penalty,
just a C function call overhead.

The thing I was really looking for though was checking the result value of
tp_hash/PyObject_Hash — if its -1 then there's an error to be dealt with.

> >> + if other_hash != this_hash:
> >> + return 0
> >> + res = Py_TYPE(this).tp_richcompare(this, other, Py_EQ)
>...

Revision history for this message
John A Meinel (jameinel) wrote :
Download full text (9.4 KiB)

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Andrew Bennetts wrote:
> John A Meinel wrote:
> [...]
>> I would guess that doing
>>
>> add = dedup.add
>> for bar in group:
>> bar = add(bar)
>>
>> Is going to perform the same as the dedup[bar] form. But both should do
>> better than setdefault. (At a minimum, setdefault takes 2 parameters,
>> and thus has to create a tuple, etc.)
>>
>> I don't know if the interpreter has further internal benefits to using
>> the __getitem__ form, since it is a known api that has to conform in
>> certain ways.
>
> Right, I think you'd still see a bit of benefit in the __getitem__ form because
> Python knows that that operator only takes one arg and so avoids packing and
> unpacking an args tuple for it. (Like METH_O vs. METH_VARARGS.) ISTR some part
> of the zope.interface C extension intentionally abuses an obscure no-arg
> operator (maybe pos?) as that's the fastest way to invoke C code from Python.
>
>> The big concern is that "dedup[bar]" can mutate 'dedup' and that is
>> potentially unexpected.
>
> Agreed. For readability my preference is .add, but obviously sufficiently large
> performance benefits may override that. I don't *think* the boost from using
> __getitem__ instead would be that much greater for this use, but I haven't
> measured so I may be very wrong :)
>
> [...]
>> How's this:
>>
>> # Data structure definition:
>
> Great!
>
>>>> +cdef int _is_equal(PyObject *this, long this_hash, PyObject *other):
>>>> + cdef long other_hash
>>>> + cdef PyObject *res
>>>> +
>>>> + if this == other:
>>>> + return 1
>>>> + other_hash = Py_TYPE(other).tp_hash(other)
>>> What happens if 'other' is not hashable?
>> Other will always be something that is already held in the internal
>> structure, and thus has been hashed. 'this' has also already been hashed
>> as part of inserting, and thus we've also checked that it can be hashed.
>>
>> I can change this to PyObject_Hash() if you feel strongly. I was
>> avoiding a function call overhead, though it probably doesn't have a
>> huge impact on performance.
>
> Well, badly-behaved objects might successfully give a hash value the first time
> and then get an error later. I do strongly lean towards paranoia in C code, so
> I think PyObject_Hash is probably safest. You ought to be able to construct a
> test that defines such a badly-behaved object to see just how bad the fallout
> is. If segfaults are possible then definitely close that hole!

No segfaults, but the potential to leave an error in the pipe. Which
causes random failures IIRC. (I forget the function where '-1' is maybe
an error, so you have to check PyErr_Occurred, etc.)

>
> Also, PyObject_Hash is where Python implements the logic that an object with no
> tp_hash in its type will use hash(id(obj)), so long as it doesn't have
> tp_compare or tp_richcompare. I think this is pretty common, e.g. the module
> type has no tp_hash. And given that you use the 'hash' global elsewhere in this
> module there's definitely some chance for confusion here.

So in my "_insert" I now have the assertion:
        if (Py_TYPE(py_key).tp_richcompare == NULL
            or Py_TYPE(py_key).tp_...

Read more...

Revision history for this message
John A Meinel (jameinel) wrote :

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

...

> Again, PyObject_IsTrue tries == Py_True as the very first thing, so the cost
> should be small. If you're worried a macro along the lines of:
>
> #define PY_IS_TRUE(o) ((o == Py_True) || PyObject_IsTrue(o))
>
> might make us both happy.
>

So it turns out that this fix actually causes crazy corruption. Specifically

assert PyObject_IsTrue(Py_NotImplemented)

passes.

In other words "Py_NotImplemented" evaluates to True.
You can also see that with:

>>> bool(NotImplemented)
True

So the code was doing:

if res == NULL:
  return -1
if PyObject_IsTrue(res):
  ...
if res == Py_NotImplemented:
  # reverse the comparison.

Anyway, I've tracked this down to some crazy interning issues I've been
seeing. (You have to get a hash collision *and* have objects that return
NotImplemented.

John
=:->
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (Cygwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkrV72AACgkQJdeBCYSNAAPiOgCdGOnxjBvPH08fKYxa0vjXHSGu
yfsAn0Mn8b62R8wn8jHsttXoBZEILhja
=3Wq/
-----END PGP SIGNATURE-----

Revision history for this message
Andrew Bennetts (spiv) wrote :

John A Meinel wrote:
[...]
> So it turns out that this fix actually causes crazy corruption. Specifically
>
> assert PyObject_IsTrue(Py_NotImplemented)
>
> passes.

Ah, yes, it would.

[...]
> So the code was doing:
>
> if res == NULL:
> return -1
> if PyObject_IsTrue(res):
> ...
> if res == Py_NotImplemented:
> # reverse the comparison.
>

So I guess you need to change this to:

if res == NULL:
    return -1
elif res == Py_NotImplemented:
    # reverse the comparison
    ...
elif PyObject_IsTrue(res):
    ...

And similarly for handling the res of the reversed comparison.

-Andrew.

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file '.bzrignore'
2--- .bzrignore 2009-09-09 11:43:10 +0000
3+++ .bzrignore 2009-10-12 16:51:14 +0000
4@@ -58,6 +58,9 @@
5 bzrlib/_known_graph_pyx.c
6 bzrlib/_readdir_pyx.c
7 bzrlib/_rio_pyx.c
8+bzrlib/_simple_set_pyx.c
9+bzrlib/_simple_set_pyx.h
10+bzrlib/_simple_set_pyx_api.h
11 bzrlib/_walkdirs_win32.c
12 # built extension modules
13 bzrlib/_*.dll
14
15=== modified file 'NEWS'
16--- NEWS 2009-10-08 23:44:40 +0000
17+++ NEWS 2009-10-12 16:51:14 +0000
18@@ -206,6 +206,13 @@
19 repository or branch object is unlocked then relocked the same way.
20 (Andrew Bennetts)
21
22+* Added ``bzrlib._simple_set_pyx``. This is a hybrid between a Set and a
23+ Dict (it only holds keys, but you can lookup the object located at a
24+ given key). It has significantly reduced memory consumption versus the
25+ builtin objects (1/2 the size of Set, 1/3rd the size of Dict). This will
26+ be used as the interning structure for StaticTuple objects, as part of
27+ an ongoing push to reduce peak memory consumption. (John Arbash Meinel)
28+
29 * ``BTreeLeafParser.extract_key`` has been tweaked slightly to reduce
30 mallocs while parsing the index (approx 3=>1 mallocs per key read).
31 This results in a 10% speedup while reading an index.
32
33=== added file 'bzrlib/_simple_set_pyx.pxd'
34--- bzrlib/_simple_set_pyx.pxd 1970-01-01 00:00:00 +0000
35+++ bzrlib/_simple_set_pyx.pxd 2009-10-12 16:51:14 +0000
36@@ -0,0 +1,91 @@
37+# Copyright (C) 2009 Canonical Ltd
38+#
39+# This program is free software; you can redistribute it and/or modify
40+# it under the terms of the GNU General Public License as published by
41+# the Free Software Foundation; either version 2 of the License, or
42+# (at your option) any later version.
43+#
44+# This program is distributed in the hope that it will be useful,
45+# but WITHOUT ANY WARRANTY; without even the implied warranty of
46+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
47+# GNU General Public License for more details.
48+#
49+# You should have received a copy of the GNU General Public License
50+# along with this program; if not, write to the Free Software
51+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
52+
53+"""Interface definition of a class like PySet but without caching the hash.
54+
55+This is generally useful when you want to 'intern' objects, etc. Note that this
56+differs from Set in that we:
57+ 1) Don't have all of the .intersection, .difference, etc functions
58+ 2) Do return the object from the set via queries
59+ eg. SimpleSet.add(key) => saved_key and SimpleSet[key] => saved_key
60+"""
61+
62+cdef extern from "Python.h":
63+ ctypedef struct PyObject:
64+ pass
65+
66+
67+cdef public api class SimpleSet [object SimpleSetObject, type SimpleSet_Type]:
68+ """A class similar to PySet, but with simpler implementation.
69+
70+ The main advantage is that this class uses only 2N memory to store N
71+ objects rather than 4N memory. The main trade-off is that we do not cache
72+ the hash value of saved objects. As such, it is assumed that computing the
73+ hash will be cheap (such as strings or tuples of strings, etc.)
74+
75+ This also differs in that you can get back the objects that are stored
76+ (like a dict), but we also don't implement the complete list of 'set'
77+ operations (difference, intersection, etc).
78+ """
79+ # Data structure definition:
80+ # This is a basic hash table using open addressing.
81+ # http://en.wikipedia.org/wiki/Open_addressing
82+ # Basically that means we keep an array of pointers to Python objects
83+ # (called a table). Each location in the array is called a 'slot'.
84+ #
85+ # An empty slot holds a NULL pointer, a slot where there was an item
86+ # which was then deleted will hold a pointer to _dummy, and a filled slot
87+ # points at the actual object which fills that slot.
88+ #
89+ # The table is always a power of two, and the default location where an
90+ # object is inserted is at hash(object) & (table_size - 1)
91+ #
92+ # If there is a collision, then we search for another location. The
93+ # specific algorithm is in _lookup. We search until we:
94+ # find the object
95+ # find an equivalent object (by tp_richcompare(obj1, obj2, Py_EQ))
96+ # find a NULL slot
97+ #
98+ # When an object is deleted, we set its slot to _dummy. this way we don't
99+ # have to track whether there was a collision, and find the corresponding
100+ # keys. (The collision resolution algorithm makes that nearly impossible
101+ # anyway, because it depends on the upper bits of the hash.)
102+ # The main effect of this, is that if we find _dummy, then we can insert
103+ # an object there, but we have to keep searching until we find NULL to
104+ # know that the object is not present elsewhere.
105+
106+ cdef Py_ssize_t _used # active
107+ cdef Py_ssize_t _fill # active + dummy
108+ cdef Py_ssize_t _mask # Table contains (mask+1) slots, a power of 2
109+ cdef PyObject **_table # Pyrex/Cython doesn't support arrays to 'object'
110+ # so we manage it manually
111+
112+ cdef PyObject *_get(self, object key) except? NULL
113+ cdef object _add(self, key)
114+ cdef int _discard(self, key) except -1
115+ cdef int _insert_clean(self, PyObject *key) except -1
116+ cdef Py_ssize_t _resize(self, Py_ssize_t min_unused) except -1
117+
118+
119+# TODO: might want to export the C api here, though it is all available from
120+# the class object...
121+cdef api SimpleSet SimpleSet_New()
122+cdef api object SimpleSet_Add(object self, object key)
123+cdef api int SimpleSet_Contains(object self, object key) except -1
124+cdef api int SimpleSet_Discard(object self, object key) except -1
125+cdef api PyObject *SimpleSet_Get(SimpleSet self, object key) except? NULL
126+cdef api Py_ssize_t SimpleSet_Size(object self) except -1
127+cdef api int SimpleSet_Next(object self, Py_ssize_t *pos, PyObject **key)
128
129=== added file 'bzrlib/_simple_set_pyx.pyx'
130--- bzrlib/_simple_set_pyx.pyx 1970-01-01 00:00:00 +0000
131+++ bzrlib/_simple_set_pyx.pyx 2009-10-12 16:51:14 +0000
132@@ -0,0 +1,600 @@
133+# Copyright (C) 2009 Canonical Ltd
134+#
135+# This program is free software; you can redistribute it and/or modify
136+# it under the terms of the GNU General Public License as published by
137+# the Free Software Foundation; either version 2 of the License, or
138+# (at your option) any later version.
139+#
140+# This program is distributed in the hope that it will be useful,
141+# but WITHOUT ANY WARRANTY; without even the implied warranty of
142+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
143+# GNU General Public License for more details.
144+#
145+# You should have received a copy of the GNU General Public License
146+# along with this program; if not, write to the Free Software
147+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
148+
149+"""Definition of a class that is similar to Set with some small changes."""
150+
151+cdef extern from "python-compat.h":
152+ pass
153+
154+cdef extern from "Python.h":
155+ ctypedef unsigned long size_t
156+ ctypedef long (*hashfunc)(PyObject*)
157+ ctypedef PyObject *(*richcmpfunc)(PyObject *, PyObject *, int)
158+ ctypedef int (*visitproc)(PyObject *, void *)
159+ ctypedef int (*traverseproc)(PyObject *, visitproc, void *)
160+ int Py_EQ
161+ PyObject *Py_True
162+ PyObject *Py_NotImplemented
163+ void Py_INCREF(PyObject *)
164+ void Py_DECREF(PyObject *)
165+ ctypedef struct PyTypeObject:
166+ hashfunc tp_hash
167+ richcmpfunc tp_richcompare
168+ traverseproc tp_traverse
169+
170+ PyTypeObject *Py_TYPE(PyObject *)
171+ int PyObject_IsTrue(PyObject *)
172+
173+ void *PyMem_Malloc(size_t nbytes)
174+ void PyMem_Free(void *)
175+ void memset(void *, int, size_t)
176+
177+
178+# Dummy is an object used to mark nodes that have been deleted. Since
179+# collisions require us to move a node to an alternative location, if we just
180+# set an entry to NULL on delete, we won't find any relocated nodes.
181+# We have to use _dummy_obj because we need to keep a refcount to it, but we
182+# also use _dummy as a pointer, because it avoids having to put <PyObject*> all
183+# over the code base.
184+cdef object _dummy_obj
185+cdef PyObject *_dummy
186+_dummy_obj = object()
187+_dummy = <PyObject *>_dummy_obj
188+
189+
190+cdef int _is_equal(PyObject *this, long this_hash, PyObject *other) except -1:
191+ cdef long other_hash
192+ cdef PyObject *res
193+
194+ if this == other:
195+ return 1
196+ other_hash = Py_TYPE(other).tp_hash(other)
197+ if other_hash == -1:
198+ # Even though other successfully hashed in the past, it seems to have
199+ # changed its mind, and failed this time, so propogate the failure.
200+ return -1
201+ if other_hash != this_hash:
202+ return 0
203+
204+ # This implements a subset of the PyObject_RichCompareBool functionality.
205+ # Namely it:
206+ # 1) Doesn't try to do anything with old-style classes
207+ # 2) Assumes that both objects have a tp_richcompare implementation, and
208+ # that if that is not enough to compare equal, then they are not
209+ # equal. (It doesn't try to cast them both to some intermediate form
210+ # that would compare equal.)
211+ res = Py_TYPE(this).tp_richcompare(this, other, Py_EQ)
212+ if res == NULL: # Exception
213+ return -1
214+ if PyObject_IsTrue(res):
215+ Py_DECREF(res)
216+ return 1
217+ if res == Py_NotImplemented:
218+ Py_DECREF(res)
219+ res = Py_TYPE(other).tp_richcompare(other, this, Py_EQ)
220+ if res == NULL:
221+ return -1
222+ if PyObject_IsTrue(res):
223+ Py_DECREF(res)
224+ return 1
225+ Py_DECREF(res)
226+ return 0
227+
228+
229+cdef public api class SimpleSet [object SimpleSetObject, type SimpleSet_Type]:
230+ """This class can be used to track canonical forms for objects.
231+
232+ It is similar in function to the interned dictionary that is used by
233+ strings. However:
234+
235+ 1) It assumes that hash(obj) is cheap, so does not need to inline a copy
236+ of it
237+ 2) It only stores one reference to the object, rather than 2 (key vs
238+ key:value)
239+
240+ As such, it uses 1/3rd the amount of memory to store a pointer to the
241+ interned object.
242+ """
243+ # Attributes are defined in the .pxd file
244+ DEF DEFAULT_SIZE=1024
245+
246+ def __init__(self):
247+ cdef Py_ssize_t size, n_bytes
248+
249+ size = DEFAULT_SIZE
250+ self._mask = size - 1
251+ self._used = 0
252+ self._fill = 0
253+ n_bytes = sizeof(PyObject*) * size;
254+ self._table = <PyObject **>PyMem_Malloc(n_bytes)
255+ if self._table == NULL:
256+ raise MemoryError()
257+ memset(self._table, 0, n_bytes)
258+
259+ def __dealloc__(self):
260+ if self._table != NULL:
261+ PyMem_Free(self._table)
262+ self._table = NULL
263+
264+ property used:
265+ def __get__(self):
266+ return self._used
267+
268+ property fill:
269+ def __get__(self):
270+ return self._fill
271+
272+ property mask:
273+ def __get__(self):
274+ return self._mask
275+
276+ def _memory_size(self):
277+ """Return the number of bytes of memory consumed by this class."""
278+ return sizeof(self) + (sizeof(PyObject*)*(self._mask + 1))
279+
280+ def __len__(self):
281+ return self._used
282+
283+ def _test_lookup(self, key):
284+ cdef PyObject **slot
285+
286+ slot = _lookup(self, key)
287+ if slot[0] == NULL:
288+ res = '<null>'
289+ elif slot[0] == _dummy:
290+ res = '<dummy>'
291+ else:
292+ res = <object>slot[0]
293+ return <int>(slot - self._table), res
294+
295+ def __contains__(self, key):
296+ """Is key present in this SimpleSet."""
297+ cdef PyObject **slot
298+
299+ slot = _lookup(self, key)
300+ if slot[0] == NULL or slot[0] == _dummy:
301+ return False
302+ return True
303+
304+ cdef PyObject *_get(self, object key) except? NULL:
305+ """Return the object (or nothing) define at the given location."""
306+ cdef PyObject **slot
307+
308+ slot = _lookup(self, key)
309+ if slot[0] == NULL or slot[0] == _dummy:
310+ return NULL
311+ return slot[0]
312+
313+ def __getitem__(self, key):
314+ """Return a stored item that is equivalent to key."""
315+ cdef PyObject *py_val
316+
317+ py_val = self._get(key)
318+ if py_val == NULL:
319+ raise KeyError("Key %s is not present" % key)
320+ val = <object>(py_val)
321+ return val
322+
323+ cdef int _insert_clean(self, PyObject *key) except -1:
324+ """Insert a key into self.table.
325+
326+ This is only meant to be used during times like '_resize',
327+ as it makes a lot of assuptions about keys not already being present,
328+ and there being no dummy entries.
329+ """
330+ cdef size_t i, n_lookup
331+ cdef long the_hash
332+ cdef PyObject **table, **slot
333+ cdef Py_ssize_t mask
334+
335+ mask = self._mask
336+ table = self._table
337+
338+ the_hash = Py_TYPE(key).tp_hash(key)
339+ if the_hash == -1:
340+ return -1
341+ i = the_hash
342+ for n_lookup from 0 <= n_lookup <= <size_t>mask: # Don't loop forever
343+ slot = &table[i & mask]
344+ if slot[0] == NULL:
345+ slot[0] = key
346+ self._fill = self._fill + 1
347+ self._used = self._used + 1
348+ return 1
349+ i = i + 1 + n_lookup
350+ raise RuntimeError('ran out of slots.')
351+
352+ def _py_resize(self, min_used):
353+ """Do not use this directly, it is only exposed for testing."""
354+ return self._resize(min_used)
355+
356+ cdef Py_ssize_t _resize(self, Py_ssize_t min_used) except -1:
357+ """Resize the internal table.
358+
359+ The final table will be big enough to hold at least min_used entries.
360+ We will copy the data from the existing table over, leaving out dummy
361+ entries.
362+
363+ :return: The new size of the internal table
364+ """
365+ cdef Py_ssize_t new_size, n_bytes, remaining
366+ cdef PyObject **new_table, **old_table, **slot
367+
368+ new_size = DEFAULT_SIZE
369+ while new_size <= min_used and new_size > 0:
370+ new_size = new_size << 1
371+ # We rolled over our signed size field
372+ if new_size <= 0:
373+ raise MemoryError()
374+ # Even if min_used == self._mask + 1, and we aren't changing the actual
375+ # size, we will still run the algorithm so that dummy entries are
376+ # removed
377+ # TODO: Test this
378+ # if new_size < self._used:
379+ # raise RuntimeError('cannot shrink SimpleSet to something'
380+ # ' smaller than the number of used slots.')
381+ n_bytes = sizeof(PyObject*) * new_size;
382+ new_table = <PyObject **>PyMem_Malloc(n_bytes)
383+ if new_table == NULL:
384+ raise MemoryError()
385+
386+ old_table = self._table
387+ self._table = new_table
388+ memset(self._table, 0, n_bytes)
389+ self._mask = new_size - 1
390+ self._used = 0
391+ remaining = self._fill
392+ self._fill = 0
393+
394+ # Moving everything to the other table is refcount neutral, so we don't
395+ # worry about it.
396+ slot = old_table
397+ while remaining > 0:
398+ if slot[0] == NULL: # unused slot
399+ pass
400+ elif slot[0] == _dummy: # dummy slot
401+ remaining = remaining - 1
402+ else: # active slot
403+ remaining = remaining - 1
404+ self._insert_clean(slot[0])
405+ slot = slot + 1
406+ PyMem_Free(old_table)
407+ return new_size
408+
409+ def add(self, key):
410+ """Similar to set.add(), start tracking this key.
411+
412+ There is one small difference, which is that we return the object that
413+ is stored at the given location. (which is closer to the
414+ dict.setdefault() functionality.)
415+ """
416+ return self._add(key)
417+
418+ cdef object _add(self, key):
419+ cdef PyObject **slot, *py_key
420+ cdef int added
421+
422+ py_key = <PyObject *>key
423+ if (Py_TYPE(py_key).tp_richcompare == NULL
424+ or Py_TYPE(py_key).tp_hash == NULL):
425+ raise TypeError('Types added to SimpleSet must implement'
426+ ' both tp_richcompare and tp_hash')
427+ added = 0
428+ # We need at least one empty slot
429+ assert self._used < self._mask
430+ slot = _lookup(self, key)
431+ if (slot[0] == NULL):
432+ Py_INCREF(py_key)
433+ self._fill = self._fill + 1
434+ self._used = self._used + 1
435+ slot[0] = py_key
436+ added = 1
437+ elif (slot[0] == _dummy):
438+ Py_INCREF(py_key)
439+ self._used = self._used + 1
440+ slot[0] = py_key
441+ added = 1
442+ # No else: clause. If _lookup returns a pointer to
443+ # a live object, then we already have a value at this location.
444+ retval = <object>(slot[0])
445+ # PySet and PyDict use a 2-3rds full algorithm, we'll follow suit
446+ if added and (self._fill * 3) >= ((self._mask + 1) * 2):
447+ # However, we always work for a load factor of 2:1
448+ self._resize(self._used * 2)
449+ # Even if we resized and ended up moving retval into a different slot,
450+ # it is still the value that is held at the slot equivalent to 'key',
451+ # so we can still return it
452+ return retval
453+
454+ def discard(self, key):
455+ """Remove key from the set, whether it exists or not.
456+
457+ :return: False if the item did not exist, True if it did
458+ """
459+ if self._discard(key):
460+ return True
461+ return False
462+
463+ cdef int _discard(self, key) except -1:
464+ cdef PyObject **slot, *py_key
465+
466+ slot = _lookup(self, key)
467+ if slot[0] == NULL or slot[0] == _dummy:
468+ return 0
469+ self._used = self._used - 1
470+ Py_DECREF(slot[0])
471+ slot[0] = _dummy
472+ # PySet uses the heuristic: If more than 1/5 are dummies, then resize
473+ # them away
474+ # if ((so->_fill - so->_used) * 5 < so->mask)
475+ # However, we are planning on using this as an interning structure, in
476+ # which we will be putting a lot of objects. And we expect that large
477+ # groups of them are going to have the same lifetime.
478+ # Dummy entries hurt a little bit because they cause the lookup to keep
479+ # searching, but resizing is also rather expensive
480+ # For now, we'll just use their algorithm, but we may want to revisit
481+ # it
482+ if ((self._fill - self._used) * 5 > self._mask):
483+ self._resize(self._used * 2)
484+ return 1
485+
486+ def __iter__(self):
487+ return _SimpleSet_iterator(self)
488+
489+
490+cdef class _SimpleSet_iterator:
491+ """Iterator over the SimpleSet structure."""
492+
493+ cdef Py_ssize_t pos
494+ cdef SimpleSet set
495+ cdef Py_ssize_t _used # track if things have been mutated while iterating
496+ cdef Py_ssize_t len # number of entries left
497+
498+ def __init__(self, obj):
499+ self.set = obj
500+ self.pos = 0
501+ self._used = self.set._used
502+ self.len = self.set._used
503+
504+ def __iter__(self):
505+ return self
506+
507+ def __next__(self):
508+ cdef Py_ssize_t mask, i
509+ cdef PyObject *key
510+
511+ if self.set is None:
512+ raise StopIteration
513+ if self.set._used != self._used:
514+ # Force this exception to continue to be raised
515+ self._used = -1
516+ raise RuntimeError("Set size changed during iteration")
517+ if not SimpleSet_Next(self.set, &self.pos, &key):
518+ self.set = None
519+ raise StopIteration
520+ # we found something
521+ the_key = <object>key # INCREF
522+ self.len = self.len - 1
523+ return the_key
524+
525+ def __length_hint__(self):
526+ if self.set is not None and self._used == self.set._used:
527+ return self.len
528+ return 0
529+
530+
531+
532+cdef api SimpleSet SimpleSet_New():
533+ """Create a new SimpleSet object."""
534+ return SimpleSet()
535+
536+
537+cdef SimpleSet _check_self(object self):
538+ """Check that the parameter is not None.
539+
540+ Pyrex/Cython will do type checking, but only to ensure that an object is
541+ either the right type or None. You can say "object foo not None" for pure
542+ python functions, but not for C functions.
543+ So this is just a helper for all the apis that need to do the check.
544+ """
545+ cdef SimpleSet true_self
546+ if self is None:
547+ raise TypeError('self must not be None')
548+ true_self = self
549+ return true_self
550+
551+
552+cdef PyObject **_lookup(SimpleSet self, object key) except NULL:
553+ """Find the slot where 'key' would fit.
554+
555+ This is the same as a dicts 'lookup' function.
556+
557+ :param key: An object we are looking up
558+ :param hash: The hash for key
559+ :return: The location in self.table where key should be put.
560+ location == NULL is an exception, but (*location) == NULL just
561+ indicates the slot is empty and can be used.
562+ """
563+ # This uses Quadratic Probing:
564+ # http://en.wikipedia.org/wiki/Quadratic_probing
565+ # with c1 = c2 = 1/2
566+ # This leads to probe locations at:
567+ # h0 = hash(k1)
568+ # h1 = h0 + 1
569+ # h2 = h0 + 3 = h1 + 1 + 1
570+ # h3 = h0 + 6 = h2 + 1 + 2
571+ # h4 = h0 + 10 = h2 + 1 + 3
572+ # Note that all of these are '& mask', but that is computed *after* the
573+ # offset.
574+ # This differs from the algorithm used by Set and Dict. Which, effectively,
575+ # use double-hashing, and a step size that starts large, but dwindles to
576+ # stepping one-by-one.
577+ # This gives more 'locality' in that if you have a collision at offset X,
578+ # the first fallback is X+1, which is fast to check. However, that means
579+ # that an object w/ hash X+1 will also check there, and then X+2 next.
580+ # However, for objects with differing hashes, their chains are different.
581+ # The former checks X, X+1, X+3, ... the latter checks X+1, X+2, X+4, ...
582+ # So different hashes diverge quickly.
583+ # A bigger problem is that we *only* ever use the lowest bits of the hash
584+ # So all integers (x + SIZE*N) will resolve into the same bucket, and all
585+ # use the same collision resolution. We may want to try to find a way to
586+ # incorporate the upper bits of the hash with quadratic probing. (For
587+ # example, X, X+1, X+3+some_upper_bits, X+6+more_upper_bits, etc.)
588+ cdef size_t i, n_lookup
589+ cdef Py_ssize_t mask
590+ cdef long key_hash
591+ cdef PyObject **table, **slot, *cur, **free_slot, *py_key
592+
593+ # hash is a signed long(), we are using an offset at unsigned size_t
594+ key_hash = hash(key)
595+ i = <size_t>key_hash
596+ mask = self._mask
597+ table = self._table
598+ free_slot = NULL
599+ py_key = <PyObject *>key
600+ for n_lookup from 0 <= n_lookup <= <size_t>mask: # Don't loop forever
601+ slot = &table[i & mask]
602+ cur = slot[0]
603+ if cur == NULL:
604+ # Found a blank spot
605+ if free_slot != NULL:
606+ # Did we find an earlier _dummy entry?
607+ return free_slot
608+ else:
609+ return slot
610+ if cur == py_key:
611+ # Found an exact pointer to the key
612+ return slot
613+ if cur == _dummy:
614+ if free_slot == NULL:
615+ free_slot = slot
616+ elif _is_equal(py_key, key_hash, cur):
617+ # Both py_key and cur belong in this slot, return it
618+ return slot
619+ i = i + 1 + n_lookup
620+ raise AssertionError('should never get here')
621+
622+
623+cdef api PyObject **_SimpleSet_Lookup(object self, object key) except NULL:
624+ """Find the slot where 'key' would fit.
625+
626+ This is the same as a dicts 'lookup' function. This is a private
627+ api because mutating what you get without maintaing the other invariants
628+ is a 'bad thing'.
629+
630+ :param key: An object we are looking up
631+ :param hash: The hash for key
632+ :return: The location in self._table where key should be put
633+ should never be NULL, but may reference a NULL (PyObject*)
634+ """
635+ return _lookup(_check_self(self), key)
636+
637+
638+cdef api object SimpleSet_Add(object self, object key):
639+ """Add a key to the SimpleSet (set).
640+
641+ :param self: The SimpleSet to add the key to.
642+ :param key: The key to be added. If the key is already present,
643+ self will not be modified
644+ :return: The current key stored at the location defined by 'key'.
645+ This may be the same object, or it may be an equivalent object.
646+ (consider dict.setdefault(key, key))
647+ """
648+ return _check_self(self)._add(key)
649+
650+
651+cdef api int SimpleSet_Contains(object self, object key) except -1:
652+ """Is key present in self?"""
653+ return (key in _check_self(self))
654+
655+
656+cdef api int SimpleSet_Discard(object self, object key) except -1:
657+ """Remove the object referenced at location 'key'.
658+
659+ :param self: The SimpleSet being modified
660+ :param key: The key we are checking on
661+ :return: 1 if there was an object present, 0 if there was not, and -1 on
662+ error.
663+ """
664+ return _check_self(self)._discard(key)
665+
666+
667+cdef api PyObject *SimpleSet_Get(SimpleSet self, object key) except? NULL:
668+ """Get a pointer to the object present at location 'key'.
669+
670+ This returns an object which is equal to key which was previously added to
671+ self. This returns a borrowed reference, as it may also return NULL if no
672+ value is present at that location.
673+
674+ :param key: The value we are looking for
675+ :return: The object present at that location
676+ """
677+ return _check_self(self)._get(key)
678+
679+
680+cdef api Py_ssize_t SimpleSet_Size(object self) except -1:
681+ """Get the number of active entries in 'self'"""
682+ return _check_self(self)._used
683+
684+
685+cdef api int SimpleSet_Next(object self, Py_ssize_t *pos, PyObject **key):
686+ """Walk over items in a SimpleSet.
687+
688+ :param pos: should be initialized to 0 by the caller, and will be updated
689+ by this function
690+ :param key: Will return a borrowed reference to key
691+ :return: 0 if nothing left, 1 if we are returning a new value
692+ """
693+ cdef Py_ssize_t i, mask
694+ cdef SimpleSet true_self
695+ cdef PyObject **table
696+ true_self = _check_self(self)
697+ i = pos[0]
698+ if (i < 0):
699+ return 0
700+ mask = true_self._mask
701+ table= true_self._table
702+ while (i <= mask and (table[i] == NULL or table[i] == _dummy)):
703+ i = i + 1
704+ pos[0] = i + 1
705+ if (i > mask):
706+ return 0 # All done
707+ if (key != NULL):
708+ key[0] = table[i]
709+ return 1
710+
711+
712+cdef int SimpleSet_traverse(SimpleSet self, visitproc visit, void *arg):
713+ """This is an implementation of 'tp_traverse' that hits the whole table.
714+
715+ Cython/Pyrex don't seem to let you define a tp_traverse, and they only
716+ define one for you if you have an 'object' attribute. Since they don't
717+ support C arrays of objects, we access the PyObject * directly.
718+ """
719+ cdef Py_ssize_t pos
720+ cdef PyObject *next_key
721+ cdef int ret
722+
723+ pos = 0
724+ while SimpleSet_Next(self, &pos, &next_key):
725+ ret = visit(next_key, arg)
726+ if ret:
727+ return ret
728+ return 0
729+
730+# It is a little bit ugly to do this, but it works, and means that Meliae can
731+# dump the total memory consumed by all child objects.
732+(<PyTypeObject *>SimpleSet).tp_traverse = <traverseproc>SimpleSet_traverse
733
734=== modified file 'bzrlib/python-compat.h'
735--- bzrlib/python-compat.h 2009-06-10 03:56:49 +0000
736+++ bzrlib/python-compat.h 2009-10-12 16:51:14 +0000
737@@ -73,4 +73,9 @@
738 #define snprintf _snprintf
739 #endif
740
741+/* Introduced in Python 2.6 */
742+#ifndef Py_TYPE
743+# define Py_TYPE(o) ((o)->ob_type)
744+#endif
745+
746 #endif /* _BZR_PYTHON_COMPAT_H */
747
748=== modified file 'bzrlib/tests/__init__.py'
749--- bzrlib/tests/__init__.py 2009-10-08 01:50:30 +0000
750+++ bzrlib/tests/__init__.py 2009-10-12 16:51:14 +0000
751@@ -3688,6 +3688,7 @@
752 'bzrlib.tests.test__groupcompress',
753 'bzrlib.tests.test__known_graph',
754 'bzrlib.tests.test__rio',
755+ 'bzrlib.tests.test__simple_set',
756 'bzrlib.tests.test__walkdirs_win32',
757 'bzrlib.tests.test_ancestry',
758 'bzrlib.tests.test_annotate',
759
760=== added file 'bzrlib/tests/test__simple_set.py'
761--- bzrlib/tests/test__simple_set.py 1970-01-01 00:00:00 +0000
762+++ bzrlib/tests/test__simple_set.py 2009-10-12 16:51:14 +0000
763@@ -0,0 +1,371 @@
764+# Copyright (C) 2009 Canonical Ltd
765+#
766+# This program is free software; you can redistribute it and/or modify
767+# it under the terms of the GNU General Public License as published by
768+# the Free Software Foundation; either version 2 of the License, or
769+# (at your option) any later version.
770+#
771+# This program is distributed in the hope that it will be useful,
772+# but WITHOUT ANY WARRANTY; without even the implied warranty of
773+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
774+# GNU General Public License for more details.
775+#
776+# You should have received a copy of the GNU General Public License
777+# along with this program; if not, write to the Free Software
778+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
779+
780+"""Tests for the StaticTupleInterned type."""
781+
782+import sys
783+
784+from bzrlib import (
785+ errors,
786+ osutils,
787+ tests,
788+ )
789+
790+try:
791+ from bzrlib import _simple_set_pyx
792+except ImportError:
793+ _simple_set_pyx = None
794+
795+
796+class _Hashable(object):
797+ """A simple object which has a fixed hash value.
798+
799+ We could have used an 'int', but it turns out that Int objects don't
800+ implement tp_richcompare...
801+ """
802+
803+ def __init__(self, the_hash):
804+ self.hash = the_hash
805+
806+ def __hash__(self):
807+ return self.hash
808+
809+ def __eq__(self, other):
810+ if not isinstance(other, _Hashable):
811+ return NotImplemented
812+ return other.hash == self.hash
813+
814+
815+class _BadSecondHash(_Hashable):
816+
817+ def __init__(self, the_hash):
818+ _Hashable.__init__(self, the_hash)
819+ self._first = True
820+
821+ def __hash__(self):
822+ if self._first:
823+ self._first = False
824+ return self.hash
825+ else:
826+ raise ValueError('I can only be hashed once.')
827+
828+
829+class _BadCompare(_Hashable):
830+
831+ def __eq__(self, other):
832+ raise RuntimeError('I refuse to play nice')
833+
834+
835+# Even though this is an extension, we don't permute the tests for a python
836+# version. As the plain python version is just a dict or set
837+
838+class _CompiledSimpleSet(tests.Feature):
839+
840+ def _probe(self):
841+ if _simple_set_pyx is None:
842+ return False
843+ return True
844+
845+ def feature_name(self):
846+ return 'bzrlib._simple_set_pyx'
847+
848+CompiledSimpleSet = _CompiledSimpleSet()
849+
850+
851+class TestSimpleSet(tests.TestCase):
852+
853+ _test_needs_features = [CompiledSimpleSet]
854+ module = _simple_set_pyx
855+
856+ def assertIn(self, obj, container):
857+ self.assertTrue(obj in container,
858+ '%s not found in %s' % (obj, container))
859+
860+ def assertNotIn(self, obj, container):
861+ self.assertTrue(obj not in container,
862+ 'We found %s in %s' % (obj, container))
863+
864+ def assertFillState(self, used, fill, mask, obj):
865+ self.assertEqual((used, fill, mask), (obj.used, obj.fill, obj.mask))
866+
867+ def assertLookup(self, offset, value, obj, key):
868+ self.assertEqual((offset, value), obj._test_lookup(key))
869+
870+ def assertRefcount(self, count, obj):
871+ """Assert that the refcount for obj is what we expect.
872+
873+ Note that this automatically adjusts for the fact that calling
874+ assertRefcount actually creates a new pointer, as does calling
875+ sys.getrefcount. So pass the expected value *before* the call.
876+ """
877+ # I'm not sure why the offset is 3, but I've check that in the caller,
878+ # an offset of 1 works, which is expected. Not sure why assertRefcount
879+ # is incrementing/decrementing 2 times
880+ self.assertEqual(count, sys.getrefcount(obj)-3)
881+
882+ def test_initial(self):
883+ obj = self.module.SimpleSet()
884+ self.assertEqual(0, len(obj))
885+ st = ('foo', 'bar')
886+ self.assertFillState(0, 0, 0x3ff, obj)
887+
888+ def test__lookup(self):
889+ # These are carefully chosen integers to force hash collisions in the
890+ # algorithm, based on the initial set size of 1024
891+ obj = self.module.SimpleSet()
892+ self.assertLookup(643, '<null>', obj, _Hashable(643))
893+ self.assertLookup(643, '<null>', obj, _Hashable(643 + 1024))
894+ self.assertLookup(643, '<null>', obj, _Hashable(643 + 50*1024))
895+
896+ def test__lookup_collision(self):
897+ obj = self.module.SimpleSet()
898+ k1 = _Hashable(643)
899+ k2 = _Hashable(643 + 1024)
900+ self.assertLookup(643, '<null>', obj, k1)
901+ self.assertLookup(643, '<null>', obj, k2)
902+ obj.add(k1)
903+ self.assertLookup(643, k1, obj, k1)
904+ self.assertLookup(644, '<null>', obj, k2)
905+
906+ def test__lookup_after_resize(self):
907+ obj = self.module.SimpleSet()
908+ k1 = _Hashable(643)
909+ k2 = _Hashable(643 + 1024)
910+ obj.add(k1)
911+ obj.add(k2)
912+ self.assertLookup(643, k1, obj, k1)
913+ self.assertLookup(644, k2, obj, k2)
914+ obj._py_resize(2047) # resized to 2048
915+ self.assertEqual(2048, obj.mask + 1)
916+ self.assertLookup(643, k1, obj, k1)
917+ self.assertLookup(643+1024, k2, obj, k2)
918+ obj._py_resize(1023) # resized back to 1024
919+ self.assertEqual(1024, obj.mask + 1)
920+ self.assertLookup(643, k1, obj, k1)
921+ self.assertLookup(644, k2, obj, k2)
922+
923+ def test_get_set_del_with_collisions(self):
924+ obj = self.module.SimpleSet()
925+
926+ h1 = 643
927+ h2 = 643 + 1024
928+ h3 = 643 + 1024*50
929+ h4 = 643 + 1024*25
930+ h5 = 644
931+ h6 = 644 + 1024
932+
933+ k1 = _Hashable(h1)
934+ k2 = _Hashable(h2)
935+ k3 = _Hashable(h3)
936+ k4 = _Hashable(h4)
937+ k5 = _Hashable(h5)
938+ k6 = _Hashable(h6)
939+ self.assertLookup(643, '<null>', obj, k1)
940+ self.assertLookup(643, '<null>', obj, k2)
941+ self.assertLookup(643, '<null>', obj, k3)
942+ self.assertLookup(643, '<null>', obj, k4)
943+ self.assertLookup(644, '<null>', obj, k5)
944+ self.assertLookup(644, '<null>', obj, k6)
945+ obj.add(k1)
946+ self.assertIn(k1, obj)
947+ self.assertNotIn(k2, obj)
948+ self.assertNotIn(k3, obj)
949+ self.assertNotIn(k4, obj)
950+ self.assertLookup(643, k1, obj, k1)
951+ self.assertLookup(644, '<null>', obj, k2)
952+ self.assertLookup(644, '<null>', obj, k3)
953+ self.assertLookup(644, '<null>', obj, k4)
954+ self.assertLookup(644, '<null>', obj, k5)
955+ self.assertLookup(644, '<null>', obj, k6)
956+ self.assertIs(k1, obj[k1])
957+ self.assertIs(k2, obj.add(k2))
958+ self.assertIs(k2, obj[k2])
959+ self.assertLookup(643, k1, obj, k1)
960+ self.assertLookup(644, k2, obj, k2)
961+ self.assertLookup(646, '<null>', obj, k3)
962+ self.assertLookup(646, '<null>', obj, k4)
963+ self.assertLookup(645, '<null>', obj, k5)
964+ self.assertLookup(645, '<null>', obj, k6)
965+ self.assertLookup(643, k1, obj, _Hashable(h1))
966+ self.assertLookup(644, k2, obj, _Hashable(h2))
967+ self.assertLookup(646, '<null>', obj, _Hashable(h3))
968+ self.assertLookup(646, '<null>', obj, _Hashable(h4))
969+ self.assertLookup(645, '<null>', obj, _Hashable(h5))
970+ self.assertLookup(645, '<null>', obj, _Hashable(h6))
971+ obj.add(k3)
972+ self.assertIs(k3, obj[k3])
973+ self.assertIn(k1, obj)
974+ self.assertIn(k2, obj)
975+ self.assertIn(k3, obj)
976+ self.assertNotIn(k4, obj)
977+
978+ obj.discard(k1)
979+ self.assertLookup(643, '<dummy>', obj, k1)
980+ self.assertLookup(644, k2, obj, k2)
981+ self.assertLookup(646, k3, obj, k3)
982+ self.assertLookup(643, '<dummy>', obj, k4)
983+ self.assertNotIn(k1, obj)
984+ self.assertIn(k2, obj)
985+ self.assertIn(k3, obj)
986+ self.assertNotIn(k4, obj)
987+
988+ def test_add(self):
989+ obj = self.module.SimpleSet()
990+ self.assertFillState(0, 0, 0x3ff, obj)
991+ # We use this clumsy notation, because otherwise the refcounts are off.
992+ # I'm guessing the python compiler sees it is a static tuple, and adds
993+ # it to the function variables, or somesuch
994+ k1 = tuple(['foo'])
995+ self.assertRefcount(1, k1)
996+ self.assertIs(k1, obj.add(k1))
997+ self.assertFillState(1, 1, 0x3ff, obj)
998+ self.assertRefcount(2, k1)
999+ ktest = obj[k1]
1000+ self.assertRefcount(3, k1)
1001+ self.assertIs(k1, ktest)
1002+ del ktest
1003+ self.assertRefcount(2, k1)
1004+ k2 = tuple(['foo'])
1005+ self.assertRefcount(1, k2)
1006+ self.assertIsNot(k1, k2)
1007+ # doesn't add anything, so the counters shouldn't be adjusted
1008+ self.assertIs(k1, obj.add(k2))
1009+ self.assertFillState(1, 1, 0x3ff, obj)
1010+ self.assertRefcount(2, k1) # not changed
1011+ self.assertRefcount(1, k2) # not incremented
1012+ self.assertIs(k1, obj[k1])
1013+ self.assertIs(k1, obj[k2])
1014+ self.assertRefcount(2, k1)
1015+ self.assertRefcount(1, k2)
1016+ # Deleting an entry should remove the fill, but not the used
1017+ obj.discard(k1)
1018+ self.assertFillState(0, 1, 0x3ff, obj)
1019+ self.assertRefcount(1, k1)
1020+ k3 = tuple(['bar'])
1021+ self.assertRefcount(1, k3)
1022+ self.assertIs(k3, obj.add(k3))
1023+ self.assertFillState(1, 2, 0x3ff, obj)
1024+ self.assertRefcount(2, k3)
1025+ self.assertIs(k2, obj.add(k2))
1026+ self.assertFillState(2, 2, 0x3ff, obj)
1027+ self.assertRefcount(1, k1)
1028+ self.assertRefcount(2, k2)
1029+ self.assertRefcount(2, k3)
1030+
1031+ def test_discard(self):
1032+ obj = self.module.SimpleSet()
1033+ k1 = tuple(['foo'])
1034+ k2 = tuple(['foo'])
1035+ k3 = tuple(['bar'])
1036+ self.assertRefcount(1, k1)
1037+ self.assertRefcount(1, k2)
1038+ self.assertRefcount(1, k3)
1039+ obj.add(k1)
1040+ self.assertRefcount(2, k1)
1041+ self.assertEqual(0, obj.discard(k3))
1042+ self.assertRefcount(1, k3)
1043+ obj.add(k3)
1044+ self.assertRefcount(2, k3)
1045+ self.assertEqual(1, obj.discard(k3))
1046+ self.assertRefcount(1, k3)
1047+
1048+ def test__resize(self):
1049+ obj = self.module.SimpleSet()
1050+ k1 = ('foo',)
1051+ k2 = ('bar',)
1052+ k3 = ('baz',)
1053+ obj.add(k1)
1054+ obj.add(k2)
1055+ obj.add(k3)
1056+ obj.discard(k2)
1057+ self.assertFillState(2, 3, 0x3ff, obj)
1058+ self.assertEqual(1024, obj._py_resize(500))
1059+ # Doesn't change the size, but does change the content
1060+ self.assertFillState(2, 2, 0x3ff, obj)
1061+ obj.add(k2)
1062+ obj.discard(k3)
1063+ self.assertFillState(2, 3, 0x3ff, obj)
1064+ self.assertEqual(4096, obj._py_resize(4095))
1065+ self.assertFillState(2, 2, 0xfff, obj)
1066+ self.assertIn(k1, obj)
1067+ self.assertIn(k2, obj)
1068+ self.assertNotIn(k3, obj)
1069+ obj.add(k2)
1070+ self.assertIn(k2, obj)
1071+ obj.discard(k2)
1072+ self.assertEqual((591, '<dummy>'), obj._test_lookup(k2))
1073+ self.assertFillState(1, 2, 0xfff, obj)
1074+ self.assertEqual(2048, obj._py_resize(1024))
1075+ self.assertFillState(1, 1, 0x7ff, obj)
1076+ self.assertEqual((591, '<null>'), obj._test_lookup(k2))
1077+
1078+ def test_second_hash_failure(self):
1079+ obj = self.module.SimpleSet()
1080+ k1 = _BadSecondHash(200)
1081+ k2 = _Hashable(200)
1082+ # Should only call hash() one time
1083+ obj.add(k1)
1084+ self.assertFalse(k1._first)
1085+ self.assertRaises(ValueError, obj.add, k2)
1086+
1087+ def test_richcompare_failure(self):
1088+ obj = self.module.SimpleSet()
1089+ k1 = _Hashable(200)
1090+ k2 = _BadCompare(200)
1091+ obj.add(k1)
1092+ # Tries to compare with k1, fails
1093+ self.assertRaises(RuntimeError, obj.add, k2)
1094+
1095+ def test_add_and_remove_lots_of_items(self):
1096+ obj = self.module.SimpleSet()
1097+ chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'
1098+ for i in chars:
1099+ for j in chars:
1100+ k = (i, j)
1101+ obj.add(k)
1102+ num = len(chars)*len(chars)
1103+ self.assertFillState(num, num, 0x1fff, obj)
1104+ # Now delete all of the entries and it should shrink again
1105+ for i in chars:
1106+ for j in chars:
1107+ k = (i, j)
1108+ obj.discard(k)
1109+ # It should be back to 1024 wide mask, though there may still be some
1110+ # dummy values in there
1111+ self.assertFillState(0, obj.fill, 0x3ff, obj)
1112+ # but there should be fewer than 1/5th dummy entries
1113+ self.assertTrue(obj.fill < 1024 / 5)
1114+
1115+ def test__iter__(self):
1116+ obj = self.module.SimpleSet()
1117+ k1 = ('1',)
1118+ k2 = ('1', '2')
1119+ k3 = ('3', '4')
1120+ obj.add(k1)
1121+ obj.add(k2)
1122+ obj.add(k3)
1123+ all = set()
1124+ for key in obj:
1125+ all.add(key)
1126+ self.assertEqual(sorted([k1, k2, k3]), sorted(all))
1127+ iterator = iter(obj)
1128+ iterator.next()
1129+ obj.add(('foo',))
1130+ # Set changed size
1131+ self.assertRaises(RuntimeError, iterator.next)
1132+ # And even removing an item still causes it to fail
1133+ obj.discard(k2)
1134+ self.assertRaises(RuntimeError, iterator.next)
1135
1136=== modified file 'setup.py'
1137--- setup.py 2009-10-01 03:46:41 +0000
1138+++ setup.py 2009-10-12 16:51:14 +0000
1139@@ -300,6 +300,7 @@
1140 add_pyrex_extension('bzrlib._chk_map_pyx', libraries=[z_lib])
1141 ext_modules.append(Extension('bzrlib._patiencediff_c',
1142 ['bzrlib/_patiencediff_c.c']))
1143+add_pyrex_extension('bzrlib._simple_set_pyx')
1144
1145
1146 if unavailable_files: