閱讀662 返回首頁    go 阿裏雲 go 技術社區[雲棲]


[筆記]PyDictObject的哈希算法和搜索過程

哈希函數如下:
long
PyObject_Hash(PyObject *v)
{
    PyTypeObject *tp = v->ob_type;
    if (tp->tp_hash != NULL)
        return (*tp->tp_hash)(v);
    /* To keep to the general practice that inheriting
     * solely from object in C code should work without
     * an explicit call to PyType_Ready, we implicitly call
     * PyType_Ready here and then check the tp_hash slot again
     */
    if (tp->tp_dict == NULL) {
        if (PyType_Ready(tp) < 0)
            return -1;
        if (tp->tp_hash != NULL)
            return (*tp->tp_hash)(v);
    }
    if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
        return _Py_HashPointer(v); /* Use address as hash value */
    }
    /* If there's a cmp but no hash defined, the object can't be hashed */
    return PyObject_HashNotImplemented(v);
}


搜索過程則是根據hash值確定表項位置,進行比較。
如果表項比較成功或者表現是Unused狀態,返回。
如果表現是Dummy狀態,則設置freeslot指向該位置,並向下一個位置進行比較。
    for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
        i = (i << 2) + i + perturb + 1;
        ep = &ep0[i & mask];



最後更新:2017-04-02 22:16:33

  上一篇:go [筆記]PyCodeObject初探
  下一篇:go [筆記]PyDictObject頭文件閱讀