dictobject.c 175 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851
  1. /* Dictionary object implementation using a hash table */
  2. /* The distribution includes a separate file, Objects/dictnotes.txt,
  3. describing explorations into dictionary design and optimization.
  4. It covers typical dictionary use patterns, the parameters for
  5. tuning dictionaries, and several ideas for possible optimizations.
  6. */
  7. /* PyDictKeysObject
  8. This implements the dictionary's hashtable.
  9. As of Python 3.6, this is compact and ordered. Basic idea is described here:
  10. * https://mail.python.org/pipermail/python-dev/2012-December/123028.html
  11. * https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
  12. layout:
  13. +---------------------+
  14. | dk_refcnt |
  15. | dk_log2_size |
  16. | dk_log2_index_bytes |
  17. | dk_kind |
  18. | dk_usable |
  19. | dk_nentries |
  20. +---------------------+
  21. | dk_indices[] |
  22. | |
  23. +---------------------+
  24. | dk_entries[] |
  25. | |
  26. +---------------------+
  27. dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1)
  28. or DKIX_DUMMY(-2).
  29. Size of indices is dk_size. Type of each index in indices is vary on dk_size:
  30. * int8 for dk_size <= 128
  31. * int16 for 256 <= dk_size <= 2**15
  32. * int32 for 2**16 <= dk_size <= 2**31
  33. * int64 for 2**32 <= dk_size
  34. dk_entries is array of PyDictKeyEntry when dk_kind == DICT_KEYS_GENERAL or
  35. PyDictUnicodeEntry otherwise. Its length is USABLE_FRACTION(dk_size).
  36. NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
  37. dk_indices entry is signed integer and int16 is used for table which
  38. dk_size == 256.
  39. */
  40. /*
  41. The DictObject can be in one of two forms.
  42. Either:
  43. A combined table:
  44. ma_values == NULL, dk_refcnt == 1.
  45. Values are stored in the me_value field of the PyDictKeysObject.
  46. Or:
  47. A split table:
  48. ma_values != NULL, dk_refcnt >= 1
  49. Values are stored in the ma_values array.
  50. Only string (unicode) keys are allowed.
  51. There are four kinds of slots in the table (slot is index, and
  52. DK_ENTRIES(keys)[index] if index >= 0):
  53. 1. Unused. index == DKIX_EMPTY
  54. Does not hold an active (key, value) pair now and never did. Unused can
  55. transition to Active upon key insertion. This is each slot's initial state.
  56. 2. Active. index >= 0, me_key != NULL and me_value != NULL
  57. Holds an active (key, value) pair. Active can transition to Dummy or
  58. Pending upon key deletion (for combined and split tables respectively).
  59. This is the only case in which me_value != NULL.
  60. 3. Dummy. index == DKIX_DUMMY (combined only)
  61. Previously held an active (key, value) pair, but that was deleted and an
  62. active pair has not yet overwritten the slot. Dummy can transition to
  63. Active upon key insertion. Dummy slots cannot be made Unused again
  64. else the probe sequence in case of collision would have no way to know
  65. they were once active.
  66. 4. Pending. index >= 0, key != NULL, and value == NULL (split only)
  67. Not yet inserted in split-table.
  68. */
  69. /*
  70. Preserving insertion order
  71. It's simple for combined table. Since dk_entries is mostly append only, we can
  72. get insertion order by just iterating dk_entries.
  73. One exception is .popitem(). It removes last item in dk_entries and decrement
  74. dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in
  75. dk_indices, we can't increment dk_usable even though dk_nentries is
  76. decremented.
  77. To preserve the order in a split table, a bit vector is used to record the
  78. insertion order. When a key is inserted the bit vector is shifted up by 4 bits
  79. and the index of the key is stored in the low 4 bits.
  80. As a consequence of this, split keys have a maximum size of 16.
  81. */
  82. /* PyDict_MINSIZE is the starting size for any new dict.
  83. * 8 allows dicts with no more than 5 active entries; experiments suggested
  84. * this suffices for the majority of dicts (consisting mostly of usually-small
  85. * dicts created to pass keyword arguments).
  86. * Making this 8, rather than 4 reduces the number of resizes for most
  87. * dictionaries, without any significant extra memory use.
  88. */
  89. #define PyDict_LOG_MINSIZE 3
  90. #define PyDict_MINSIZE 8
  91. #include "Python.h"
  92. #include "pycore_bitutils.h" // _Py_bit_length
  93. #include "pycore_call.h" // _PyObject_CallNoArgs()
  94. #include "pycore_code.h" // stats
  95. #include "pycore_dict.h" // PyDictKeysObject
  96. #include "pycore_gc.h" // _PyObject_GC_IS_TRACKED()
  97. #include "pycore_object.h" // _PyObject_GC_TRACK()
  98. #include "pycore_pyerrors.h" // _PyErr_GetRaisedException()
  99. #include "pycore_pystate.h" // _PyThreadState_GET()
  100. #include "stringlib/eq.h" // unicode_eq()
  101. #include <stdbool.h>
  102. /*[clinic input]
  103. class dict "PyDictObject *" "&PyDict_Type"
  104. [clinic start generated code]*/
  105. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
  106. /*
  107. To ensure the lookup algorithm terminates, there must be at least one Unused
  108. slot (NULL key) in the table.
  109. To avoid slowing down lookups on a near-full table, we resize the table when
  110. it's USABLE_FRACTION (currently two-thirds) full.
  111. */
  112. #define PERTURB_SHIFT 5
  113. /*
  114. Major subtleties ahead: Most hash schemes depend on having a "good" hash
  115. function, in the sense of simulating randomness. Python doesn't: its most
  116. important hash functions (for ints) are very regular in common
  117. cases:
  118. >>>[hash(i) for i in range(4)]
  119. [0, 1, 2, 3]
  120. This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
  121. the low-order i bits as the initial table index is extremely fast, and there
  122. are no collisions at all for dicts indexed by a contiguous range of ints. So
  123. this gives better-than-random behavior in common cases, and that's very
  124. desirable.
  125. OTOH, when collisions occur, the tendency to fill contiguous slices of the
  126. hash table makes a good collision resolution strategy crucial. Taking only
  127. the last i bits of the hash code is also vulnerable: for example, consider
  128. the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
  129. their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
  130. of every hash code are all 0: they *all* map to the same table index.
  131. But catering to unusual cases should not slow the usual ones, so we just take
  132. the last i bits anyway. It's up to collision resolution to do the rest. If
  133. we *usually* find the key we're looking for on the first try (and, it turns
  134. out, we usually do -- the table load factor is kept under 2/3, so the odds
  135. are solidly in our favor), then it makes best sense to keep the initial index
  136. computation dirt cheap.
  137. The first half of collision resolution is to visit table indices via this
  138. recurrence:
  139. j = ((5*j) + 1) mod 2**i
  140. For any initial j in range(2**i), repeating that 2**i times generates each
  141. int in range(2**i) exactly once (see any text on random-number generation for
  142. proof). By itself, this doesn't help much: like linear probing (setting
  143. j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
  144. order. This would be bad, except that's not the only thing we do, and it's
  145. actually *good* in the common cases where hash keys are consecutive. In an
  146. example that's really too small to make this entirely clear, for a table of
  147. size 2**3 the order of indices is:
  148. 0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
  149. If two things come in at index 5, the first place we look after is index 2,
  150. not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
  151. Linear probing is deadly in this case because there the fixed probe order
  152. is the *same* as the order consecutive keys are likely to arrive. But it's
  153. extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
  154. and certain that consecutive hash codes do not.
  155. The other half of the strategy is to get the other bits of the hash code
  156. into play. This is done by initializing a (unsigned) vrbl "perturb" to the
  157. full hash code, and changing the recurrence to:
  158. perturb >>= PERTURB_SHIFT;
  159. j = (5*j) + 1 + perturb;
  160. use j % 2**i as the next table index;
  161. Now the probe sequence depends (eventually) on every bit in the hash code,
  162. and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
  163. because it quickly magnifies small differences in the bits that didn't affect
  164. the initial index. Note that because perturb is unsigned, if the recurrence
  165. is executed often enough perturb eventually becomes and remains 0. At that
  166. point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
  167. that's certain to find an empty slot eventually (since it generates every int
  168. in range(2**i), and we make sure there's always at least one empty slot).
  169. Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
  170. small so that the high bits of the hash code continue to affect the probe
  171. sequence across iterations; but you want it large so that in really bad cases
  172. the high-order hash bits have an effect on early iterations. 5 was "the
  173. best" in minimizing total collisions across experiments Tim Peters ran (on
  174. both normal and pathological cases), but 4 and 6 weren't significantly worse.
  175. Historical: Reimer Behrends contributed the idea of using a polynomial-based
  176. approach, using repeated multiplication by x in GF(2**n) where an irreducible
  177. polynomial for each table size was chosen such that x was a primitive root.
  178. Christian Tismer later extended that to use division by x instead, as an
  179. efficient way to get the high bits of the hash code into play. This scheme
  180. also gave excellent collision statistics, but was more expensive: two
  181. if-tests were required inside the loop; computing "the next" index took about
  182. the same number of operations but without as much potential parallelism
  183. (e.g., computing 5*j can go on at the same time as computing 1+perturb in the
  184. above, and then shifting perturb can be done while the table index is being
  185. masked); and the PyDictObject struct required a member to hold the table's
  186. polynomial. In Tim's experiments the current scheme ran faster, produced
  187. equally good collision statistics, needed less code & used less memory.
  188. */
  189. static int dictresize(PyInterpreterState *interp, PyDictObject *mp,
  190. uint8_t log_newsize, int unicode);
  191. static PyObject* dict_iter(PyDictObject *dict);
  192. #include "clinic/dictobject.c.h"
  193. #if PyDict_MAXFREELIST > 0
  194. static struct _Py_dict_state *
  195. get_dict_state(PyInterpreterState *interp)
  196. {
  197. return &interp->dict_state;
  198. }
  199. #endif
  200. void
  201. _PyDict_ClearFreeList(PyInterpreterState *interp)
  202. {
  203. #if PyDict_MAXFREELIST > 0
  204. struct _Py_dict_state *state = &interp->dict_state;
  205. while (state->numfree) {
  206. PyDictObject *op = state->free_list[--state->numfree];
  207. assert(PyDict_CheckExact(op));
  208. PyObject_GC_Del(op);
  209. }
  210. while (state->keys_numfree) {
  211. PyObject_Free(state->keys_free_list[--state->keys_numfree]);
  212. }
  213. #endif
  214. }
  215. void
  216. _PyDict_Fini(PyInterpreterState *interp)
  217. {
  218. _PyDict_ClearFreeList(interp);
  219. #if defined(Py_DEBUG) && PyDict_MAXFREELIST > 0
  220. struct _Py_dict_state *state = &interp->dict_state;
  221. state->numfree = -1;
  222. state->keys_numfree = -1;
  223. #endif
  224. }
  225. static inline Py_hash_t
  226. unicode_get_hash(PyObject *o)
  227. {
  228. assert(PyUnicode_CheckExact(o));
  229. return _PyASCIIObject_CAST(o)->hash;
  230. }
  231. /* Print summary info about the state of the optimized allocator */
  232. void
  233. _PyDict_DebugMallocStats(FILE *out)
  234. {
  235. #if PyDict_MAXFREELIST > 0
  236. PyInterpreterState *interp = _PyInterpreterState_GET();
  237. struct _Py_dict_state *state = get_dict_state(interp);
  238. _PyDebugAllocatorStats(out, "free PyDictObject",
  239. state->numfree, sizeof(PyDictObject));
  240. #endif
  241. }
  242. #define DK_MASK(dk) (DK_SIZE(dk)-1)
  243. static void free_keys_object(PyInterpreterState *interp, PyDictKeysObject *keys);
  244. /* PyDictKeysObject has refcounts like PyObject does, so we have the
  245. following two functions to mirror what Py_INCREF() and Py_DECREF() do.
  246. (Keep in mind that PyDictKeysObject isn't actually a PyObject.)
  247. Likewise a PyDictKeysObject can be immortal (e.g. Py_EMPTY_KEYS),
  248. so we apply a naive version of what Py_INCREF() and Py_DECREF() do
  249. for immortal objects. */
  250. static inline void
  251. dictkeys_incref(PyDictKeysObject *dk)
  252. {
  253. if (dk->dk_refcnt == _Py_IMMORTAL_REFCNT) {
  254. return;
  255. }
  256. #ifdef Py_REF_DEBUG
  257. _Py_IncRefTotal(_PyInterpreterState_GET());
  258. #endif
  259. dk->dk_refcnt++;
  260. }
  261. static inline void
  262. dictkeys_decref(PyInterpreterState *interp, PyDictKeysObject *dk)
  263. {
  264. if (dk->dk_refcnt == _Py_IMMORTAL_REFCNT) {
  265. return;
  266. }
  267. assert(dk->dk_refcnt > 0);
  268. #ifdef Py_REF_DEBUG
  269. _Py_DecRefTotal(_PyInterpreterState_GET());
  270. #endif
  271. if (--dk->dk_refcnt == 0) {
  272. free_keys_object(interp, dk);
  273. }
  274. }
  275. /* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
  276. static inline Py_ssize_t
  277. dictkeys_get_index(const PyDictKeysObject *keys, Py_ssize_t i)
  278. {
  279. int log2size = DK_LOG_SIZE(keys);
  280. Py_ssize_t ix;
  281. if (log2size < 8) {
  282. const int8_t *indices = (const int8_t*)(keys->dk_indices);
  283. ix = indices[i];
  284. }
  285. else if (log2size < 16) {
  286. const int16_t *indices = (const int16_t*)(keys->dk_indices);
  287. ix = indices[i];
  288. }
  289. #if SIZEOF_VOID_P > 4
  290. else if (log2size >= 32) {
  291. const int64_t *indices = (const int64_t*)(keys->dk_indices);
  292. ix = indices[i];
  293. }
  294. #endif
  295. else {
  296. const int32_t *indices = (const int32_t*)(keys->dk_indices);
  297. ix = indices[i];
  298. }
  299. assert(ix >= DKIX_DUMMY);
  300. return ix;
  301. }
  302. /* write to indices. */
  303. static inline void
  304. dictkeys_set_index(PyDictKeysObject *keys, Py_ssize_t i, Py_ssize_t ix)
  305. {
  306. int log2size = DK_LOG_SIZE(keys);
  307. assert(ix >= DKIX_DUMMY);
  308. assert(keys->dk_version == 0);
  309. if (log2size < 8) {
  310. int8_t *indices = (int8_t*)(keys->dk_indices);
  311. assert(ix <= 0x7f);
  312. indices[i] = (char)ix;
  313. }
  314. else if (log2size < 16) {
  315. int16_t *indices = (int16_t*)(keys->dk_indices);
  316. assert(ix <= 0x7fff);
  317. indices[i] = (int16_t)ix;
  318. }
  319. #if SIZEOF_VOID_P > 4
  320. else if (log2size >= 32) {
  321. int64_t *indices = (int64_t*)(keys->dk_indices);
  322. indices[i] = ix;
  323. }
  324. #endif
  325. else {
  326. int32_t *indices = (int32_t*)(keys->dk_indices);
  327. assert(ix <= 0x7fffffff);
  328. indices[i] = (int32_t)ix;
  329. }
  330. }
  331. /* USABLE_FRACTION is the maximum dictionary load.
  332. * Increasing this ratio makes dictionaries more dense resulting in more
  333. * collisions. Decreasing it improves sparseness at the expense of spreading
  334. * indices over more cache lines and at the cost of total memory consumed.
  335. *
  336. * USABLE_FRACTION must obey the following:
  337. * (0 < USABLE_FRACTION(n) < n) for all n >= 2
  338. *
  339. * USABLE_FRACTION should be quick to calculate.
  340. * Fractions around 1/2 to 2/3 seem to work well in practice.
  341. */
  342. #define USABLE_FRACTION(n) (((n) << 1)/3)
  343. /* Find the smallest dk_size >= minsize. */
  344. static inline uint8_t
  345. calculate_log2_keysize(Py_ssize_t minsize)
  346. {
  347. #if SIZEOF_LONG == SIZEOF_SIZE_T
  348. minsize = (minsize | PyDict_MINSIZE) - 1;
  349. return _Py_bit_length(minsize | (PyDict_MINSIZE-1));
  350. #elif defined(_MSC_VER)
  351. // On 64bit Windows, sizeof(long) == 4.
  352. minsize = (minsize | PyDict_MINSIZE) - 1;
  353. unsigned long msb;
  354. _BitScanReverse64(&msb, (uint64_t)minsize);
  355. return (uint8_t)(msb + 1);
  356. #else
  357. uint8_t log2_size;
  358. for (log2_size = PyDict_LOG_MINSIZE;
  359. (((Py_ssize_t)1) << log2_size) < minsize;
  360. log2_size++)
  361. ;
  362. return log2_size;
  363. #endif
  364. }
  365. /* estimate_keysize is reverse function of USABLE_FRACTION.
  366. *
  367. * This can be used to reserve enough size to insert n entries without
  368. * resizing.
  369. */
  370. static inline uint8_t
  371. estimate_log2_keysize(Py_ssize_t n)
  372. {
  373. return calculate_log2_keysize((n*3 + 1) / 2);
  374. }
  375. /* GROWTH_RATE. Growth rate upon hitting maximum load.
  376. * Currently set to used*3.
  377. * This means that dicts double in size when growing without deletions,
  378. * but have more head room when the number of deletions is on a par with the
  379. * number of insertions. See also bpo-17563 and bpo-33205.
  380. *
  381. * GROWTH_RATE was set to used*4 up to version 3.2.
  382. * GROWTH_RATE was set to used*2 in version 3.3.0
  383. * GROWTH_RATE was set to used*2 + capacity/2 in 3.4.0-3.6.0.
  384. */
  385. #define GROWTH_RATE(d) ((d)->ma_used*3)
  386. /* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
  387. * (which cannot fail and thus can do no allocation).
  388. */
  389. static PyDictKeysObject empty_keys_struct = {
  390. _Py_IMMORTAL_REFCNT, /* dk_refcnt */
  391. 0, /* dk_log2_size */
  392. 0, /* dk_log2_index_bytes */
  393. DICT_KEYS_UNICODE, /* dk_kind */
  394. 1, /* dk_version */
  395. 0, /* dk_usable (immutable) */
  396. 0, /* dk_nentries */
  397. {DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY,
  398. DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY, DKIX_EMPTY}, /* dk_indices */
  399. };
  400. #define Py_EMPTY_KEYS &empty_keys_struct
  401. /* Uncomment to check the dict content in _PyDict_CheckConsistency() */
  402. // #define DEBUG_PYDICT
  403. #ifdef DEBUG_PYDICT
  404. # define ASSERT_CONSISTENT(op) assert(_PyDict_CheckConsistency((PyObject *)(op), 1))
  405. #else
  406. # define ASSERT_CONSISTENT(op) assert(_PyDict_CheckConsistency((PyObject *)(op), 0))
  407. #endif
  408. static inline int
  409. get_index_from_order(PyDictObject *mp, Py_ssize_t i)
  410. {
  411. assert(mp->ma_used <= SHARED_KEYS_MAX_SIZE);
  412. assert(i < (((char *)mp->ma_values)[-2]));
  413. return ((char *)mp->ma_values)[-3-i];
  414. }
  415. #ifdef DEBUG_PYDICT
  416. static void
  417. dump_entries(PyDictKeysObject *dk)
  418. {
  419. for (Py_ssize_t i = 0; i < dk->dk_nentries; i++) {
  420. if (DK_IS_UNICODE(dk)) {
  421. PyDictUnicodeEntry *ep = &DK_UNICODE_ENTRIES(dk)[i];
  422. printf("key=%p value=%p\n", ep->me_key, ep->me_value);
  423. }
  424. else {
  425. PyDictKeyEntry *ep = &DK_ENTRIES(dk)[i];
  426. printf("key=%p hash=%lx value=%p\n", ep->me_key, ep->me_hash, ep->me_value);
  427. }
  428. }
  429. }
  430. #endif
  431. int
  432. _PyDict_CheckConsistency(PyObject *op, int check_content)
  433. {
  434. #define CHECK(expr) \
  435. do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
  436. assert(op != NULL);
  437. CHECK(PyDict_Check(op));
  438. PyDictObject *mp = (PyDictObject *)op;
  439. PyDictKeysObject *keys = mp->ma_keys;
  440. int splitted = _PyDict_HasSplitTable(mp);
  441. Py_ssize_t usable = USABLE_FRACTION(DK_SIZE(keys));
  442. CHECK(0 <= mp->ma_used && mp->ma_used <= usable);
  443. CHECK(0 <= keys->dk_usable && keys->dk_usable <= usable);
  444. CHECK(0 <= keys->dk_nentries && keys->dk_nentries <= usable);
  445. CHECK(keys->dk_usable + keys->dk_nentries <= usable);
  446. if (!splitted) {
  447. /* combined table */
  448. CHECK(keys->dk_kind != DICT_KEYS_SPLIT);
  449. CHECK(keys->dk_refcnt == 1 || keys == Py_EMPTY_KEYS);
  450. }
  451. else {
  452. CHECK(keys->dk_kind == DICT_KEYS_SPLIT);
  453. CHECK(mp->ma_used <= SHARED_KEYS_MAX_SIZE);
  454. }
  455. if (check_content) {
  456. for (Py_ssize_t i=0; i < DK_SIZE(keys); i++) {
  457. Py_ssize_t ix = dictkeys_get_index(keys, i);
  458. CHECK(DKIX_DUMMY <= ix && ix <= usable);
  459. }
  460. if (keys->dk_kind == DICT_KEYS_GENERAL) {
  461. PyDictKeyEntry *entries = DK_ENTRIES(keys);
  462. for (Py_ssize_t i=0; i < usable; i++) {
  463. PyDictKeyEntry *entry = &entries[i];
  464. PyObject *key = entry->me_key;
  465. if (key != NULL) {
  466. /* test_dict fails if PyObject_Hash() is called again */
  467. CHECK(entry->me_hash != -1);
  468. CHECK(entry->me_value != NULL);
  469. if (PyUnicode_CheckExact(key)) {
  470. Py_hash_t hash = unicode_get_hash(key);
  471. CHECK(entry->me_hash == hash);
  472. }
  473. }
  474. }
  475. }
  476. else {
  477. PyDictUnicodeEntry *entries = DK_UNICODE_ENTRIES(keys);
  478. for (Py_ssize_t i=0; i < usable; i++) {
  479. PyDictUnicodeEntry *entry = &entries[i];
  480. PyObject *key = entry->me_key;
  481. if (key != NULL) {
  482. CHECK(PyUnicode_CheckExact(key));
  483. Py_hash_t hash = unicode_get_hash(key);
  484. CHECK(hash != -1);
  485. if (!splitted) {
  486. CHECK(entry->me_value != NULL);
  487. }
  488. }
  489. if (splitted) {
  490. CHECK(entry->me_value == NULL);
  491. }
  492. }
  493. }
  494. if (splitted) {
  495. CHECK(mp->ma_used <= SHARED_KEYS_MAX_SIZE);
  496. /* splitted table */
  497. int duplicate_check = 0;
  498. for (Py_ssize_t i=0; i < mp->ma_used; i++) {
  499. int index = get_index_from_order(mp, i);
  500. CHECK((duplicate_check & (1<<index)) == 0);
  501. duplicate_check |= (1<<index);
  502. CHECK(mp->ma_values->values[index] != NULL);
  503. }
  504. }
  505. }
  506. return 1;
  507. #undef CHECK
  508. }
  509. static PyDictKeysObject*
  510. new_keys_object(PyInterpreterState *interp, uint8_t log2_size, bool unicode)
  511. {
  512. PyDictKeysObject *dk;
  513. Py_ssize_t usable;
  514. int log2_bytes;
  515. size_t entry_size = unicode ? sizeof(PyDictUnicodeEntry) : sizeof(PyDictKeyEntry);
  516. assert(log2_size >= PyDict_LOG_MINSIZE);
  517. usable = USABLE_FRACTION((size_t)1<<log2_size);
  518. if (log2_size < 8) {
  519. log2_bytes = log2_size;
  520. }
  521. else if (log2_size < 16) {
  522. log2_bytes = log2_size + 1;
  523. }
  524. #if SIZEOF_VOID_P > 4
  525. else if (log2_size >= 32) {
  526. log2_bytes = log2_size + 3;
  527. }
  528. #endif
  529. else {
  530. log2_bytes = log2_size + 2;
  531. }
  532. #if PyDict_MAXFREELIST > 0
  533. struct _Py_dict_state *state = get_dict_state(interp);
  534. #ifdef Py_DEBUG
  535. // new_keys_object() must not be called after _PyDict_Fini()
  536. assert(state->keys_numfree != -1);
  537. #endif
  538. if (log2_size == PyDict_LOG_MINSIZE && unicode && state->keys_numfree > 0) {
  539. dk = state->keys_free_list[--state->keys_numfree];
  540. OBJECT_STAT_INC(from_freelist);
  541. }
  542. else
  543. #endif
  544. {
  545. dk = PyObject_Malloc(sizeof(PyDictKeysObject)
  546. + ((size_t)1 << log2_bytes)
  547. + entry_size * usable);
  548. if (dk == NULL) {
  549. PyErr_NoMemory();
  550. return NULL;
  551. }
  552. }
  553. #ifdef Py_REF_DEBUG
  554. _Py_IncRefTotal(_PyInterpreterState_GET());
  555. #endif
  556. dk->dk_refcnt = 1;
  557. dk->dk_log2_size = log2_size;
  558. dk->dk_log2_index_bytes = log2_bytes;
  559. dk->dk_kind = unicode ? DICT_KEYS_UNICODE : DICT_KEYS_GENERAL;
  560. dk->dk_nentries = 0;
  561. dk->dk_usable = usable;
  562. dk->dk_version = 0;
  563. memset(&dk->dk_indices[0], 0xff, ((size_t)1 << log2_bytes));
  564. memset(&dk->dk_indices[(size_t)1 << log2_bytes], 0, entry_size * usable);
  565. return dk;
  566. }
  567. static void
  568. free_keys_object(PyInterpreterState *interp, PyDictKeysObject *keys)
  569. {
  570. assert(keys != Py_EMPTY_KEYS);
  571. if (DK_IS_UNICODE(keys)) {
  572. PyDictUnicodeEntry *entries = DK_UNICODE_ENTRIES(keys);
  573. Py_ssize_t i, n;
  574. for (i = 0, n = keys->dk_nentries; i < n; i++) {
  575. Py_XDECREF(entries[i].me_key);
  576. Py_XDECREF(entries[i].me_value);
  577. }
  578. }
  579. else {
  580. PyDictKeyEntry *entries = DK_ENTRIES(keys);
  581. Py_ssize_t i, n;
  582. for (i = 0, n = keys->dk_nentries; i < n; i++) {
  583. Py_XDECREF(entries[i].me_key);
  584. Py_XDECREF(entries[i].me_value);
  585. }
  586. }
  587. #if PyDict_MAXFREELIST > 0
  588. struct _Py_dict_state *state = get_dict_state(interp);
  589. #ifdef Py_DEBUG
  590. // free_keys_object() must not be called after _PyDict_Fini()
  591. assert(state->keys_numfree != -1);
  592. #endif
  593. if (DK_LOG_SIZE(keys) == PyDict_LOG_MINSIZE
  594. && state->keys_numfree < PyDict_MAXFREELIST
  595. && DK_IS_UNICODE(keys)) {
  596. state->keys_free_list[state->keys_numfree++] = keys;
  597. OBJECT_STAT_INC(to_freelist);
  598. return;
  599. }
  600. #endif
  601. PyObject_Free(keys);
  602. }
  603. static inline PyDictValues*
  604. new_values(size_t size)
  605. {
  606. assert(size >= 1);
  607. size_t prefix_size = _Py_SIZE_ROUND_UP(size+2, sizeof(PyObject *));
  608. assert(prefix_size < 256);
  609. size_t n = prefix_size + size * sizeof(PyObject *);
  610. uint8_t *mem = PyMem_Malloc(n);
  611. if (mem == NULL) {
  612. return NULL;
  613. }
  614. assert(prefix_size % sizeof(PyObject *) == 0);
  615. mem[prefix_size-1] = (uint8_t)prefix_size;
  616. return (PyDictValues*)(mem + prefix_size);
  617. }
  618. static inline void
  619. free_values(PyDictValues *values)
  620. {
  621. int prefix_size = ((uint8_t *)values)[-1];
  622. PyMem_Free(((char *)values)-prefix_size);
  623. }
  624. /* Consumes a reference to the keys object */
  625. static PyObject *
  626. new_dict(PyInterpreterState *interp,
  627. PyDictKeysObject *keys, PyDictValues *values,
  628. Py_ssize_t used, int free_values_on_failure)
  629. {
  630. PyDictObject *mp;
  631. assert(keys != NULL);
  632. #if PyDict_MAXFREELIST > 0
  633. struct _Py_dict_state *state = get_dict_state(interp);
  634. #ifdef Py_DEBUG
  635. // new_dict() must not be called after _PyDict_Fini()
  636. assert(state->numfree != -1);
  637. #endif
  638. if (state->numfree) {
  639. mp = state->free_list[--state->numfree];
  640. assert (mp != NULL);
  641. assert (Py_IS_TYPE(mp, &PyDict_Type));
  642. OBJECT_STAT_INC(from_freelist);
  643. _Py_NewReference((PyObject *)mp);
  644. }
  645. else
  646. #endif
  647. {
  648. mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
  649. if (mp == NULL) {
  650. dictkeys_decref(interp, keys);
  651. if (free_values_on_failure) {
  652. free_values(values);
  653. }
  654. return NULL;
  655. }
  656. }
  657. mp->ma_keys = keys;
  658. mp->ma_values = values;
  659. mp->ma_used = used;
  660. mp->ma_version_tag = DICT_NEXT_VERSION(interp);
  661. ASSERT_CONSISTENT(mp);
  662. return (PyObject *)mp;
  663. }
  664. static inline size_t
  665. shared_keys_usable_size(PyDictKeysObject *keys)
  666. {
  667. return (size_t)keys->dk_nentries + (size_t)keys->dk_usable;
  668. }
  669. /* Consumes a reference to the keys object */
  670. static PyObject *
  671. new_dict_with_shared_keys(PyInterpreterState *interp, PyDictKeysObject *keys)
  672. {
  673. size_t size = shared_keys_usable_size(keys);
  674. PyDictValues *values = new_values(size);
  675. if (values == NULL) {
  676. dictkeys_decref(interp, keys);
  677. return PyErr_NoMemory();
  678. }
  679. ((char *)values)[-2] = 0;
  680. for (size_t i = 0; i < size; i++) {
  681. values->values[i] = NULL;
  682. }
  683. return new_dict(interp, keys, values, 0, 1);
  684. }
  685. static PyDictKeysObject *
  686. clone_combined_dict_keys(PyDictObject *orig)
  687. {
  688. assert(PyDict_Check(orig));
  689. assert(Py_TYPE(orig)->tp_iter == (getiterfunc)dict_iter);
  690. assert(orig->ma_values == NULL);
  691. assert(orig->ma_keys != Py_EMPTY_KEYS);
  692. assert(orig->ma_keys->dk_refcnt == 1);
  693. size_t keys_size = _PyDict_KeysSize(orig->ma_keys);
  694. PyDictKeysObject *keys = PyObject_Malloc(keys_size);
  695. if (keys == NULL) {
  696. PyErr_NoMemory();
  697. return NULL;
  698. }
  699. memcpy(keys, orig->ma_keys, keys_size);
  700. /* After copying key/value pairs, we need to incref all
  701. keys and values and they are about to be co-owned by a
  702. new dict object. */
  703. PyObject **pkey, **pvalue;
  704. size_t offs;
  705. if (DK_IS_UNICODE(orig->ma_keys)) {
  706. PyDictUnicodeEntry *ep0 = DK_UNICODE_ENTRIES(keys);
  707. pkey = &ep0->me_key;
  708. pvalue = &ep0->me_value;
  709. offs = sizeof(PyDictUnicodeEntry) / sizeof(PyObject*);
  710. }
  711. else {
  712. PyDictKeyEntry *ep0 = DK_ENTRIES(keys);
  713. pkey = &ep0->me_key;
  714. pvalue = &ep0->me_value;
  715. offs = sizeof(PyDictKeyEntry) / sizeof(PyObject*);
  716. }
  717. Py_ssize_t n = keys->dk_nentries;
  718. for (Py_ssize_t i = 0; i < n; i++) {
  719. PyObject *value = *pvalue;
  720. if (value != NULL) {
  721. Py_INCREF(value);
  722. Py_INCREF(*pkey);
  723. }
  724. pvalue += offs;
  725. pkey += offs;
  726. }
  727. /* Since we copied the keys table we now have an extra reference
  728. in the system. Manually call increment _Py_RefTotal to signal that
  729. we have it now; calling dictkeys_incref would be an error as
  730. keys->dk_refcnt is already set to 1 (after memcpy). */
  731. #ifdef Py_REF_DEBUG
  732. _Py_IncRefTotal(_PyInterpreterState_GET());
  733. #endif
  734. return keys;
  735. }
  736. PyObject *
  737. PyDict_New(void)
  738. {
  739. PyInterpreterState *interp = _PyInterpreterState_GET();
  740. /* We don't incref Py_EMPTY_KEYS here because it is immortal. */
  741. return new_dict(interp, Py_EMPTY_KEYS, NULL, 0, 0);
  742. }
  743. /* Search index of hash table from offset of entry table */
  744. static Py_ssize_t
  745. lookdict_index(PyDictKeysObject *k, Py_hash_t hash, Py_ssize_t index)
  746. {
  747. size_t mask = DK_MASK(k);
  748. size_t perturb = (size_t)hash;
  749. size_t i = (size_t)hash & mask;
  750. for (;;) {
  751. Py_ssize_t ix = dictkeys_get_index(k, i);
  752. if (ix == index) {
  753. return i;
  754. }
  755. if (ix == DKIX_EMPTY) {
  756. return DKIX_EMPTY;
  757. }
  758. perturb >>= PERTURB_SHIFT;
  759. i = mask & (i*5 + perturb + 1);
  760. }
  761. Py_UNREACHABLE();
  762. }
  763. // Search non-Unicode key from Unicode table
  764. static Py_ssize_t
  765. unicodekeys_lookup_generic(PyDictObject *mp, PyDictKeysObject* dk, PyObject *key, Py_hash_t hash)
  766. {
  767. PyDictUnicodeEntry *ep0 = DK_UNICODE_ENTRIES(dk);
  768. size_t mask = DK_MASK(dk);
  769. size_t perturb = hash;
  770. size_t i = (size_t)hash & mask;
  771. Py_ssize_t ix;
  772. for (;;) {
  773. ix = dictkeys_get_index(dk, i);
  774. if (ix >= 0) {
  775. PyDictUnicodeEntry *ep = &ep0[ix];
  776. assert(ep->me_key != NULL);
  777. assert(PyUnicode_CheckExact(ep->me_key));
  778. if (ep->me_key == key) {
  779. return ix;
  780. }
  781. if (unicode_get_hash(ep->me_key) == hash) {
  782. PyObject *startkey = ep->me_key;
  783. Py_INCREF(startkey);
  784. int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
  785. Py_DECREF(startkey);
  786. if (cmp < 0) {
  787. return DKIX_ERROR;
  788. }
  789. if (dk == mp->ma_keys && ep->me_key == startkey) {
  790. if (cmp > 0) {
  791. return ix;
  792. }
  793. }
  794. else {
  795. /* The dict was mutated, restart */
  796. return DKIX_KEY_CHANGED;
  797. }
  798. }
  799. }
  800. else if (ix == DKIX_EMPTY) {
  801. return DKIX_EMPTY;
  802. }
  803. perturb >>= PERTURB_SHIFT;
  804. i = mask & (i*5 + perturb + 1);
  805. }
  806. Py_UNREACHABLE();
  807. }
  808. // Search Unicode key from Unicode table.
  809. static Py_ssize_t _Py_HOT_FUNCTION
  810. unicodekeys_lookup_unicode(PyDictKeysObject* dk, PyObject *key, Py_hash_t hash)
  811. {
  812. PyDictUnicodeEntry *ep0 = DK_UNICODE_ENTRIES(dk);
  813. size_t mask = DK_MASK(dk);
  814. size_t perturb = hash;
  815. size_t i = (size_t)hash & mask;
  816. Py_ssize_t ix;
  817. for (;;) {
  818. ix = dictkeys_get_index(dk, i);
  819. if (ix >= 0) {
  820. PyDictUnicodeEntry *ep = &ep0[ix];
  821. assert(ep->me_key != NULL);
  822. assert(PyUnicode_CheckExact(ep->me_key));
  823. if (ep->me_key == key ||
  824. (unicode_get_hash(ep->me_key) == hash && unicode_eq(ep->me_key, key))) {
  825. return ix;
  826. }
  827. }
  828. else if (ix == DKIX_EMPTY) {
  829. return DKIX_EMPTY;
  830. }
  831. perturb >>= PERTURB_SHIFT;
  832. i = mask & (i*5 + perturb + 1);
  833. // Manual loop unrolling
  834. ix = dictkeys_get_index(dk, i);
  835. if (ix >= 0) {
  836. PyDictUnicodeEntry *ep = &ep0[ix];
  837. assert(ep->me_key != NULL);
  838. assert(PyUnicode_CheckExact(ep->me_key));
  839. if (ep->me_key == key ||
  840. (unicode_get_hash(ep->me_key) == hash && unicode_eq(ep->me_key, key))) {
  841. return ix;
  842. }
  843. }
  844. else if (ix == DKIX_EMPTY) {
  845. return DKIX_EMPTY;
  846. }
  847. perturb >>= PERTURB_SHIFT;
  848. i = mask & (i*5 + perturb + 1);
  849. }
  850. Py_UNREACHABLE();
  851. }
  852. // Search key from Generic table.
  853. static Py_ssize_t
  854. dictkeys_generic_lookup(PyDictObject *mp, PyDictKeysObject* dk, PyObject *key, Py_hash_t hash)
  855. {
  856. PyDictKeyEntry *ep0 = DK_ENTRIES(dk);
  857. size_t mask = DK_MASK(dk);
  858. size_t perturb = hash;
  859. size_t i = (size_t)hash & mask;
  860. Py_ssize_t ix;
  861. for (;;) {
  862. ix = dictkeys_get_index(dk, i);
  863. if (ix >= 0) {
  864. PyDictKeyEntry *ep = &ep0[ix];
  865. assert(ep->me_key != NULL);
  866. if (ep->me_key == key) {
  867. return ix;
  868. }
  869. if (ep->me_hash == hash) {
  870. PyObject *startkey = ep->me_key;
  871. Py_INCREF(startkey);
  872. int cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
  873. Py_DECREF(startkey);
  874. if (cmp < 0) {
  875. return DKIX_ERROR;
  876. }
  877. if (dk == mp->ma_keys && ep->me_key == startkey) {
  878. if (cmp > 0) {
  879. return ix;
  880. }
  881. }
  882. else {
  883. /* The dict was mutated, restart */
  884. return DKIX_KEY_CHANGED;
  885. }
  886. }
  887. }
  888. else if (ix == DKIX_EMPTY) {
  889. return DKIX_EMPTY;
  890. }
  891. perturb >>= PERTURB_SHIFT;
  892. i = mask & (i*5 + perturb + 1);
  893. }
  894. Py_UNREACHABLE();
  895. }
  896. /* Lookup a string in a (all unicode) dict keys.
  897. * Returns DKIX_ERROR if key is not a string,
  898. * or if the dict keys is not all strings.
  899. * If the keys is present then return the index of key.
  900. * If the key is not present then return DKIX_EMPTY.
  901. */
  902. Py_ssize_t
  903. _PyDictKeys_StringLookup(PyDictKeysObject* dk, PyObject *key)
  904. {
  905. DictKeysKind kind = dk->dk_kind;
  906. if (!PyUnicode_CheckExact(key) || kind == DICT_KEYS_GENERAL) {
  907. return DKIX_ERROR;
  908. }
  909. Py_hash_t hash = unicode_get_hash(key);
  910. if (hash == -1) {
  911. hash = PyUnicode_Type.tp_hash(key);
  912. if (hash == -1) {
  913. PyErr_Clear();
  914. return DKIX_ERROR;
  915. }
  916. }
  917. return unicodekeys_lookup_unicode(dk, key, hash);
  918. }
  919. /*
  920. The basic lookup function used by all operations.
  921. This is based on Algorithm D from Knuth Vol. 3, Sec. 6.4.
  922. Open addressing is preferred over chaining since the link overhead for
  923. chaining would be substantial (100% with typical malloc overhead).
  924. The initial probe index is computed as hash mod the table size. Subsequent
  925. probe indices are computed as explained earlier.
  926. All arithmetic on hash should ignore overflow.
  927. _Py_dict_lookup() is general-purpose, and may return DKIX_ERROR if (and only if) a
  928. comparison raises an exception.
  929. When the key isn't found a DKIX_EMPTY is returned.
  930. */
  931. Py_ssize_t
  932. _Py_dict_lookup(PyDictObject *mp, PyObject *key, Py_hash_t hash, PyObject **value_addr)
  933. {
  934. PyDictKeysObject *dk;
  935. DictKeysKind kind;
  936. Py_ssize_t ix;
  937. start:
  938. dk = mp->ma_keys;
  939. kind = dk->dk_kind;
  940. if (kind != DICT_KEYS_GENERAL) {
  941. if (PyUnicode_CheckExact(key)) {
  942. ix = unicodekeys_lookup_unicode(dk, key, hash);
  943. }
  944. else {
  945. ix = unicodekeys_lookup_generic(mp, dk, key, hash);
  946. if (ix == DKIX_KEY_CHANGED) {
  947. goto start;
  948. }
  949. }
  950. if (ix >= 0) {
  951. if (kind == DICT_KEYS_SPLIT) {
  952. *value_addr = mp->ma_values->values[ix];
  953. }
  954. else {
  955. *value_addr = DK_UNICODE_ENTRIES(dk)[ix].me_value;
  956. }
  957. }
  958. else {
  959. *value_addr = NULL;
  960. }
  961. }
  962. else {
  963. ix = dictkeys_generic_lookup(mp, dk, key, hash);
  964. if (ix == DKIX_KEY_CHANGED) {
  965. goto start;
  966. }
  967. if (ix >= 0) {
  968. *value_addr = DK_ENTRIES(dk)[ix].me_value;
  969. }
  970. else {
  971. *value_addr = NULL;
  972. }
  973. }
  974. return ix;
  975. }
  976. int
  977. _PyDict_HasOnlyStringKeys(PyObject *dict)
  978. {
  979. Py_ssize_t pos = 0;
  980. PyObject *key, *value;
  981. assert(PyDict_Check(dict));
  982. /* Shortcut */
  983. if (((PyDictObject *)dict)->ma_keys->dk_kind != DICT_KEYS_GENERAL)
  984. return 1;
  985. while (PyDict_Next(dict, &pos, &key, &value))
  986. if (!PyUnicode_Check(key))
  987. return 0;
  988. return 1;
  989. }
  990. #define MAINTAIN_TRACKING(mp, key, value) \
  991. do { \
  992. if (!_PyObject_GC_IS_TRACKED(mp)) { \
  993. if (_PyObject_GC_MAY_BE_TRACKED(key) || \
  994. _PyObject_GC_MAY_BE_TRACKED(value)) { \
  995. _PyObject_GC_TRACK(mp); \
  996. } \
  997. } \
  998. } while(0)
  999. void
  1000. _PyDict_MaybeUntrack(PyObject *op)
  1001. {
  1002. PyDictObject *mp;
  1003. PyObject *value;
  1004. Py_ssize_t i, numentries;
  1005. if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
  1006. return;
  1007. mp = (PyDictObject *) op;
  1008. numentries = mp->ma_keys->dk_nentries;
  1009. if (_PyDict_HasSplitTable(mp)) {
  1010. for (i = 0; i < numentries; i++) {
  1011. if ((value = mp->ma_values->values[i]) == NULL)
  1012. continue;
  1013. if (_PyObject_GC_MAY_BE_TRACKED(value)) {
  1014. return;
  1015. }
  1016. }
  1017. }
  1018. else {
  1019. if (DK_IS_UNICODE(mp->ma_keys)) {
  1020. PyDictUnicodeEntry *ep0 = DK_UNICODE_ENTRIES(mp->ma_keys);
  1021. for (i = 0; i < numentries; i++) {
  1022. if ((value = ep0[i].me_value) == NULL)
  1023. continue;
  1024. if (_PyObject_GC_MAY_BE_TRACKED(value))
  1025. return;
  1026. }
  1027. }
  1028. else {
  1029. PyDictKeyEntry *ep0 = DK_ENTRIES(mp->ma_keys);
  1030. for (i = 0; i < numentries; i++) {
  1031. if ((value = ep0[i].me_value) == NULL)
  1032. continue;
  1033. if (_PyObject_GC_MAY_BE_TRACKED(value) ||
  1034. _PyObject_GC_MAY_BE_TRACKED(ep0[i].me_key))
  1035. return;
  1036. }
  1037. }
  1038. }
  1039. _PyObject_GC_UNTRACK(op);
  1040. }
  1041. /* Internal function to find slot for an item from its hash
  1042. when it is known that the key is not present in the dict.
  1043. The dict must be combined. */
  1044. static Py_ssize_t
  1045. find_empty_slot(PyDictKeysObject *keys, Py_hash_t hash)
  1046. {
  1047. assert(keys != NULL);
  1048. const size_t mask = DK_MASK(keys);
  1049. size_t i = hash & mask;
  1050. Py_ssize_t ix = dictkeys_get_index(keys, i);
  1051. for (size_t perturb = hash; ix >= 0;) {
  1052. perturb >>= PERTURB_SHIFT;
  1053. i = (i*5 + perturb + 1) & mask;
  1054. ix = dictkeys_get_index(keys, i);
  1055. }
  1056. return i;
  1057. }
  1058. static int
  1059. insertion_resize(PyInterpreterState *interp, PyDictObject *mp, int unicode)
  1060. {
  1061. return dictresize(interp, mp, calculate_log2_keysize(GROWTH_RATE(mp)), unicode);
  1062. }
  1063. static Py_ssize_t
  1064. insert_into_dictkeys(PyDictKeysObject *keys, PyObject *name)
  1065. {
  1066. assert(PyUnicode_CheckExact(name));
  1067. Py_hash_t hash = unicode_get_hash(name);
  1068. if (hash == -1) {
  1069. hash = PyUnicode_Type.tp_hash(name);
  1070. if (hash == -1) {
  1071. PyErr_Clear();
  1072. return DKIX_EMPTY;
  1073. }
  1074. }
  1075. Py_ssize_t ix = unicodekeys_lookup_unicode(keys, name, hash);
  1076. if (ix == DKIX_EMPTY) {
  1077. if (keys->dk_usable <= 0) {
  1078. return DKIX_EMPTY;
  1079. }
  1080. /* Insert into new slot. */
  1081. keys->dk_version = 0;
  1082. Py_ssize_t hashpos = find_empty_slot(keys, hash);
  1083. ix = keys->dk_nentries;
  1084. PyDictUnicodeEntry *ep = &DK_UNICODE_ENTRIES(keys)[ix];
  1085. dictkeys_set_index(keys, hashpos, ix);
  1086. assert(ep->me_key == NULL);
  1087. ep->me_key = Py_NewRef(name);
  1088. keys->dk_usable--;
  1089. keys->dk_nentries++;
  1090. }
  1091. assert (ix < SHARED_KEYS_MAX_SIZE);
  1092. return ix;
  1093. }
  1094. /*
  1095. Internal routine to insert a new item into the table.
  1096. Used both by the internal resize routine and by the public insert routine.
  1097. Returns -1 if an error occurred, or 0 on success.
  1098. Consumes key and value references.
  1099. */
  1100. static int
  1101. insertdict(PyInterpreterState *interp, PyDictObject *mp,
  1102. PyObject *key, Py_hash_t hash, PyObject *value)
  1103. {
  1104. PyObject *old_value;
  1105. if (DK_IS_UNICODE(mp->ma_keys) && !PyUnicode_CheckExact(key)) {
  1106. if (insertion_resize(interp, mp, 0) < 0)
  1107. goto Fail;
  1108. assert(mp->ma_keys->dk_kind == DICT_KEYS_GENERAL);
  1109. }
  1110. Py_ssize_t ix = _Py_dict_lookup(mp, key, hash, &old_value);
  1111. if (ix == DKIX_ERROR)
  1112. goto Fail;
  1113. MAINTAIN_TRACKING(mp, key, value);
  1114. if (ix == DKIX_EMPTY) {
  1115. assert(old_value == NULL);
  1116. if (mp->ma_keys->dk_usable <= 0) {
  1117. /* Need to resize. */
  1118. if (insertion_resize(interp, mp, 1) < 0)
  1119. goto Fail;
  1120. }
  1121. uint64_t new_version = _PyDict_NotifyEvent(
  1122. interp, PyDict_EVENT_ADDED, mp, key, value);
  1123. /* Insert into new slot. */
  1124. mp->ma_keys->dk_version = 0;
  1125. Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
  1126. dictkeys_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
  1127. if (DK_IS_UNICODE(mp->ma_keys)) {
  1128. PyDictUnicodeEntry *ep;
  1129. ep = &DK_UNICODE_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
  1130. ep->me_key = key;
  1131. if (mp->ma_values) {
  1132. Py_ssize_t index = mp->ma_keys->dk_nentries;
  1133. _PyDictValues_AddToInsertionOrder(mp->ma_values, index);
  1134. assert (mp->ma_values->values[index] == NULL);
  1135. mp->ma_values->values[index] = value;
  1136. }
  1137. else {
  1138. ep->me_value = value;
  1139. }
  1140. }
  1141. else {
  1142. PyDictKeyEntry *ep;
  1143. ep = &DK_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
  1144. ep->me_key = key;
  1145. ep->me_hash = hash;
  1146. ep->me_value = value;
  1147. }
  1148. mp->ma_used++;
  1149. mp->ma_version_tag = new_version;
  1150. mp->ma_keys->dk_usable--;
  1151. mp->ma_keys->dk_nentries++;
  1152. assert(mp->ma_keys->dk_usable >= 0);
  1153. ASSERT_CONSISTENT(mp);
  1154. return 0;
  1155. }
  1156. if (old_value != value) {
  1157. uint64_t new_version = _PyDict_NotifyEvent(
  1158. interp, PyDict_EVENT_MODIFIED, mp, key, value);
  1159. if (_PyDict_HasSplitTable(mp)) {
  1160. mp->ma_values->values[ix] = value;
  1161. if (old_value == NULL) {
  1162. _PyDictValues_AddToInsertionOrder(mp->ma_values, ix);
  1163. mp->ma_used++;
  1164. }
  1165. }
  1166. else {
  1167. assert(old_value != NULL);
  1168. if (DK_IS_UNICODE(mp->ma_keys)) {
  1169. DK_UNICODE_ENTRIES(mp->ma_keys)[ix].me_value = value;
  1170. }
  1171. else {
  1172. DK_ENTRIES(mp->ma_keys)[ix].me_value = value;
  1173. }
  1174. }
  1175. mp->ma_version_tag = new_version;
  1176. }
  1177. Py_XDECREF(old_value); /* which **CAN** re-enter (see issue #22653) */
  1178. ASSERT_CONSISTENT(mp);
  1179. Py_DECREF(key);
  1180. return 0;
  1181. Fail:
  1182. Py_DECREF(value);
  1183. Py_DECREF(key);
  1184. return -1;
  1185. }
  1186. // Same to insertdict but specialized for ma_keys = Py_EMPTY_KEYS.
  1187. // Consumes key and value references.
  1188. static int
  1189. insert_to_emptydict(PyInterpreterState *interp, PyDictObject *mp,
  1190. PyObject *key, Py_hash_t hash, PyObject *value)
  1191. {
  1192. assert(mp->ma_keys == Py_EMPTY_KEYS);
  1193. int unicode = PyUnicode_CheckExact(key);
  1194. PyDictKeysObject *newkeys = new_keys_object(
  1195. interp, PyDict_LOG_MINSIZE, unicode);
  1196. if (newkeys == NULL) {
  1197. Py_DECREF(key);
  1198. Py_DECREF(value);
  1199. return -1;
  1200. }
  1201. uint64_t new_version = _PyDict_NotifyEvent(
  1202. interp, PyDict_EVENT_ADDED, mp, key, value);
  1203. /* We don't decref Py_EMPTY_KEYS here because it is immortal. */
  1204. mp->ma_keys = newkeys;
  1205. mp->ma_values = NULL;
  1206. MAINTAIN_TRACKING(mp, key, value);
  1207. size_t hashpos = (size_t)hash & (PyDict_MINSIZE-1);
  1208. dictkeys_set_index(mp->ma_keys, hashpos, 0);
  1209. if (unicode) {
  1210. PyDictUnicodeEntry *ep = DK_UNICODE_ENTRIES(mp->ma_keys);
  1211. ep->me_key = key;
  1212. ep->me_value = value;
  1213. }
  1214. else {
  1215. PyDictKeyEntry *ep = DK_ENTRIES(mp->ma_keys);
  1216. ep->me_key = key;
  1217. ep->me_hash = hash;
  1218. ep->me_value = value;
  1219. }
  1220. mp->ma_used++;
  1221. mp->ma_version_tag = new_version;
  1222. mp->ma_keys->dk_usable--;
  1223. mp->ma_keys->dk_nentries++;
  1224. return 0;
  1225. }
  1226. /*
  1227. Internal routine used by dictresize() to build a hashtable of entries.
  1228. */
  1229. static void
  1230. build_indices_generic(PyDictKeysObject *keys, PyDictKeyEntry *ep, Py_ssize_t n)
  1231. {
  1232. size_t mask = DK_MASK(keys);
  1233. for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
  1234. Py_hash_t hash = ep->me_hash;
  1235. size_t i = hash & mask;
  1236. for (size_t perturb = hash; dictkeys_get_index(keys, i) != DKIX_EMPTY;) {
  1237. perturb >>= PERTURB_SHIFT;
  1238. i = mask & (i*5 + perturb + 1);
  1239. }
  1240. dictkeys_set_index(keys, i, ix);
  1241. }
  1242. }
  1243. static void
  1244. build_indices_unicode(PyDictKeysObject *keys, PyDictUnicodeEntry *ep, Py_ssize_t n)
  1245. {
  1246. size_t mask = DK_MASK(keys);
  1247. for (Py_ssize_t ix = 0; ix != n; ix++, ep++) {
  1248. Py_hash_t hash = unicode_get_hash(ep->me_key);
  1249. assert(hash != -1);
  1250. size_t i = hash & mask;
  1251. for (size_t perturb = hash; dictkeys_get_index(keys, i) != DKIX_EMPTY;) {
  1252. perturb >>= PERTURB_SHIFT;
  1253. i = mask & (i*5 + perturb + 1);
  1254. }
  1255. dictkeys_set_index(keys, i, ix);
  1256. }
  1257. }
  1258. /*
  1259. Restructure the table by allocating a new table and reinserting all
  1260. items again. When entries have been deleted, the new table may
  1261. actually be smaller than the old one.
  1262. If a table is split (its keys and hashes are shared, its values are not),
  1263. then the values are temporarily copied into the table, it is resized as
  1264. a combined table, then the me_value slots in the old table are NULLed out.
  1265. After resizing a table is always combined.
  1266. This function supports:
  1267. - Unicode split -> Unicode combined or Generic
  1268. - Unicode combined -> Unicode combined or Generic
  1269. - Generic -> Generic
  1270. */
  1271. static int
  1272. dictresize(PyInterpreterState *interp, PyDictObject *mp,
  1273. uint8_t log2_newsize, int unicode)
  1274. {
  1275. PyDictKeysObject *oldkeys;
  1276. PyDictValues *oldvalues;
  1277. if (log2_newsize >= SIZEOF_SIZE_T*8) {
  1278. PyErr_NoMemory();
  1279. return -1;
  1280. }
  1281. assert(log2_newsize >= PyDict_LOG_MINSIZE);
  1282. oldkeys = mp->ma_keys;
  1283. oldvalues = mp->ma_values;
  1284. if (!DK_IS_UNICODE(oldkeys)) {
  1285. unicode = 0;
  1286. }
  1287. /* NOTE: Current odict checks mp->ma_keys to detect resize happen.
  1288. * So we can't reuse oldkeys even if oldkeys->dk_size == newsize.
  1289. * TODO: Try reusing oldkeys when reimplement odict.
  1290. */
  1291. /* Allocate a new table. */
  1292. mp->ma_keys = new_keys_object(interp, log2_newsize, unicode);
  1293. if (mp->ma_keys == NULL) {
  1294. mp->ma_keys = oldkeys;
  1295. return -1;
  1296. }
  1297. // New table must be large enough.
  1298. assert(mp->ma_keys->dk_usable >= mp->ma_used);
  1299. Py_ssize_t numentries = mp->ma_used;
  1300. if (oldvalues != NULL) {
  1301. PyDictUnicodeEntry *oldentries = DK_UNICODE_ENTRIES(oldkeys);
  1302. /* Convert split table into new combined table.
  1303. * We must incref keys; we can transfer values.
  1304. */
  1305. if (mp->ma_keys->dk_kind == DICT_KEYS_GENERAL) {
  1306. // split -> generic
  1307. PyDictKeyEntry *newentries = DK_ENTRIES(mp->ma_keys);
  1308. for (Py_ssize_t i = 0; i < numentries; i++) {
  1309. int index = get_index_from_order(mp, i);
  1310. PyDictUnicodeEntry *ep = &oldentries[index];
  1311. assert(oldvalues->values[index] != NULL);
  1312. newentries[i].me_key = Py_NewRef(ep->me_key);
  1313. newentries[i].me_hash = unicode_get_hash(ep->me_key);
  1314. newentries[i].me_value = oldvalues->values[index];
  1315. }
  1316. build_indices_generic(mp->ma_keys, newentries, numentries);
  1317. }
  1318. else { // split -> combined unicode
  1319. PyDictUnicodeEntry *newentries = DK_UNICODE_ENTRIES(mp->ma_keys);
  1320. for (Py_ssize_t i = 0; i < numentries; i++) {
  1321. int index = get_index_from_order(mp, i);
  1322. PyDictUnicodeEntry *ep = &oldentries[index];
  1323. assert(oldvalues->values[index] != NULL);
  1324. newentries[i].me_key = Py_NewRef(ep->me_key);
  1325. newentries[i].me_value = oldvalues->values[index];
  1326. }
  1327. build_indices_unicode(mp->ma_keys, newentries, numentries);
  1328. }
  1329. dictkeys_decref(interp, oldkeys);
  1330. mp->ma_values = NULL;
  1331. free_values(oldvalues);
  1332. }
  1333. else { // oldkeys is combined.
  1334. if (oldkeys->dk_kind == DICT_KEYS_GENERAL) {
  1335. // generic -> generic
  1336. assert(mp->ma_keys->dk_kind == DICT_KEYS_GENERAL);
  1337. PyDictKeyEntry *oldentries = DK_ENTRIES(oldkeys);
  1338. PyDictKeyEntry *newentries = DK_ENTRIES(mp->ma_keys);
  1339. if (oldkeys->dk_nentries == numentries) {
  1340. memcpy(newentries, oldentries, numentries * sizeof(PyDictKeyEntry));
  1341. }
  1342. else {
  1343. PyDictKeyEntry *ep = oldentries;
  1344. for (Py_ssize_t i = 0; i < numentries; i++) {
  1345. while (ep->me_value == NULL)
  1346. ep++;
  1347. newentries[i] = *ep++;
  1348. }
  1349. }
  1350. build_indices_generic(mp->ma_keys, newentries, numentries);
  1351. }
  1352. else { // oldkeys is combined unicode
  1353. PyDictUnicodeEntry *oldentries = DK_UNICODE_ENTRIES(oldkeys);
  1354. if (unicode) { // combined unicode -> combined unicode
  1355. PyDictUnicodeEntry *newentries = DK_UNICODE_ENTRIES(mp->ma_keys);
  1356. if (oldkeys->dk_nentries == numentries && mp->ma_keys->dk_kind == DICT_KEYS_UNICODE) {
  1357. memcpy(newentries, oldentries, numentries * sizeof(PyDictUnicodeEntry));
  1358. }
  1359. else {
  1360. PyDictUnicodeEntry *ep = oldentries;
  1361. for (Py_ssize_t i = 0; i < numentries; i++) {
  1362. while (ep->me_value == NULL)
  1363. ep++;
  1364. newentries[i] = *ep++;
  1365. }
  1366. }
  1367. build_indices_unicode(mp->ma_keys, newentries, numentries);
  1368. }
  1369. else { // combined unicode -> generic
  1370. PyDictKeyEntry *newentries = DK_ENTRIES(mp->ma_keys);
  1371. PyDictUnicodeEntry *ep = oldentries;
  1372. for (Py_ssize_t i = 0; i < numentries; i++) {
  1373. while (ep->me_value == NULL)
  1374. ep++;
  1375. newentries[i].me_key = ep->me_key;
  1376. newentries[i].me_hash = unicode_get_hash(ep->me_key);
  1377. newentries[i].me_value = ep->me_value;
  1378. ep++;
  1379. }
  1380. build_indices_generic(mp->ma_keys, newentries, numentries);
  1381. }
  1382. }
  1383. // We can not use free_keys_object here because key's reference
  1384. // are moved already.
  1385. if (oldkeys != Py_EMPTY_KEYS) {
  1386. #ifdef Py_REF_DEBUG
  1387. _Py_DecRefTotal(_PyInterpreterState_GET());
  1388. #endif
  1389. assert(oldkeys->dk_kind != DICT_KEYS_SPLIT);
  1390. assert(oldkeys->dk_refcnt == 1);
  1391. #if PyDict_MAXFREELIST > 0
  1392. struct _Py_dict_state *state = get_dict_state(interp);
  1393. #ifdef Py_DEBUG
  1394. // dictresize() must not be called after _PyDict_Fini()
  1395. assert(state->keys_numfree != -1);
  1396. #endif
  1397. if (DK_LOG_SIZE(oldkeys) == PyDict_LOG_MINSIZE &&
  1398. DK_IS_UNICODE(oldkeys) &&
  1399. state->keys_numfree < PyDict_MAXFREELIST)
  1400. {
  1401. state->keys_free_list[state->keys_numfree++] = oldkeys;
  1402. OBJECT_STAT_INC(to_freelist);
  1403. }
  1404. else
  1405. #endif
  1406. {
  1407. PyObject_Free(oldkeys);
  1408. }
  1409. }
  1410. }
  1411. mp->ma_keys->dk_usable -= numentries;
  1412. mp->ma_keys->dk_nentries = numentries;
  1413. ASSERT_CONSISTENT(mp);
  1414. return 0;
  1415. }
  1416. static PyObject *
  1417. dict_new_presized(PyInterpreterState *interp, Py_ssize_t minused, bool unicode)
  1418. {
  1419. const uint8_t log2_max_presize = 17;
  1420. const Py_ssize_t max_presize = ((Py_ssize_t)1) << log2_max_presize;
  1421. uint8_t log2_newsize;
  1422. PyDictKeysObject *new_keys;
  1423. if (minused <= USABLE_FRACTION(PyDict_MINSIZE)) {
  1424. return PyDict_New();
  1425. }
  1426. /* There are no strict guarantee that returned dict can contain minused
  1427. * items without resize. So we create medium size dict instead of very
  1428. * large dict or MemoryError.
  1429. */
  1430. if (minused > USABLE_FRACTION(max_presize)) {
  1431. log2_newsize = log2_max_presize;
  1432. }
  1433. else {
  1434. log2_newsize = estimate_log2_keysize(minused);
  1435. }
  1436. new_keys = new_keys_object(interp, log2_newsize, unicode);
  1437. if (new_keys == NULL)
  1438. return NULL;
  1439. return new_dict(interp, new_keys, NULL, 0, 0);
  1440. }
  1441. PyObject *
  1442. _PyDict_NewPresized(Py_ssize_t minused)
  1443. {
  1444. PyInterpreterState *interp = _PyInterpreterState_GET();
  1445. return dict_new_presized(interp, minused, false);
  1446. }
  1447. PyObject *
  1448. _PyDict_FromItems(PyObject *const *keys, Py_ssize_t keys_offset,
  1449. PyObject *const *values, Py_ssize_t values_offset,
  1450. Py_ssize_t length)
  1451. {
  1452. bool unicode = true;
  1453. PyObject *const *ks = keys;
  1454. PyInterpreterState *interp = _PyInterpreterState_GET();
  1455. for (Py_ssize_t i = 0; i < length; i++) {
  1456. if (!PyUnicode_CheckExact(*ks)) {
  1457. unicode = false;
  1458. break;
  1459. }
  1460. ks += keys_offset;
  1461. }
  1462. PyObject *dict = dict_new_presized(interp, length, unicode);
  1463. if (dict == NULL) {
  1464. return NULL;
  1465. }
  1466. ks = keys;
  1467. PyObject *const *vs = values;
  1468. for (Py_ssize_t i = 0; i < length; i++) {
  1469. PyObject *key = *ks;
  1470. PyObject *value = *vs;
  1471. if (PyDict_SetItem(dict, key, value) < 0) {
  1472. Py_DECREF(dict);
  1473. return NULL;
  1474. }
  1475. ks += keys_offset;
  1476. vs += values_offset;
  1477. }
  1478. return dict;
  1479. }
  1480. /* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
  1481. * that may occur (originally dicts supported only string keys, and exceptions
  1482. * weren't possible). So, while the original intent was that a NULL return
  1483. * meant the key wasn't present, in reality it can mean that, or that an error
  1484. * (suppressed) occurred while computing the key's hash, or that some error
  1485. * (suppressed) occurred when comparing keys in the dict's internal probe
  1486. * sequence. A nasty example of the latter is when a Python-coded comparison
  1487. * function hits a stack-depth error, which can cause this to return NULL
  1488. * even if the key is present.
  1489. */
  1490. PyObject *
  1491. PyDict_GetItem(PyObject *op, PyObject *key)
  1492. {
  1493. if (!PyDict_Check(op)) {
  1494. return NULL;
  1495. }
  1496. PyDictObject *mp = (PyDictObject *)op;
  1497. Py_hash_t hash;
  1498. if (!PyUnicode_CheckExact(key) || (hash = unicode_get_hash(key)) == -1) {
  1499. hash = PyObject_Hash(key);
  1500. if (hash == -1) {
  1501. PyErr_Clear();
  1502. return NULL;
  1503. }
  1504. }
  1505. PyThreadState *tstate = _PyThreadState_GET();
  1506. #ifdef Py_DEBUG
  1507. // bpo-40839: Before Python 3.10, it was possible to call PyDict_GetItem()
  1508. // with the GIL released.
  1509. _Py_EnsureTstateNotNULL(tstate);
  1510. #endif
  1511. /* Preserve the existing exception */
  1512. PyObject *value;
  1513. Py_ssize_t ix; (void)ix;
  1514. PyObject *exc = _PyErr_GetRaisedException(tstate);
  1515. ix = _Py_dict_lookup(mp, key, hash, &value);
  1516. /* Ignore any exception raised by the lookup */
  1517. _PyErr_SetRaisedException(tstate, exc);
  1518. assert(ix >= 0 || value == NULL);
  1519. return value;
  1520. }
  1521. Py_ssize_t
  1522. _PyDict_LookupIndex(PyDictObject *mp, PyObject *key)
  1523. {
  1524. PyObject *value;
  1525. assert(PyDict_CheckExact((PyObject*)mp));
  1526. assert(PyUnicode_CheckExact(key));
  1527. Py_hash_t hash = unicode_get_hash(key);
  1528. if (hash == -1) {
  1529. hash = PyObject_Hash(key);
  1530. if (hash == -1) {
  1531. return -1;
  1532. }
  1533. }
  1534. return _Py_dict_lookup(mp, key, hash, &value);
  1535. }
  1536. /* Same as PyDict_GetItemWithError() but with hash supplied by caller.
  1537. This returns NULL *with* an exception set if an exception occurred.
  1538. It returns NULL *without* an exception set if the key wasn't present.
  1539. */
  1540. PyObject *
  1541. _PyDict_GetItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
  1542. {
  1543. Py_ssize_t ix; (void)ix;
  1544. PyDictObject *mp = (PyDictObject *)op;
  1545. PyObject *value;
  1546. if (!PyDict_Check(op)) {
  1547. PyErr_BadInternalCall();
  1548. return NULL;
  1549. }
  1550. ix = _Py_dict_lookup(mp, key, hash, &value);
  1551. assert(ix >= 0 || value == NULL);
  1552. return value;
  1553. }
  1554. /* Variant of PyDict_GetItem() that doesn't suppress exceptions.
  1555. This returns NULL *with* an exception set if an exception occurred.
  1556. It returns NULL *without* an exception set if the key wasn't present.
  1557. */
  1558. PyObject *
  1559. PyDict_GetItemWithError(PyObject *op, PyObject *key)
  1560. {
  1561. Py_ssize_t ix; (void)ix;
  1562. Py_hash_t hash;
  1563. PyDictObject*mp = (PyDictObject *)op;
  1564. PyObject *value;
  1565. if (!PyDict_Check(op)) {
  1566. PyErr_BadInternalCall();
  1567. return NULL;
  1568. }
  1569. if (!PyUnicode_CheckExact(key) || (hash = unicode_get_hash(key)) == -1)
  1570. {
  1571. hash = PyObject_Hash(key);
  1572. if (hash == -1) {
  1573. return NULL;
  1574. }
  1575. }
  1576. ix = _Py_dict_lookup(mp, key, hash, &value);
  1577. assert(ix >= 0 || value == NULL);
  1578. return value;
  1579. }
  1580. PyObject *
  1581. _PyDict_GetItemWithError(PyObject *dp, PyObject *kv)
  1582. {
  1583. assert(PyUnicode_CheckExact(kv));
  1584. Py_hash_t hash = kv->ob_type->tp_hash(kv);
  1585. if (hash == -1) {
  1586. return NULL;
  1587. }
  1588. return _PyDict_GetItem_KnownHash(dp, kv, hash);
  1589. }
  1590. PyObject *
  1591. _PyDict_GetItemIdWithError(PyObject *dp, _Py_Identifier *key)
  1592. {
  1593. PyObject *kv;
  1594. kv = _PyUnicode_FromId(key); /* borrowed */
  1595. if (kv == NULL)
  1596. return NULL;
  1597. Py_hash_t hash = unicode_get_hash(kv);
  1598. assert (hash != -1); /* interned strings have their hash value initialised */
  1599. return _PyDict_GetItem_KnownHash(dp, kv, hash);
  1600. }
  1601. PyObject *
  1602. _PyDict_GetItemStringWithError(PyObject *v, const char *key)
  1603. {
  1604. PyObject *kv, *rv;
  1605. kv = PyUnicode_FromString(key);
  1606. if (kv == NULL) {
  1607. return NULL;
  1608. }
  1609. rv = PyDict_GetItemWithError(v, kv);
  1610. Py_DECREF(kv);
  1611. return rv;
  1612. }
  1613. /* Fast version of global value lookup (LOAD_GLOBAL).
  1614. * Lookup in globals, then builtins.
  1615. *
  1616. *
  1617. *
  1618. *
  1619. * Raise an exception and return NULL if an error occurred (ex: computing the
  1620. * key hash failed, key comparison failed, ...). Return NULL if the key doesn't
  1621. * exist. Return the value if the key exists.
  1622. */
  1623. PyObject *
  1624. _PyDict_LoadGlobal(PyDictObject *globals, PyDictObject *builtins, PyObject *key)
  1625. {
  1626. Py_ssize_t ix;
  1627. Py_hash_t hash;
  1628. PyObject *value;
  1629. if (!PyUnicode_CheckExact(key) || (hash = unicode_get_hash(key)) == -1) {
  1630. hash = PyObject_Hash(key);
  1631. if (hash == -1)
  1632. return NULL;
  1633. }
  1634. /* namespace 1: globals */
  1635. ix = _Py_dict_lookup(globals, key, hash, &value);
  1636. if (ix == DKIX_ERROR)
  1637. return NULL;
  1638. if (ix != DKIX_EMPTY && value != NULL)
  1639. return value;
  1640. /* namespace 2: builtins */
  1641. ix = _Py_dict_lookup(builtins, key, hash, &value);
  1642. assert(ix >= 0 || value == NULL);
  1643. return value;
  1644. }
  1645. /* Consumes references to key and value */
  1646. int
  1647. _PyDict_SetItem_Take2(PyDictObject *mp, PyObject *key, PyObject *value)
  1648. {
  1649. assert(key);
  1650. assert(value);
  1651. assert(PyDict_Check(mp));
  1652. Py_hash_t hash;
  1653. if (!PyUnicode_CheckExact(key) || (hash = unicode_get_hash(key)) == -1) {
  1654. hash = PyObject_Hash(key);
  1655. if (hash == -1) {
  1656. Py_DECREF(key);
  1657. Py_DECREF(value);
  1658. return -1;
  1659. }
  1660. }
  1661. PyInterpreterState *interp = _PyInterpreterState_GET();
  1662. if (mp->ma_keys == Py_EMPTY_KEYS) {
  1663. return insert_to_emptydict(interp, mp, key, hash, value);
  1664. }
  1665. /* insertdict() handles any resizing that might be necessary */
  1666. return insertdict(interp, mp, key, hash, value);
  1667. }
  1668. /* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
  1669. * dictionary if it's merely replacing the value for an existing key.
  1670. * This means that it's safe to loop over a dictionary with PyDict_Next()
  1671. * and occasionally replace a value -- but you can't insert new keys or
  1672. * remove them.
  1673. */
  1674. int
  1675. PyDict_SetItem(PyObject *op, PyObject *key, PyObject *value)
  1676. {
  1677. if (!PyDict_Check(op)) {
  1678. PyErr_BadInternalCall();
  1679. return -1;
  1680. }
  1681. assert(key);
  1682. assert(value);
  1683. return _PyDict_SetItem_Take2((PyDictObject *)op,
  1684. Py_NewRef(key), Py_NewRef(value));
  1685. }
  1686. int
  1687. _PyDict_SetItem_KnownHash(PyObject *op, PyObject *key, PyObject *value,
  1688. Py_hash_t hash)
  1689. {
  1690. PyDictObject *mp;
  1691. if (!PyDict_Check(op)) {
  1692. PyErr_BadInternalCall();
  1693. return -1;
  1694. }
  1695. assert(key);
  1696. assert(value);
  1697. assert(hash != -1);
  1698. mp = (PyDictObject *)op;
  1699. PyInterpreterState *interp = _PyInterpreterState_GET();
  1700. if (mp->ma_keys == Py_EMPTY_KEYS) {
  1701. return insert_to_emptydict(interp, mp, Py_NewRef(key), hash, Py_NewRef(value));
  1702. }
  1703. /* insertdict() handles any resizing that might be necessary */
  1704. return insertdict(interp, mp, Py_NewRef(key), hash, Py_NewRef(value));
  1705. }
  1706. static void
  1707. delete_index_from_values(PyDictValues *values, Py_ssize_t ix)
  1708. {
  1709. uint8_t *size_ptr = ((uint8_t *)values)-2;
  1710. int size = *size_ptr;
  1711. int i;
  1712. for (i = 1; size_ptr[-i] != ix; i++) {
  1713. assert(i <= size);
  1714. }
  1715. assert(i <= size);
  1716. for (; i < size; i++) {
  1717. size_ptr[-i] = size_ptr[-i-1];
  1718. }
  1719. *size_ptr = size -1;
  1720. }
  1721. static int
  1722. delitem_common(PyDictObject *mp, Py_hash_t hash, Py_ssize_t ix,
  1723. PyObject *old_value, uint64_t new_version)
  1724. {
  1725. PyObject *old_key;
  1726. Py_ssize_t hashpos = lookdict_index(mp->ma_keys, hash, ix);
  1727. assert(hashpos >= 0);
  1728. mp->ma_used--;
  1729. mp->ma_version_tag = new_version;
  1730. if (mp->ma_values) {
  1731. assert(old_value == mp->ma_values->values[ix]);
  1732. mp->ma_values->values[ix] = NULL;
  1733. assert(ix < SHARED_KEYS_MAX_SIZE);
  1734. /* Update order */
  1735. delete_index_from_values(mp->ma_values, ix);
  1736. ASSERT_CONSISTENT(mp);
  1737. }
  1738. else {
  1739. mp->ma_keys->dk_version = 0;
  1740. dictkeys_set_index(mp->ma_keys, hashpos, DKIX_DUMMY);
  1741. if (DK_IS_UNICODE(mp->ma_keys)) {
  1742. PyDictUnicodeEntry *ep = &DK_UNICODE_ENTRIES(mp->ma_keys)[ix];
  1743. old_key = ep->me_key;
  1744. ep->me_key = NULL;
  1745. ep->me_value = NULL;
  1746. }
  1747. else {
  1748. PyDictKeyEntry *ep = &DK_ENTRIES(mp->ma_keys)[ix];
  1749. old_key = ep->me_key;
  1750. ep->me_key = NULL;
  1751. ep->me_value = NULL;
  1752. ep->me_hash = 0;
  1753. }
  1754. Py_DECREF(old_key);
  1755. }
  1756. Py_DECREF(old_value);
  1757. ASSERT_CONSISTENT(mp);
  1758. return 0;
  1759. }
  1760. int
  1761. PyDict_DelItem(PyObject *op, PyObject *key)
  1762. {
  1763. Py_hash_t hash;
  1764. assert(key);
  1765. if (!PyUnicode_CheckExact(key) || (hash = unicode_get_hash(key)) == -1) {
  1766. hash = PyObject_Hash(key);
  1767. if (hash == -1)
  1768. return -1;
  1769. }
  1770. return _PyDict_DelItem_KnownHash(op, key, hash);
  1771. }
  1772. int
  1773. _PyDict_DelItem_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
  1774. {
  1775. Py_ssize_t ix;
  1776. PyDictObject *mp;
  1777. PyObject *old_value;
  1778. if (!PyDict_Check(op)) {
  1779. PyErr_BadInternalCall();
  1780. return -1;
  1781. }
  1782. assert(key);
  1783. assert(hash != -1);
  1784. mp = (PyDictObject *)op;
  1785. ix = _Py_dict_lookup(mp, key, hash, &old_value);
  1786. if (ix == DKIX_ERROR)
  1787. return -1;
  1788. if (ix == DKIX_EMPTY || old_value == NULL) {
  1789. _PyErr_SetKeyError(key);
  1790. return -1;
  1791. }
  1792. PyInterpreterState *interp = _PyInterpreterState_GET();
  1793. uint64_t new_version = _PyDict_NotifyEvent(
  1794. interp, PyDict_EVENT_DELETED, mp, key, NULL);
  1795. return delitem_common(mp, hash, ix, old_value, new_version);
  1796. }
  1797. /* This function promises that the predicate -> deletion sequence is atomic
  1798. * (i.e. protected by the GIL), assuming the predicate itself doesn't
  1799. * release the GIL.
  1800. */
  1801. int
  1802. _PyDict_DelItemIf(PyObject *op, PyObject *key,
  1803. int (*predicate)(PyObject *value))
  1804. {
  1805. Py_ssize_t hashpos, ix;
  1806. PyDictObject *mp;
  1807. Py_hash_t hash;
  1808. PyObject *old_value;
  1809. int res;
  1810. if (!PyDict_Check(op)) {
  1811. PyErr_BadInternalCall();
  1812. return -1;
  1813. }
  1814. assert(key);
  1815. hash = PyObject_Hash(key);
  1816. if (hash == -1)
  1817. return -1;
  1818. mp = (PyDictObject *)op;
  1819. ix = _Py_dict_lookup(mp, key, hash, &old_value);
  1820. if (ix == DKIX_ERROR)
  1821. return -1;
  1822. if (ix == DKIX_EMPTY || old_value == NULL) {
  1823. _PyErr_SetKeyError(key);
  1824. return -1;
  1825. }
  1826. res = predicate(old_value);
  1827. if (res == -1)
  1828. return -1;
  1829. hashpos = lookdict_index(mp->ma_keys, hash, ix);
  1830. assert(hashpos >= 0);
  1831. if (res > 0) {
  1832. PyInterpreterState *interp = _PyInterpreterState_GET();
  1833. uint64_t new_version = _PyDict_NotifyEvent(
  1834. interp, PyDict_EVENT_DELETED, mp, key, NULL);
  1835. return delitem_common(mp, hashpos, ix, old_value, new_version);
  1836. } else {
  1837. return 0;
  1838. }
  1839. }
  1840. void
  1841. PyDict_Clear(PyObject *op)
  1842. {
  1843. PyDictObject *mp;
  1844. PyDictKeysObject *oldkeys;
  1845. PyDictValues *oldvalues;
  1846. Py_ssize_t i, n;
  1847. if (!PyDict_Check(op))
  1848. return;
  1849. mp = ((PyDictObject *)op);
  1850. oldkeys = mp->ma_keys;
  1851. oldvalues = mp->ma_values;
  1852. if (oldkeys == Py_EMPTY_KEYS) {
  1853. return;
  1854. }
  1855. /* Empty the dict... */
  1856. PyInterpreterState *interp = _PyInterpreterState_GET();
  1857. uint64_t new_version = _PyDict_NotifyEvent(
  1858. interp, PyDict_EVENT_CLEARED, mp, NULL, NULL);
  1859. dictkeys_incref(Py_EMPTY_KEYS);
  1860. mp->ma_keys = Py_EMPTY_KEYS;
  1861. mp->ma_values = NULL;
  1862. mp->ma_used = 0;
  1863. mp->ma_version_tag = new_version;
  1864. /* ...then clear the keys and values */
  1865. if (oldvalues != NULL) {
  1866. n = oldkeys->dk_nentries;
  1867. for (i = 0; i < n; i++)
  1868. Py_CLEAR(oldvalues->values[i]);
  1869. free_values(oldvalues);
  1870. dictkeys_decref(interp, oldkeys);
  1871. }
  1872. else {
  1873. assert(oldkeys->dk_refcnt == 1);
  1874. dictkeys_decref(interp, oldkeys);
  1875. }
  1876. ASSERT_CONSISTENT(mp);
  1877. }
  1878. /* Internal version of PyDict_Next that returns a hash value in addition
  1879. * to the key and value.
  1880. * Return 1 on success, return 0 when the reached the end of the dictionary
  1881. * (or if op is not a dictionary)
  1882. */
  1883. int
  1884. _PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey,
  1885. PyObject **pvalue, Py_hash_t *phash)
  1886. {
  1887. Py_ssize_t i;
  1888. PyDictObject *mp;
  1889. PyObject *key, *value;
  1890. Py_hash_t hash;
  1891. if (!PyDict_Check(op))
  1892. return 0;
  1893. mp = (PyDictObject *)op;
  1894. i = *ppos;
  1895. if (mp->ma_values) {
  1896. assert(mp->ma_used <= SHARED_KEYS_MAX_SIZE);
  1897. if (i < 0 || i >= mp->ma_used)
  1898. return 0;
  1899. int index = get_index_from_order(mp, i);
  1900. value = mp->ma_values->values[index];
  1901. key = DK_UNICODE_ENTRIES(mp->ma_keys)[index].me_key;
  1902. hash = unicode_get_hash(key);
  1903. assert(value != NULL);
  1904. }
  1905. else {
  1906. Py_ssize_t n = mp->ma_keys->dk_nentries;
  1907. if (i < 0 || i >= n)
  1908. return 0;
  1909. if (DK_IS_UNICODE(mp->ma_keys)) {
  1910. PyDictUnicodeEntry *entry_ptr = &DK_UNICODE_ENTRIES(mp->ma_keys)[i];
  1911. while (i < n && entry_ptr->me_value == NULL) {
  1912. entry_ptr++;
  1913. i++;
  1914. }
  1915. if (i >= n)
  1916. return 0;
  1917. key = entry_ptr->me_key;
  1918. hash = unicode_get_hash(entry_ptr->me_key);
  1919. value = entry_ptr->me_value;
  1920. }
  1921. else {
  1922. PyDictKeyEntry *entry_ptr = &DK_ENTRIES(mp->ma_keys)[i];
  1923. while (i < n && entry_ptr->me_value == NULL) {
  1924. entry_ptr++;
  1925. i++;
  1926. }
  1927. if (i >= n)
  1928. return 0;
  1929. key = entry_ptr->me_key;
  1930. hash = entry_ptr->me_hash;
  1931. value = entry_ptr->me_value;
  1932. }
  1933. }
  1934. *ppos = i+1;
  1935. if (pkey)
  1936. *pkey = key;
  1937. if (pvalue)
  1938. *pvalue = value;
  1939. if (phash)
  1940. *phash = hash;
  1941. return 1;
  1942. }
  1943. /*
  1944. * Iterate over a dict. Use like so:
  1945. *
  1946. * Py_ssize_t i;
  1947. * PyObject *key, *value;
  1948. * i = 0; # important! i should not otherwise be changed by you
  1949. * while (PyDict_Next(yourdict, &i, &key, &value)) {
  1950. * Refer to borrowed references in key and value.
  1951. * }
  1952. *
  1953. * Return 1 on success, return 0 when the reached the end of the dictionary
  1954. * (or if op is not a dictionary)
  1955. *
  1956. * CAUTION: In general, it isn't safe to use PyDict_Next in a loop that
  1957. * mutates the dict. One exception: it is safe if the loop merely changes
  1958. * the values associated with the keys (but doesn't insert new keys or
  1959. * delete keys), via PyDict_SetItem().
  1960. */
  1961. int
  1962. PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
  1963. {
  1964. return _PyDict_Next(op, ppos, pkey, pvalue, NULL);
  1965. }
  1966. /* Internal version of dict.pop(). */
  1967. PyObject *
  1968. _PyDict_Pop_KnownHash(PyObject *dict, PyObject *key, Py_hash_t hash, PyObject *deflt)
  1969. {
  1970. Py_ssize_t ix;
  1971. PyObject *old_value;
  1972. PyDictObject *mp;
  1973. PyInterpreterState *interp = _PyInterpreterState_GET();
  1974. assert(PyDict_Check(dict));
  1975. mp = (PyDictObject *)dict;
  1976. if (mp->ma_used == 0) {
  1977. if (deflt) {
  1978. return Py_NewRef(deflt);
  1979. }
  1980. _PyErr_SetKeyError(key);
  1981. return NULL;
  1982. }
  1983. ix = _Py_dict_lookup(mp, key, hash, &old_value);
  1984. if (ix == DKIX_ERROR)
  1985. return NULL;
  1986. if (ix == DKIX_EMPTY || old_value == NULL) {
  1987. if (deflt) {
  1988. return Py_NewRef(deflt);
  1989. }
  1990. _PyErr_SetKeyError(key);
  1991. return NULL;
  1992. }
  1993. assert(old_value != NULL);
  1994. uint64_t new_version = _PyDict_NotifyEvent(
  1995. interp, PyDict_EVENT_DELETED, mp, key, NULL);
  1996. delitem_common(mp, hash, ix, Py_NewRef(old_value), new_version);
  1997. ASSERT_CONSISTENT(mp);
  1998. return old_value;
  1999. }
  2000. PyObject *
  2001. _PyDict_Pop(PyObject *dict, PyObject *key, PyObject *deflt)
  2002. {
  2003. Py_hash_t hash;
  2004. if (((PyDictObject *)dict)->ma_used == 0) {
  2005. if (deflt) {
  2006. return Py_NewRef(deflt);
  2007. }
  2008. _PyErr_SetKeyError(key);
  2009. return NULL;
  2010. }
  2011. if (!PyUnicode_CheckExact(key) || (hash = unicode_get_hash(key)) == -1) {
  2012. hash = PyObject_Hash(key);
  2013. if (hash == -1)
  2014. return NULL;
  2015. }
  2016. return _PyDict_Pop_KnownHash(dict, key, hash, deflt);
  2017. }
  2018. /* Internal version of dict.from_keys(). It is subclass-friendly. */
  2019. PyObject *
  2020. _PyDict_FromKeys(PyObject *cls, PyObject *iterable, PyObject *value)
  2021. {
  2022. PyObject *it; /* iter(iterable) */
  2023. PyObject *key;
  2024. PyObject *d;
  2025. int status;
  2026. PyInterpreterState *interp = _PyInterpreterState_GET();
  2027. d = _PyObject_CallNoArgs(cls);
  2028. if (d == NULL)
  2029. return NULL;
  2030. if (PyDict_CheckExact(d) && ((PyDictObject *)d)->ma_used == 0) {
  2031. if (PyDict_CheckExact(iterable)) {
  2032. PyDictObject *mp = (PyDictObject *)d;
  2033. PyObject *oldvalue;
  2034. Py_ssize_t pos = 0;
  2035. PyObject *key;
  2036. Py_hash_t hash;
  2037. int unicode = DK_IS_UNICODE(((PyDictObject*)iterable)->ma_keys);
  2038. if (dictresize(interp, mp,
  2039. estimate_log2_keysize(PyDict_GET_SIZE(iterable)),
  2040. unicode)) {
  2041. Py_DECREF(d);
  2042. return NULL;
  2043. }
  2044. while (_PyDict_Next(iterable, &pos, &key, &oldvalue, &hash)) {
  2045. if (insertdict(interp, mp,
  2046. Py_NewRef(key), hash, Py_NewRef(value))) {
  2047. Py_DECREF(d);
  2048. return NULL;
  2049. }
  2050. }
  2051. return d;
  2052. }
  2053. if (PyAnySet_CheckExact(iterable)) {
  2054. PyDictObject *mp = (PyDictObject *)d;
  2055. Py_ssize_t pos = 0;
  2056. PyObject *key;
  2057. Py_hash_t hash;
  2058. if (dictresize(interp, mp,
  2059. estimate_log2_keysize(PySet_GET_SIZE(iterable)), 0)) {
  2060. Py_DECREF(d);
  2061. return NULL;
  2062. }
  2063. while (_PySet_NextEntry(iterable, &pos, &key, &hash)) {
  2064. if (insertdict(interp, mp, Py_NewRef(key), hash, Py_NewRef(value))) {
  2065. Py_DECREF(d);
  2066. return NULL;
  2067. }
  2068. }
  2069. return d;
  2070. }
  2071. }
  2072. it = PyObject_GetIter(iterable);
  2073. if (it == NULL){
  2074. Py_DECREF(d);
  2075. return NULL;
  2076. }
  2077. if (PyDict_CheckExact(d)) {
  2078. while ((key = PyIter_Next(it)) != NULL) {
  2079. status = PyDict_SetItem(d, key, value);
  2080. Py_DECREF(key);
  2081. if (status < 0)
  2082. goto Fail;
  2083. }
  2084. } else {
  2085. while ((key = PyIter_Next(it)) != NULL) {
  2086. status = PyObject_SetItem(d, key, value);
  2087. Py_DECREF(key);
  2088. if (status < 0)
  2089. goto Fail;
  2090. }
  2091. }
  2092. if (PyErr_Occurred())
  2093. goto Fail;
  2094. Py_DECREF(it);
  2095. return d;
  2096. Fail:
  2097. Py_DECREF(it);
  2098. Py_DECREF(d);
  2099. return NULL;
  2100. }
  2101. /* Methods */
  2102. static void
  2103. dict_dealloc(PyDictObject *mp)
  2104. {
  2105. PyInterpreterState *interp = _PyInterpreterState_GET();
  2106. assert(Py_REFCNT(mp) == 0);
  2107. Py_SET_REFCNT(mp, 1);
  2108. _PyDict_NotifyEvent(interp, PyDict_EVENT_DEALLOCATED, mp, NULL, NULL);
  2109. if (Py_REFCNT(mp) > 1) {
  2110. Py_SET_REFCNT(mp, Py_REFCNT(mp) - 1);
  2111. return;
  2112. }
  2113. Py_SET_REFCNT(mp, 0);
  2114. PyDictValues *values = mp->ma_values;
  2115. PyDictKeysObject *keys = mp->ma_keys;
  2116. Py_ssize_t i, n;
  2117. /* bpo-31095: UnTrack is needed before calling any callbacks */
  2118. PyObject_GC_UnTrack(mp);
  2119. Py_TRASHCAN_BEGIN(mp, dict_dealloc)
  2120. if (values != NULL) {
  2121. for (i = 0, n = mp->ma_keys->dk_nentries; i < n; i++) {
  2122. Py_XDECREF(values->values[i]);
  2123. }
  2124. free_values(values);
  2125. dictkeys_decref(interp, keys);
  2126. }
  2127. else if (keys != NULL) {
  2128. assert(keys->dk_refcnt == 1 || keys == Py_EMPTY_KEYS);
  2129. dictkeys_decref(interp, keys);
  2130. }
  2131. #if PyDict_MAXFREELIST > 0
  2132. struct _Py_dict_state *state = get_dict_state(interp);
  2133. #ifdef Py_DEBUG
  2134. // new_dict() must not be called after _PyDict_Fini()
  2135. assert(state->numfree != -1);
  2136. #endif
  2137. if (state->numfree < PyDict_MAXFREELIST && Py_IS_TYPE(mp, &PyDict_Type)) {
  2138. state->free_list[state->numfree++] = mp;
  2139. OBJECT_STAT_INC(to_freelist);
  2140. }
  2141. else
  2142. #endif
  2143. {
  2144. Py_TYPE(mp)->tp_free((PyObject *)mp);
  2145. }
  2146. Py_TRASHCAN_END
  2147. }
  2148. static PyObject *
  2149. dict_repr(PyDictObject *mp)
  2150. {
  2151. Py_ssize_t i;
  2152. PyObject *key = NULL, *value = NULL;
  2153. _PyUnicodeWriter writer;
  2154. int first;
  2155. i = Py_ReprEnter((PyObject *)mp);
  2156. if (i != 0) {
  2157. return i > 0 ? PyUnicode_FromString("{...}") : NULL;
  2158. }
  2159. if (mp->ma_used == 0) {
  2160. Py_ReprLeave((PyObject *)mp);
  2161. return PyUnicode_FromString("{}");
  2162. }
  2163. _PyUnicodeWriter_Init(&writer);
  2164. writer.overallocate = 1;
  2165. /* "{" + "1: 2" + ", 3: 4" * (len - 1) + "}" */
  2166. writer.min_length = 1 + 4 + (2 + 4) * (mp->ma_used - 1) + 1;
  2167. if (_PyUnicodeWriter_WriteChar(&writer, '{') < 0)
  2168. goto error;
  2169. /* Do repr() on each key+value pair, and insert ": " between them.
  2170. Note that repr may mutate the dict. */
  2171. i = 0;
  2172. first = 1;
  2173. while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
  2174. PyObject *s;
  2175. int res;
  2176. /* Prevent repr from deleting key or value during key format. */
  2177. Py_INCREF(key);
  2178. Py_INCREF(value);
  2179. if (!first) {
  2180. if (_PyUnicodeWriter_WriteASCIIString(&writer, ", ", 2) < 0)
  2181. goto error;
  2182. }
  2183. first = 0;
  2184. s = PyObject_Repr(key);
  2185. if (s == NULL)
  2186. goto error;
  2187. res = _PyUnicodeWriter_WriteStr(&writer, s);
  2188. Py_DECREF(s);
  2189. if (res < 0)
  2190. goto error;
  2191. if (_PyUnicodeWriter_WriteASCIIString(&writer, ": ", 2) < 0)
  2192. goto error;
  2193. s = PyObject_Repr(value);
  2194. if (s == NULL)
  2195. goto error;
  2196. res = _PyUnicodeWriter_WriteStr(&writer, s);
  2197. Py_DECREF(s);
  2198. if (res < 0)
  2199. goto error;
  2200. Py_CLEAR(key);
  2201. Py_CLEAR(value);
  2202. }
  2203. writer.overallocate = 0;
  2204. if (_PyUnicodeWriter_WriteChar(&writer, '}') < 0)
  2205. goto error;
  2206. Py_ReprLeave((PyObject *)mp);
  2207. return _PyUnicodeWriter_Finish(&writer);
  2208. error:
  2209. Py_ReprLeave((PyObject *)mp);
  2210. _PyUnicodeWriter_Dealloc(&writer);
  2211. Py_XDECREF(key);
  2212. Py_XDECREF(value);
  2213. return NULL;
  2214. }
  2215. static Py_ssize_t
  2216. dict_length(PyDictObject *mp)
  2217. {
  2218. return mp->ma_used;
  2219. }
  2220. static PyObject *
  2221. dict_subscript(PyDictObject *mp, PyObject *key)
  2222. {
  2223. Py_ssize_t ix;
  2224. Py_hash_t hash;
  2225. PyObject *value;
  2226. if (!PyUnicode_CheckExact(key) || (hash = unicode_get_hash(key)) == -1) {
  2227. hash = PyObject_Hash(key);
  2228. if (hash == -1)
  2229. return NULL;
  2230. }
  2231. ix = _Py_dict_lookup(mp, key, hash, &value);
  2232. if (ix == DKIX_ERROR)
  2233. return NULL;
  2234. if (ix == DKIX_EMPTY || value == NULL) {
  2235. if (!PyDict_CheckExact(mp)) {
  2236. /* Look up __missing__ method if we're a subclass. */
  2237. PyObject *missing, *res;
  2238. missing = _PyObject_LookupSpecial(
  2239. (PyObject *)mp, &_Py_ID(__missing__));
  2240. if (missing != NULL) {
  2241. res = PyObject_CallOneArg(missing, key);
  2242. Py_DECREF(missing);
  2243. return res;
  2244. }
  2245. else if (PyErr_Occurred())
  2246. return NULL;
  2247. }
  2248. _PyErr_SetKeyError(key);
  2249. return NULL;
  2250. }
  2251. return Py_NewRef(value);
  2252. }
  2253. static int
  2254. dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
  2255. {
  2256. if (w == NULL)
  2257. return PyDict_DelItem((PyObject *)mp, v);
  2258. else
  2259. return PyDict_SetItem((PyObject *)mp, v, w);
  2260. }
  2261. static PyMappingMethods dict_as_mapping = {
  2262. (lenfunc)dict_length, /*mp_length*/
  2263. (binaryfunc)dict_subscript, /*mp_subscript*/
  2264. (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
  2265. };
  2266. static PyObject *
  2267. dict_keys(PyDictObject *mp)
  2268. {
  2269. PyObject *v;
  2270. Py_ssize_t n;
  2271. again:
  2272. n = mp->ma_used;
  2273. v = PyList_New(n);
  2274. if (v == NULL)
  2275. return NULL;
  2276. if (n != mp->ma_used) {
  2277. /* Durnit. The allocations caused the dict to resize.
  2278. * Just start over, this shouldn't normally happen.
  2279. */
  2280. Py_DECREF(v);
  2281. goto again;
  2282. }
  2283. /* Nothing we do below makes any function calls. */
  2284. Py_ssize_t j = 0, pos = 0;
  2285. PyObject *key;
  2286. while (_PyDict_Next((PyObject*)mp, &pos, &key, NULL, NULL)) {
  2287. assert(j < n);
  2288. PyList_SET_ITEM(v, j, Py_NewRef(key));
  2289. j++;
  2290. }
  2291. assert(j == n);
  2292. return v;
  2293. }
  2294. static PyObject *
  2295. dict_values(PyDictObject *mp)
  2296. {
  2297. PyObject *v;
  2298. Py_ssize_t n;
  2299. again:
  2300. n = mp->ma_used;
  2301. v = PyList_New(n);
  2302. if (v == NULL)
  2303. return NULL;
  2304. if (n != mp->ma_used) {
  2305. /* Durnit. The allocations caused the dict to resize.
  2306. * Just start over, this shouldn't normally happen.
  2307. */
  2308. Py_DECREF(v);
  2309. goto again;
  2310. }
  2311. /* Nothing we do below makes any function calls. */
  2312. Py_ssize_t j = 0, pos = 0;
  2313. PyObject *value;
  2314. while (_PyDict_Next((PyObject*)mp, &pos, NULL, &value, NULL)) {
  2315. assert(j < n);
  2316. PyList_SET_ITEM(v, j, Py_NewRef(value));
  2317. j++;
  2318. }
  2319. assert(j == n);
  2320. return v;
  2321. }
  2322. static PyObject *
  2323. dict_items(PyDictObject *mp)
  2324. {
  2325. PyObject *v;
  2326. Py_ssize_t i, n;
  2327. PyObject *item;
  2328. /* Preallocate the list of tuples, to avoid allocations during
  2329. * the loop over the items, which could trigger GC, which
  2330. * could resize the dict. :-(
  2331. */
  2332. again:
  2333. n = mp->ma_used;
  2334. v = PyList_New(n);
  2335. if (v == NULL)
  2336. return NULL;
  2337. for (i = 0; i < n; i++) {
  2338. item = PyTuple_New(2);
  2339. if (item == NULL) {
  2340. Py_DECREF(v);
  2341. return NULL;
  2342. }
  2343. PyList_SET_ITEM(v, i, item);
  2344. }
  2345. if (n != mp->ma_used) {
  2346. /* Durnit. The allocations caused the dict to resize.
  2347. * Just start over, this shouldn't normally happen.
  2348. */
  2349. Py_DECREF(v);
  2350. goto again;
  2351. }
  2352. /* Nothing we do below makes any function calls. */
  2353. Py_ssize_t j = 0, pos = 0;
  2354. PyObject *key, *value;
  2355. while (_PyDict_Next((PyObject*)mp, &pos, &key, &value, NULL)) {
  2356. assert(j < n);
  2357. PyObject *item = PyList_GET_ITEM(v, j);
  2358. PyTuple_SET_ITEM(item, 0, Py_NewRef(key));
  2359. PyTuple_SET_ITEM(item, 1, Py_NewRef(value));
  2360. j++;
  2361. }
  2362. assert(j == n);
  2363. return v;
  2364. }
  2365. /*[clinic input]
  2366. @classmethod
  2367. dict.fromkeys
  2368. iterable: object
  2369. value: object=None
  2370. /
  2371. Create a new dictionary with keys from iterable and values set to value.
  2372. [clinic start generated code]*/
  2373. static PyObject *
  2374. dict_fromkeys_impl(PyTypeObject *type, PyObject *iterable, PyObject *value)
  2375. /*[clinic end generated code: output=8fb98e4b10384999 input=382ba4855d0f74c3]*/
  2376. {
  2377. return _PyDict_FromKeys((PyObject *)type, iterable, value);
  2378. }
  2379. /* Single-arg dict update; used by dict_update_common and operators. */
  2380. static int
  2381. dict_update_arg(PyObject *self, PyObject *arg)
  2382. {
  2383. if (PyDict_CheckExact(arg)) {
  2384. return PyDict_Merge(self, arg, 1);
  2385. }
  2386. PyObject *func;
  2387. if (_PyObject_LookupAttr(arg, &_Py_ID(keys), &func) < 0) {
  2388. return -1;
  2389. }
  2390. if (func != NULL) {
  2391. Py_DECREF(func);
  2392. return PyDict_Merge(self, arg, 1);
  2393. }
  2394. return PyDict_MergeFromSeq2(self, arg, 1);
  2395. }
  2396. static int
  2397. dict_update_common(PyObject *self, PyObject *args, PyObject *kwds,
  2398. const char *methname)
  2399. {
  2400. PyObject *arg = NULL;
  2401. int result = 0;
  2402. if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg)) {
  2403. result = -1;
  2404. }
  2405. else if (arg != NULL) {
  2406. result = dict_update_arg(self, arg);
  2407. }
  2408. if (result == 0 && kwds != NULL) {
  2409. if (PyArg_ValidateKeywordArguments(kwds))
  2410. result = PyDict_Merge(self, kwds, 1);
  2411. else
  2412. result = -1;
  2413. }
  2414. return result;
  2415. }
  2416. /* Note: dict.update() uses the METH_VARARGS|METH_KEYWORDS calling convention.
  2417. Using METH_FASTCALL|METH_KEYWORDS would make dict.update(**dict2) calls
  2418. slower, see the issue #29312. */
  2419. static PyObject *
  2420. dict_update(PyObject *self, PyObject *args, PyObject *kwds)
  2421. {
  2422. if (dict_update_common(self, args, kwds, "update") != -1)
  2423. Py_RETURN_NONE;
  2424. return NULL;
  2425. }
  2426. /* Update unconditionally replaces existing items.
  2427. Merge has a 3rd argument 'override'; if set, it acts like Update,
  2428. otherwise it leaves existing items unchanged.
  2429. PyDict_{Update,Merge} update/merge from a mapping object.
  2430. PyDict_MergeFromSeq2 updates/merges from any iterable object
  2431. producing iterable objects of length 2.
  2432. */
  2433. int
  2434. PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
  2435. {
  2436. PyObject *it; /* iter(seq2) */
  2437. Py_ssize_t i; /* index into seq2 of current element */
  2438. PyObject *item; /* seq2[i] */
  2439. PyObject *fast; /* item as a 2-tuple or 2-list */
  2440. assert(d != NULL);
  2441. assert(PyDict_Check(d));
  2442. assert(seq2 != NULL);
  2443. it = PyObject_GetIter(seq2);
  2444. if (it == NULL)
  2445. return -1;
  2446. for (i = 0; ; ++i) {
  2447. PyObject *key, *value;
  2448. Py_ssize_t n;
  2449. fast = NULL;
  2450. item = PyIter_Next(it);
  2451. if (item == NULL) {
  2452. if (PyErr_Occurred())
  2453. goto Fail;
  2454. break;
  2455. }
  2456. /* Convert item to sequence, and verify length 2. */
  2457. fast = PySequence_Fast(item, "");
  2458. if (fast == NULL) {
  2459. if (PyErr_ExceptionMatches(PyExc_TypeError))
  2460. PyErr_Format(PyExc_TypeError,
  2461. "cannot convert dictionary update "
  2462. "sequence element #%zd to a sequence",
  2463. i);
  2464. goto Fail;
  2465. }
  2466. n = PySequence_Fast_GET_SIZE(fast);
  2467. if (n != 2) {
  2468. PyErr_Format(PyExc_ValueError,
  2469. "dictionary update sequence element #%zd "
  2470. "has length %zd; 2 is required",
  2471. i, n);
  2472. goto Fail;
  2473. }
  2474. /* Update/merge with this (key, value) pair. */
  2475. key = PySequence_Fast_GET_ITEM(fast, 0);
  2476. value = PySequence_Fast_GET_ITEM(fast, 1);
  2477. Py_INCREF(key);
  2478. Py_INCREF(value);
  2479. if (override) {
  2480. if (PyDict_SetItem(d, key, value) < 0) {
  2481. Py_DECREF(key);
  2482. Py_DECREF(value);
  2483. goto Fail;
  2484. }
  2485. }
  2486. else {
  2487. if (PyDict_SetDefault(d, key, value) == NULL) {
  2488. Py_DECREF(key);
  2489. Py_DECREF(value);
  2490. goto Fail;
  2491. }
  2492. }
  2493. Py_DECREF(key);
  2494. Py_DECREF(value);
  2495. Py_DECREF(fast);
  2496. Py_DECREF(item);
  2497. }
  2498. i = 0;
  2499. ASSERT_CONSISTENT(d);
  2500. goto Return;
  2501. Fail:
  2502. Py_XDECREF(item);
  2503. Py_XDECREF(fast);
  2504. i = -1;
  2505. Return:
  2506. Py_DECREF(it);
  2507. return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
  2508. }
  2509. static int
  2510. dict_merge(PyInterpreterState *interp, PyObject *a, PyObject *b, int override)
  2511. {
  2512. PyDictObject *mp, *other;
  2513. assert(0 <= override && override <= 2);
  2514. /* We accept for the argument either a concrete dictionary object,
  2515. * or an abstract "mapping" object. For the former, we can do
  2516. * things quite efficiently. For the latter, we only require that
  2517. * PyMapping_Keys() and PyObject_GetItem() be supported.
  2518. */
  2519. if (a == NULL || !PyDict_Check(a) || b == NULL) {
  2520. PyErr_BadInternalCall();
  2521. return -1;
  2522. }
  2523. mp = (PyDictObject*)a;
  2524. if (PyDict_Check(b) && (Py_TYPE(b)->tp_iter == (getiterfunc)dict_iter)) {
  2525. other = (PyDictObject*)b;
  2526. if (other == mp || other->ma_used == 0)
  2527. /* a.update(a) or a.update({}); nothing to do */
  2528. return 0;
  2529. if (mp->ma_used == 0) {
  2530. /* Since the target dict is empty, PyDict_GetItem()
  2531. * always returns NULL. Setting override to 1
  2532. * skips the unnecessary test.
  2533. */
  2534. override = 1;
  2535. PyDictKeysObject *okeys = other->ma_keys;
  2536. // If other is clean, combined, and just allocated, just clone it.
  2537. if (other->ma_values == NULL &&
  2538. other->ma_used == okeys->dk_nentries &&
  2539. (DK_LOG_SIZE(okeys) == PyDict_LOG_MINSIZE ||
  2540. USABLE_FRACTION(DK_SIZE(okeys)/2) < other->ma_used)) {
  2541. uint64_t new_version = _PyDict_NotifyEvent(
  2542. interp, PyDict_EVENT_CLONED, mp, b, NULL);
  2543. PyDictKeysObject *keys = clone_combined_dict_keys(other);
  2544. if (keys == NULL) {
  2545. return -1;
  2546. }
  2547. dictkeys_decref(interp, mp->ma_keys);
  2548. mp->ma_keys = keys;
  2549. if (mp->ma_values != NULL) {
  2550. free_values(mp->ma_values);
  2551. mp->ma_values = NULL;
  2552. }
  2553. mp->ma_used = other->ma_used;
  2554. mp->ma_version_tag = new_version;
  2555. ASSERT_CONSISTENT(mp);
  2556. if (_PyObject_GC_IS_TRACKED(other) && !_PyObject_GC_IS_TRACKED(mp)) {
  2557. /* Maintain tracking. */
  2558. _PyObject_GC_TRACK(mp);
  2559. }
  2560. return 0;
  2561. }
  2562. }
  2563. /* Do one big resize at the start, rather than
  2564. * incrementally resizing as we insert new items. Expect
  2565. * that there will be no (or few) overlapping keys.
  2566. */
  2567. if (USABLE_FRACTION(DK_SIZE(mp->ma_keys)) < other->ma_used) {
  2568. int unicode = DK_IS_UNICODE(other->ma_keys);
  2569. if (dictresize(interp, mp,
  2570. estimate_log2_keysize(mp->ma_used + other->ma_used),
  2571. unicode)) {
  2572. return -1;
  2573. }
  2574. }
  2575. Py_ssize_t orig_size = other->ma_keys->dk_nentries;
  2576. Py_ssize_t pos = 0;
  2577. Py_hash_t hash;
  2578. PyObject *key, *value;
  2579. while (_PyDict_Next((PyObject*)other, &pos, &key, &value, &hash)) {
  2580. int err = 0;
  2581. Py_INCREF(key);
  2582. Py_INCREF(value);
  2583. if (override == 1) {
  2584. err = insertdict(interp, mp,
  2585. Py_NewRef(key), hash, Py_NewRef(value));
  2586. }
  2587. else {
  2588. err = _PyDict_Contains_KnownHash(a, key, hash);
  2589. if (err == 0) {
  2590. err = insertdict(interp, mp,
  2591. Py_NewRef(key), hash, Py_NewRef(value));
  2592. }
  2593. else if (err > 0) {
  2594. if (override != 0) {
  2595. _PyErr_SetKeyError(key);
  2596. Py_DECREF(value);
  2597. Py_DECREF(key);
  2598. return -1;
  2599. }
  2600. err = 0;
  2601. }
  2602. }
  2603. Py_DECREF(value);
  2604. Py_DECREF(key);
  2605. if (err != 0)
  2606. return -1;
  2607. if (orig_size != other->ma_keys->dk_nentries) {
  2608. PyErr_SetString(PyExc_RuntimeError,
  2609. "dict mutated during update");
  2610. return -1;
  2611. }
  2612. }
  2613. }
  2614. else {
  2615. /* Do it the generic, slower way */
  2616. PyObject *keys = PyMapping_Keys(b);
  2617. PyObject *iter;
  2618. PyObject *key, *value;
  2619. int status;
  2620. if (keys == NULL)
  2621. /* Docstring says this is equivalent to E.keys() so
  2622. * if E doesn't have a .keys() method we want
  2623. * AttributeError to percolate up. Might as well
  2624. * do the same for any other error.
  2625. */
  2626. return -1;
  2627. iter = PyObject_GetIter(keys);
  2628. Py_DECREF(keys);
  2629. if (iter == NULL)
  2630. return -1;
  2631. for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
  2632. if (override != 1) {
  2633. status = PyDict_Contains(a, key);
  2634. if (status != 0) {
  2635. if (status > 0) {
  2636. if (override == 0) {
  2637. Py_DECREF(key);
  2638. continue;
  2639. }
  2640. _PyErr_SetKeyError(key);
  2641. }
  2642. Py_DECREF(key);
  2643. Py_DECREF(iter);
  2644. return -1;
  2645. }
  2646. }
  2647. value = PyObject_GetItem(b, key);
  2648. if (value == NULL) {
  2649. Py_DECREF(iter);
  2650. Py_DECREF(key);
  2651. return -1;
  2652. }
  2653. status = PyDict_SetItem(a, key, value);
  2654. Py_DECREF(key);
  2655. Py_DECREF(value);
  2656. if (status < 0) {
  2657. Py_DECREF(iter);
  2658. return -1;
  2659. }
  2660. }
  2661. Py_DECREF(iter);
  2662. if (PyErr_Occurred())
  2663. /* Iterator completed, via error */
  2664. return -1;
  2665. }
  2666. ASSERT_CONSISTENT(a);
  2667. return 0;
  2668. }
  2669. int
  2670. PyDict_Update(PyObject *a, PyObject *b)
  2671. {
  2672. PyInterpreterState *interp = _PyInterpreterState_GET();
  2673. return dict_merge(interp, a, b, 1);
  2674. }
  2675. int
  2676. PyDict_Merge(PyObject *a, PyObject *b, int override)
  2677. {
  2678. PyInterpreterState *interp = _PyInterpreterState_GET();
  2679. /* XXX Deprecate override not in (0, 1). */
  2680. return dict_merge(interp, a, b, override != 0);
  2681. }
  2682. int
  2683. _PyDict_MergeEx(PyObject *a, PyObject *b, int override)
  2684. {
  2685. PyInterpreterState *interp = _PyInterpreterState_GET();
  2686. return dict_merge(interp, a, b, override);
  2687. }
  2688. static PyObject *
  2689. dict_copy(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
  2690. {
  2691. return PyDict_Copy((PyObject*)mp);
  2692. }
  2693. PyObject *
  2694. PyDict_Copy(PyObject *o)
  2695. {
  2696. PyObject *copy;
  2697. PyDictObject *mp;
  2698. PyInterpreterState *interp = _PyInterpreterState_GET();
  2699. if (o == NULL || !PyDict_Check(o)) {
  2700. PyErr_BadInternalCall();
  2701. return NULL;
  2702. }
  2703. mp = (PyDictObject *)o;
  2704. if (mp->ma_used == 0) {
  2705. /* The dict is empty; just return a new dict. */
  2706. return PyDict_New();
  2707. }
  2708. if (_PyDict_HasSplitTable(mp)) {
  2709. PyDictObject *split_copy;
  2710. size_t size = shared_keys_usable_size(mp->ma_keys);
  2711. PyDictValues *newvalues = new_values(size);
  2712. if (newvalues == NULL)
  2713. return PyErr_NoMemory();
  2714. split_copy = PyObject_GC_New(PyDictObject, &PyDict_Type);
  2715. if (split_copy == NULL) {
  2716. free_values(newvalues);
  2717. return NULL;
  2718. }
  2719. size_t prefix_size = ((uint8_t *)newvalues)[-1];
  2720. memcpy(((char *)newvalues)-prefix_size, ((char *)mp->ma_values)-prefix_size, prefix_size-1);
  2721. split_copy->ma_values = newvalues;
  2722. split_copy->ma_keys = mp->ma_keys;
  2723. split_copy->ma_used = mp->ma_used;
  2724. split_copy->ma_version_tag = DICT_NEXT_VERSION(interp);
  2725. dictkeys_incref(mp->ma_keys);
  2726. for (size_t i = 0; i < size; i++) {
  2727. PyObject *value = mp->ma_values->values[i];
  2728. split_copy->ma_values->values[i] = Py_XNewRef(value);
  2729. }
  2730. if (_PyObject_GC_IS_TRACKED(mp))
  2731. _PyObject_GC_TRACK(split_copy);
  2732. return (PyObject *)split_copy;
  2733. }
  2734. if (Py_TYPE(mp)->tp_iter == (getiterfunc)dict_iter &&
  2735. mp->ma_values == NULL &&
  2736. (mp->ma_used >= (mp->ma_keys->dk_nentries * 2) / 3))
  2737. {
  2738. /* Use fast-copy if:
  2739. (1) type(mp) doesn't override tp_iter; and
  2740. (2) 'mp' is not a split-dict; and
  2741. (3) if 'mp' is non-compact ('del' operation does not resize dicts),
  2742. do fast-copy only if it has at most 1/3 non-used keys.
  2743. The last condition (3) is important to guard against a pathological
  2744. case when a large dict is almost emptied with multiple del/pop
  2745. operations and copied after that. In cases like this, we defer to
  2746. PyDict_Merge, which produces a compacted copy.
  2747. */
  2748. PyDictKeysObject *keys = clone_combined_dict_keys(mp);
  2749. if (keys == NULL) {
  2750. return NULL;
  2751. }
  2752. PyDictObject *new = (PyDictObject *)new_dict(interp, keys, NULL, 0, 0);
  2753. if (new == NULL) {
  2754. /* In case of an error, `new_dict()` takes care of
  2755. cleaning up `keys`. */
  2756. return NULL;
  2757. }
  2758. new->ma_used = mp->ma_used;
  2759. ASSERT_CONSISTENT(new);
  2760. if (_PyObject_GC_IS_TRACKED(mp)) {
  2761. /* Maintain tracking. */
  2762. _PyObject_GC_TRACK(new);
  2763. }
  2764. return (PyObject *)new;
  2765. }
  2766. copy = PyDict_New();
  2767. if (copy == NULL)
  2768. return NULL;
  2769. if (dict_merge(interp, copy, o, 1) == 0)
  2770. return copy;
  2771. Py_DECREF(copy);
  2772. return NULL;
  2773. }
  2774. Py_ssize_t
  2775. PyDict_Size(PyObject *mp)
  2776. {
  2777. if (mp == NULL || !PyDict_Check(mp)) {
  2778. PyErr_BadInternalCall();
  2779. return -1;
  2780. }
  2781. return ((PyDictObject *)mp)->ma_used;
  2782. }
  2783. PyObject *
  2784. PyDict_Keys(PyObject *mp)
  2785. {
  2786. if (mp == NULL || !PyDict_Check(mp)) {
  2787. PyErr_BadInternalCall();
  2788. return NULL;
  2789. }
  2790. return dict_keys((PyDictObject *)mp);
  2791. }
  2792. PyObject *
  2793. PyDict_Values(PyObject *mp)
  2794. {
  2795. if (mp == NULL || !PyDict_Check(mp)) {
  2796. PyErr_BadInternalCall();
  2797. return NULL;
  2798. }
  2799. return dict_values((PyDictObject *)mp);
  2800. }
  2801. PyObject *
  2802. PyDict_Items(PyObject *mp)
  2803. {
  2804. if (mp == NULL || !PyDict_Check(mp)) {
  2805. PyErr_BadInternalCall();
  2806. return NULL;
  2807. }
  2808. return dict_items((PyDictObject *)mp);
  2809. }
  2810. /* Return 1 if dicts equal, 0 if not, -1 if error.
  2811. * Gets out as soon as any difference is detected.
  2812. * Uses only Py_EQ comparison.
  2813. */
  2814. static int
  2815. dict_equal(PyDictObject *a, PyDictObject *b)
  2816. {
  2817. Py_ssize_t i;
  2818. if (a->ma_used != b->ma_used)
  2819. /* can't be equal if # of entries differ */
  2820. return 0;
  2821. /* Same # of entries -- check all of 'em. Exit early on any diff. */
  2822. for (i = 0; i < a->ma_keys->dk_nentries; i++) {
  2823. PyObject *key, *aval;
  2824. Py_hash_t hash;
  2825. if (DK_IS_UNICODE(a->ma_keys)) {
  2826. PyDictUnicodeEntry *ep = &DK_UNICODE_ENTRIES(a->ma_keys)[i];
  2827. key = ep->me_key;
  2828. if (key == NULL) {
  2829. continue;
  2830. }
  2831. hash = unicode_get_hash(key);
  2832. if (a->ma_values)
  2833. aval = a->ma_values->values[i];
  2834. else
  2835. aval = ep->me_value;
  2836. }
  2837. else {
  2838. PyDictKeyEntry *ep = &DK_ENTRIES(a->ma_keys)[i];
  2839. key = ep->me_key;
  2840. aval = ep->me_value;
  2841. hash = ep->me_hash;
  2842. }
  2843. if (aval != NULL) {
  2844. int cmp;
  2845. PyObject *bval;
  2846. /* temporarily bump aval's refcount to ensure it stays
  2847. alive until we're done with it */
  2848. Py_INCREF(aval);
  2849. /* ditto for key */
  2850. Py_INCREF(key);
  2851. /* reuse the known hash value */
  2852. _Py_dict_lookup(b, key, hash, &bval);
  2853. if (bval == NULL) {
  2854. Py_DECREF(key);
  2855. Py_DECREF(aval);
  2856. if (PyErr_Occurred())
  2857. return -1;
  2858. return 0;
  2859. }
  2860. Py_INCREF(bval);
  2861. cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
  2862. Py_DECREF(key);
  2863. Py_DECREF(aval);
  2864. Py_DECREF(bval);
  2865. if (cmp <= 0) /* error or not equal */
  2866. return cmp;
  2867. }
  2868. }
  2869. return 1;
  2870. }
  2871. static PyObject *
  2872. dict_richcompare(PyObject *v, PyObject *w, int op)
  2873. {
  2874. int cmp;
  2875. PyObject *res;
  2876. if (!PyDict_Check(v) || !PyDict_Check(w)) {
  2877. res = Py_NotImplemented;
  2878. }
  2879. else if (op == Py_EQ || op == Py_NE) {
  2880. cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
  2881. if (cmp < 0)
  2882. return NULL;
  2883. res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
  2884. }
  2885. else
  2886. res = Py_NotImplemented;
  2887. return Py_NewRef(res);
  2888. }
  2889. /*[clinic input]
  2890. @coexist
  2891. dict.__contains__
  2892. key: object
  2893. /
  2894. True if the dictionary has the specified key, else False.
  2895. [clinic start generated code]*/
  2896. static PyObject *
  2897. dict___contains__(PyDictObject *self, PyObject *key)
  2898. /*[clinic end generated code: output=a3d03db709ed6e6b input=fe1cb42ad831e820]*/
  2899. {
  2900. register PyDictObject *mp = self;
  2901. Py_hash_t hash;
  2902. Py_ssize_t ix;
  2903. PyObject *value;
  2904. if (!PyUnicode_CheckExact(key) || (hash = unicode_get_hash(key)) == -1) {
  2905. hash = PyObject_Hash(key);
  2906. if (hash == -1)
  2907. return NULL;
  2908. }
  2909. ix = _Py_dict_lookup(mp, key, hash, &value);
  2910. if (ix == DKIX_ERROR)
  2911. return NULL;
  2912. if (ix == DKIX_EMPTY || value == NULL)
  2913. Py_RETURN_FALSE;
  2914. Py_RETURN_TRUE;
  2915. }
  2916. /*[clinic input]
  2917. dict.get
  2918. key: object
  2919. default: object = None
  2920. /
  2921. Return the value for key if key is in the dictionary, else default.
  2922. [clinic start generated code]*/
  2923. static PyObject *
  2924. dict_get_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
  2925. /*[clinic end generated code: output=bba707729dee05bf input=279ddb5790b6b107]*/
  2926. {
  2927. PyObject *val = NULL;
  2928. Py_hash_t hash;
  2929. Py_ssize_t ix;
  2930. if (!PyUnicode_CheckExact(key) || (hash = unicode_get_hash(key)) == -1) {
  2931. hash = PyObject_Hash(key);
  2932. if (hash == -1)
  2933. return NULL;
  2934. }
  2935. ix = _Py_dict_lookup(self, key, hash, &val);
  2936. if (ix == DKIX_ERROR)
  2937. return NULL;
  2938. if (ix == DKIX_EMPTY || val == NULL) {
  2939. val = default_value;
  2940. }
  2941. return Py_NewRef(val);
  2942. }
  2943. PyObject *
  2944. PyDict_SetDefault(PyObject *d, PyObject *key, PyObject *defaultobj)
  2945. {
  2946. PyDictObject *mp = (PyDictObject *)d;
  2947. PyObject *value;
  2948. Py_hash_t hash;
  2949. PyInterpreterState *interp = _PyInterpreterState_GET();
  2950. if (!PyDict_Check(d)) {
  2951. PyErr_BadInternalCall();
  2952. return NULL;
  2953. }
  2954. if (!PyUnicode_CheckExact(key) || (hash = unicode_get_hash(key)) == -1) {
  2955. hash = PyObject_Hash(key);
  2956. if (hash == -1)
  2957. return NULL;
  2958. }
  2959. if (mp->ma_keys == Py_EMPTY_KEYS) {
  2960. if (insert_to_emptydict(interp, mp, Py_NewRef(key), hash,
  2961. Py_NewRef(defaultobj)) < 0) {
  2962. return NULL;
  2963. }
  2964. return defaultobj;
  2965. }
  2966. if (!PyUnicode_CheckExact(key) && DK_IS_UNICODE(mp->ma_keys)) {
  2967. if (insertion_resize(interp, mp, 0) < 0) {
  2968. return NULL;
  2969. }
  2970. }
  2971. Py_ssize_t ix = _Py_dict_lookup(mp, key, hash, &value);
  2972. if (ix == DKIX_ERROR)
  2973. return NULL;
  2974. if (ix == DKIX_EMPTY) {
  2975. value = defaultobj;
  2976. if (mp->ma_keys->dk_usable <= 0) {
  2977. if (insertion_resize(interp, mp, 1) < 0) {
  2978. return NULL;
  2979. }
  2980. }
  2981. uint64_t new_version = _PyDict_NotifyEvent(
  2982. interp, PyDict_EVENT_ADDED, mp, key, defaultobj);
  2983. mp->ma_keys->dk_version = 0;
  2984. Py_ssize_t hashpos = find_empty_slot(mp->ma_keys, hash);
  2985. dictkeys_set_index(mp->ma_keys, hashpos, mp->ma_keys->dk_nentries);
  2986. if (DK_IS_UNICODE(mp->ma_keys)) {
  2987. assert(PyUnicode_CheckExact(key));
  2988. PyDictUnicodeEntry *ep = &DK_UNICODE_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
  2989. ep->me_key = Py_NewRef(key);
  2990. if (_PyDict_HasSplitTable(mp)) {
  2991. Py_ssize_t index = (int)mp->ma_keys->dk_nentries;
  2992. assert(index < SHARED_KEYS_MAX_SIZE);
  2993. assert(mp->ma_values->values[index] == NULL);
  2994. mp->ma_values->values[index] = Py_NewRef(value);
  2995. _PyDictValues_AddToInsertionOrder(mp->ma_values, index);
  2996. }
  2997. else {
  2998. ep->me_value = Py_NewRef(value);
  2999. }
  3000. }
  3001. else {
  3002. PyDictKeyEntry *ep = &DK_ENTRIES(mp->ma_keys)[mp->ma_keys->dk_nentries];
  3003. ep->me_key = Py_NewRef(key);
  3004. ep->me_hash = hash;
  3005. ep->me_value = Py_NewRef(value);
  3006. }
  3007. MAINTAIN_TRACKING(mp, key, value);
  3008. mp->ma_used++;
  3009. mp->ma_version_tag = new_version;
  3010. mp->ma_keys->dk_usable--;
  3011. mp->ma_keys->dk_nentries++;
  3012. assert(mp->ma_keys->dk_usable >= 0);
  3013. }
  3014. else if (value == NULL) {
  3015. uint64_t new_version = _PyDict_NotifyEvent(
  3016. interp, PyDict_EVENT_ADDED, mp, key, defaultobj);
  3017. value = defaultobj;
  3018. assert(_PyDict_HasSplitTable(mp));
  3019. assert(mp->ma_values->values[ix] == NULL);
  3020. MAINTAIN_TRACKING(mp, key, value);
  3021. mp->ma_values->values[ix] = Py_NewRef(value);
  3022. _PyDictValues_AddToInsertionOrder(mp->ma_values, ix);
  3023. mp->ma_used++;
  3024. mp->ma_version_tag = new_version;
  3025. }
  3026. ASSERT_CONSISTENT(mp);
  3027. return value;
  3028. }
  3029. /*[clinic input]
  3030. dict.setdefault
  3031. key: object
  3032. default: object = None
  3033. /
  3034. Insert key with a value of default if key is not in the dictionary.
  3035. Return the value for key if key is in the dictionary, else default.
  3036. [clinic start generated code]*/
  3037. static PyObject *
  3038. dict_setdefault_impl(PyDictObject *self, PyObject *key,
  3039. PyObject *default_value)
  3040. /*[clinic end generated code: output=f8c1101ebf69e220 input=0f063756e815fd9d]*/
  3041. {
  3042. PyObject *val;
  3043. val = PyDict_SetDefault((PyObject *)self, key, default_value);
  3044. return Py_XNewRef(val);
  3045. }
  3046. static PyObject *
  3047. dict_clear(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
  3048. {
  3049. PyDict_Clear((PyObject *)mp);
  3050. Py_RETURN_NONE;
  3051. }
  3052. /*[clinic input]
  3053. dict.pop
  3054. key: object
  3055. default: object = NULL
  3056. /
  3057. D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  3058. If the key is not found, return the default if given; otherwise,
  3059. raise a KeyError.
  3060. [clinic start generated code]*/
  3061. static PyObject *
  3062. dict_pop_impl(PyDictObject *self, PyObject *key, PyObject *default_value)
  3063. /*[clinic end generated code: output=3abb47b89f24c21c input=e221baa01044c44c]*/
  3064. {
  3065. return _PyDict_Pop((PyObject*)self, key, default_value);
  3066. }
  3067. /*[clinic input]
  3068. dict.popitem
  3069. Remove and return a (key, value) pair as a 2-tuple.
  3070. Pairs are returned in LIFO (last-in, first-out) order.
  3071. Raises KeyError if the dict is empty.
  3072. [clinic start generated code]*/
  3073. static PyObject *
  3074. dict_popitem_impl(PyDictObject *self)
  3075. /*[clinic end generated code: output=e65fcb04420d230d input=1c38a49f21f64941]*/
  3076. {
  3077. Py_ssize_t i, j;
  3078. PyObject *res;
  3079. uint64_t new_version;
  3080. PyInterpreterState *interp = _PyInterpreterState_GET();
  3081. /* Allocate the result tuple before checking the size. Believe it
  3082. * or not, this allocation could trigger a garbage collection which
  3083. * could empty the dict, so if we checked the size first and that
  3084. * happened, the result would be an infinite loop (searching for an
  3085. * entry that no longer exists). Note that the usual popitem()
  3086. * idiom is "while d: k, v = d.popitem()". so needing to throw the
  3087. * tuple away if the dict *is* empty isn't a significant
  3088. * inefficiency -- possible, but unlikely in practice.
  3089. */
  3090. res = PyTuple_New(2);
  3091. if (res == NULL)
  3092. return NULL;
  3093. if (self->ma_used == 0) {
  3094. Py_DECREF(res);
  3095. PyErr_SetString(PyExc_KeyError, "popitem(): dictionary is empty");
  3096. return NULL;
  3097. }
  3098. /* Convert split table to combined table */
  3099. if (self->ma_keys->dk_kind == DICT_KEYS_SPLIT) {
  3100. if (dictresize(interp, self, DK_LOG_SIZE(self->ma_keys), 1)) {
  3101. Py_DECREF(res);
  3102. return NULL;
  3103. }
  3104. }
  3105. self->ma_keys->dk_version = 0;
  3106. /* Pop last item */
  3107. PyObject *key, *value;
  3108. Py_hash_t hash;
  3109. if (DK_IS_UNICODE(self->ma_keys)) {
  3110. PyDictUnicodeEntry *ep0 = DK_UNICODE_ENTRIES(self->ma_keys);
  3111. i = self->ma_keys->dk_nentries - 1;
  3112. while (i >= 0 && ep0[i].me_value == NULL) {
  3113. i--;
  3114. }
  3115. assert(i >= 0);
  3116. key = ep0[i].me_key;
  3117. new_version = _PyDict_NotifyEvent(
  3118. interp, PyDict_EVENT_DELETED, self, key, NULL);
  3119. hash = unicode_get_hash(key);
  3120. value = ep0[i].me_value;
  3121. ep0[i].me_key = NULL;
  3122. ep0[i].me_value = NULL;
  3123. }
  3124. else {
  3125. PyDictKeyEntry *ep0 = DK_ENTRIES(self->ma_keys);
  3126. i = self->ma_keys->dk_nentries - 1;
  3127. while (i >= 0 && ep0[i].me_value == NULL) {
  3128. i--;
  3129. }
  3130. assert(i >= 0);
  3131. key = ep0[i].me_key;
  3132. new_version = _PyDict_NotifyEvent(
  3133. interp, PyDict_EVENT_DELETED, self, key, NULL);
  3134. hash = ep0[i].me_hash;
  3135. value = ep0[i].me_value;
  3136. ep0[i].me_key = NULL;
  3137. ep0[i].me_hash = -1;
  3138. ep0[i].me_value = NULL;
  3139. }
  3140. j = lookdict_index(self->ma_keys, hash, i);
  3141. assert(j >= 0);
  3142. assert(dictkeys_get_index(self->ma_keys, j) == i);
  3143. dictkeys_set_index(self->ma_keys, j, DKIX_DUMMY);
  3144. PyTuple_SET_ITEM(res, 0, key);
  3145. PyTuple_SET_ITEM(res, 1, value);
  3146. /* We can't dk_usable++ since there is DKIX_DUMMY in indices */
  3147. self->ma_keys->dk_nentries = i;
  3148. self->ma_used--;
  3149. self->ma_version_tag = new_version;
  3150. ASSERT_CONSISTENT(self);
  3151. return res;
  3152. }
  3153. static int
  3154. dict_traverse(PyObject *op, visitproc visit, void *arg)
  3155. {
  3156. PyDictObject *mp = (PyDictObject *)op;
  3157. PyDictKeysObject *keys = mp->ma_keys;
  3158. Py_ssize_t i, n = keys->dk_nentries;
  3159. if (DK_IS_UNICODE(keys)) {
  3160. if (mp->ma_values != NULL) {
  3161. for (i = 0; i < n; i++) {
  3162. Py_VISIT(mp->ma_values->values[i]);
  3163. }
  3164. }
  3165. else {
  3166. PyDictUnicodeEntry *entries = DK_UNICODE_ENTRIES(keys);
  3167. for (i = 0; i < n; i++) {
  3168. Py_VISIT(entries[i].me_value);
  3169. }
  3170. }
  3171. }
  3172. else {
  3173. PyDictKeyEntry *entries = DK_ENTRIES(keys);
  3174. for (i = 0; i < n; i++) {
  3175. if (entries[i].me_value != NULL) {
  3176. Py_VISIT(entries[i].me_value);
  3177. Py_VISIT(entries[i].me_key);
  3178. }
  3179. }
  3180. }
  3181. return 0;
  3182. }
  3183. static int
  3184. dict_tp_clear(PyObject *op)
  3185. {
  3186. PyDict_Clear(op);
  3187. return 0;
  3188. }
  3189. static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
  3190. Py_ssize_t
  3191. _PyDict_SizeOf(PyDictObject *mp)
  3192. {
  3193. size_t res = _PyObject_SIZE(Py_TYPE(mp));
  3194. if (mp->ma_values) {
  3195. res += shared_keys_usable_size(mp->ma_keys) * sizeof(PyObject*);
  3196. }
  3197. /* If the dictionary is split, the keys portion is accounted-for
  3198. in the type object. */
  3199. if (mp->ma_keys->dk_refcnt == 1) {
  3200. res += _PyDict_KeysSize(mp->ma_keys);
  3201. }
  3202. assert(res <= (size_t)PY_SSIZE_T_MAX);
  3203. return (Py_ssize_t)res;
  3204. }
  3205. size_t
  3206. _PyDict_KeysSize(PyDictKeysObject *keys)
  3207. {
  3208. size_t es = (keys->dk_kind == DICT_KEYS_GENERAL
  3209. ? sizeof(PyDictKeyEntry) : sizeof(PyDictUnicodeEntry));
  3210. size_t size = sizeof(PyDictKeysObject);
  3211. size += (size_t)1 << keys->dk_log2_index_bytes;
  3212. size += USABLE_FRACTION((size_t)DK_SIZE(keys)) * es;
  3213. return size;
  3214. }
  3215. static PyObject *
  3216. dict_sizeof(PyDictObject *mp, PyObject *Py_UNUSED(ignored))
  3217. {
  3218. return PyLong_FromSsize_t(_PyDict_SizeOf(mp));
  3219. }
  3220. static PyObject *
  3221. dict_or(PyObject *self, PyObject *other)
  3222. {
  3223. if (!PyDict_Check(self) || !PyDict_Check(other)) {
  3224. Py_RETURN_NOTIMPLEMENTED;
  3225. }
  3226. PyObject *new = PyDict_Copy(self);
  3227. if (new == NULL) {
  3228. return NULL;
  3229. }
  3230. if (dict_update_arg(new, other)) {
  3231. Py_DECREF(new);
  3232. return NULL;
  3233. }
  3234. return new;
  3235. }
  3236. static PyObject *
  3237. dict_ior(PyObject *self, PyObject *other)
  3238. {
  3239. if (dict_update_arg(self, other)) {
  3240. return NULL;
  3241. }
  3242. return Py_NewRef(self);
  3243. }
  3244. PyDoc_STRVAR(getitem__doc__,
  3245. "__getitem__($self, key, /)\n--\n\nReturn self[key].");
  3246. PyDoc_STRVAR(sizeof__doc__,
  3247. "D.__sizeof__() -> size of D in memory, in bytes");
  3248. PyDoc_STRVAR(update__doc__,
  3249. "D.update([E, ]**F) -> None. Update D from dict/iterable E and F.\n\
  3250. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]\n\
  3251. If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v\n\
  3252. In either case, this is followed by: for k in F: D[k] = F[k]");
  3253. PyDoc_STRVAR(clear__doc__,
  3254. "D.clear() -> None. Remove all items from D.");
  3255. PyDoc_STRVAR(copy__doc__,
  3256. "D.copy() -> a shallow copy of D");
  3257. /* Forward */
  3258. static PyObject *dictkeys_new(PyObject *, PyObject *);
  3259. static PyObject *dictitems_new(PyObject *, PyObject *);
  3260. static PyObject *dictvalues_new(PyObject *, PyObject *);
  3261. PyDoc_STRVAR(keys__doc__,
  3262. "D.keys() -> a set-like object providing a view on D's keys");
  3263. PyDoc_STRVAR(items__doc__,
  3264. "D.items() -> a set-like object providing a view on D's items");
  3265. PyDoc_STRVAR(values__doc__,
  3266. "D.values() -> an object providing a view on D's values");
  3267. static PyMethodDef mapp_methods[] = {
  3268. DICT___CONTAINS___METHODDEF
  3269. {"__getitem__", _PyCFunction_CAST(dict_subscript), METH_O | METH_COEXIST,
  3270. getitem__doc__},
  3271. {"__sizeof__", _PyCFunction_CAST(dict_sizeof), METH_NOARGS,
  3272. sizeof__doc__},
  3273. DICT_GET_METHODDEF
  3274. DICT_SETDEFAULT_METHODDEF
  3275. DICT_POP_METHODDEF
  3276. DICT_POPITEM_METHODDEF
  3277. {"keys", dictkeys_new, METH_NOARGS,
  3278. keys__doc__},
  3279. {"items", dictitems_new, METH_NOARGS,
  3280. items__doc__},
  3281. {"values", dictvalues_new, METH_NOARGS,
  3282. values__doc__},
  3283. {"update", _PyCFunction_CAST(dict_update), METH_VARARGS | METH_KEYWORDS,
  3284. update__doc__},
  3285. DICT_FROMKEYS_METHODDEF
  3286. {"clear", (PyCFunction)dict_clear, METH_NOARGS,
  3287. clear__doc__},
  3288. {"copy", (PyCFunction)dict_copy, METH_NOARGS,
  3289. copy__doc__},
  3290. DICT___REVERSED___METHODDEF
  3291. {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  3292. {NULL, NULL} /* sentinel */
  3293. };
  3294. /* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
  3295. int
  3296. PyDict_Contains(PyObject *op, PyObject *key)
  3297. {
  3298. Py_hash_t hash;
  3299. Py_ssize_t ix;
  3300. PyDictObject *mp = (PyDictObject *)op;
  3301. PyObject *value;
  3302. if (!PyUnicode_CheckExact(key) || (hash = unicode_get_hash(key)) == -1) {
  3303. hash = PyObject_Hash(key);
  3304. if (hash == -1)
  3305. return -1;
  3306. }
  3307. ix = _Py_dict_lookup(mp, key, hash, &value);
  3308. if (ix == DKIX_ERROR)
  3309. return -1;
  3310. return (ix != DKIX_EMPTY && value != NULL);
  3311. }
  3312. /* Internal version of PyDict_Contains used when the hash value is already known */
  3313. int
  3314. _PyDict_Contains_KnownHash(PyObject *op, PyObject *key, Py_hash_t hash)
  3315. {
  3316. PyDictObject *mp = (PyDictObject *)op;
  3317. PyObject *value;
  3318. Py_ssize_t ix;
  3319. ix = _Py_dict_lookup(mp, key, hash, &value);
  3320. if (ix == DKIX_ERROR)
  3321. return -1;
  3322. return (ix != DKIX_EMPTY && value != NULL);
  3323. }
  3324. int
  3325. _PyDict_ContainsId(PyObject *op, _Py_Identifier *key)
  3326. {
  3327. PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
  3328. if (kv == NULL) {
  3329. return -1;
  3330. }
  3331. return PyDict_Contains(op, kv);
  3332. }
  3333. /* Hack to implement "key in dict" */
  3334. static PySequenceMethods dict_as_sequence = {
  3335. 0, /* sq_length */
  3336. 0, /* sq_concat */
  3337. 0, /* sq_repeat */
  3338. 0, /* sq_item */
  3339. 0, /* sq_slice */
  3340. 0, /* sq_ass_item */
  3341. 0, /* sq_ass_slice */
  3342. PyDict_Contains, /* sq_contains */
  3343. 0, /* sq_inplace_concat */
  3344. 0, /* sq_inplace_repeat */
  3345. };
  3346. static PyNumberMethods dict_as_number = {
  3347. .nb_or = dict_or,
  3348. .nb_inplace_or = dict_ior,
  3349. };
  3350. static PyObject *
  3351. dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  3352. {
  3353. assert(type != NULL);
  3354. assert(type->tp_alloc != NULL);
  3355. // dict subclasses must implement the GC protocol
  3356. assert(_PyType_IS_GC(type));
  3357. PyObject *self = type->tp_alloc(type, 0);
  3358. if (self == NULL) {
  3359. return NULL;
  3360. }
  3361. PyDictObject *d = (PyDictObject *)self;
  3362. d->ma_used = 0;
  3363. d->ma_version_tag = DICT_NEXT_VERSION(
  3364. _PyInterpreterState_GET());
  3365. dictkeys_incref(Py_EMPTY_KEYS);
  3366. d->ma_keys = Py_EMPTY_KEYS;
  3367. d->ma_values = NULL;
  3368. ASSERT_CONSISTENT(d);
  3369. if (type != &PyDict_Type) {
  3370. // Don't track if a subclass tp_alloc is PyType_GenericAlloc()
  3371. if (!_PyObject_GC_IS_TRACKED(d)) {
  3372. _PyObject_GC_TRACK(d);
  3373. }
  3374. }
  3375. else {
  3376. // _PyType_AllocNoTrack() does not track the created object
  3377. assert(!_PyObject_GC_IS_TRACKED(d));
  3378. }
  3379. return self;
  3380. }
  3381. static int
  3382. dict_init(PyObject *self, PyObject *args, PyObject *kwds)
  3383. {
  3384. return dict_update_common(self, args, kwds, "dict");
  3385. }
  3386. static PyObject *
  3387. dict_vectorcall(PyObject *type, PyObject * const*args,
  3388. size_t nargsf, PyObject *kwnames)
  3389. {
  3390. Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);
  3391. if (!_PyArg_CheckPositional("dict", nargs, 0, 1)) {
  3392. return NULL;
  3393. }
  3394. PyObject *self = dict_new(_PyType_CAST(type), NULL, NULL);
  3395. if (self == NULL) {
  3396. return NULL;
  3397. }
  3398. if (nargs == 1) {
  3399. if (dict_update_arg(self, args[0]) < 0) {
  3400. Py_DECREF(self);
  3401. return NULL;
  3402. }
  3403. args++;
  3404. }
  3405. if (kwnames != NULL) {
  3406. for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(kwnames); i++) {
  3407. if (PyDict_SetItem(self, PyTuple_GET_ITEM(kwnames, i), args[i]) < 0) {
  3408. Py_DECREF(self);
  3409. return NULL;
  3410. }
  3411. }
  3412. }
  3413. return self;
  3414. }
  3415. static PyObject *
  3416. dict_iter(PyDictObject *dict)
  3417. {
  3418. return dictiter_new(dict, &PyDictIterKey_Type);
  3419. }
  3420. PyDoc_STRVAR(dictionary_doc,
  3421. "dict() -> new empty dictionary\n"
  3422. "dict(mapping) -> new dictionary initialized from a mapping object's\n"
  3423. " (key, value) pairs\n"
  3424. "dict(iterable) -> new dictionary initialized as if via:\n"
  3425. " d = {}\n"
  3426. " for k, v in iterable:\n"
  3427. " d[k] = v\n"
  3428. "dict(**kwargs) -> new dictionary initialized with the name=value pairs\n"
  3429. " in the keyword argument list. For example: dict(one=1, two=2)");
  3430. PyTypeObject PyDict_Type = {
  3431. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  3432. "dict",
  3433. sizeof(PyDictObject),
  3434. 0,
  3435. (destructor)dict_dealloc, /* tp_dealloc */
  3436. 0, /* tp_vectorcall_offset */
  3437. 0, /* tp_getattr */
  3438. 0, /* tp_setattr */
  3439. 0, /* tp_as_async */
  3440. (reprfunc)dict_repr, /* tp_repr */
  3441. &dict_as_number, /* tp_as_number */
  3442. &dict_as_sequence, /* tp_as_sequence */
  3443. &dict_as_mapping, /* tp_as_mapping */
  3444. PyObject_HashNotImplemented, /* tp_hash */
  3445. 0, /* tp_call */
  3446. 0, /* tp_str */
  3447. PyObject_GenericGetAttr, /* tp_getattro */
  3448. 0, /* tp_setattro */
  3449. 0, /* tp_as_buffer */
  3450. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  3451. Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS |
  3452. _Py_TPFLAGS_MATCH_SELF | Py_TPFLAGS_MAPPING, /* tp_flags */
  3453. dictionary_doc, /* tp_doc */
  3454. dict_traverse, /* tp_traverse */
  3455. dict_tp_clear, /* tp_clear */
  3456. dict_richcompare, /* tp_richcompare */
  3457. 0, /* tp_weaklistoffset */
  3458. (getiterfunc)dict_iter, /* tp_iter */
  3459. 0, /* tp_iternext */
  3460. mapp_methods, /* tp_methods */
  3461. 0, /* tp_members */
  3462. 0, /* tp_getset */
  3463. 0, /* tp_base */
  3464. 0, /* tp_dict */
  3465. 0, /* tp_descr_get */
  3466. 0, /* tp_descr_set */
  3467. 0, /* tp_dictoffset */
  3468. dict_init, /* tp_init */
  3469. _PyType_AllocNoTrack, /* tp_alloc */
  3470. dict_new, /* tp_new */
  3471. PyObject_GC_Del, /* tp_free */
  3472. .tp_vectorcall = dict_vectorcall,
  3473. };
  3474. /* For backward compatibility with old dictionary interface */
  3475. PyObject *
  3476. PyDict_GetItemString(PyObject *v, const char *key)
  3477. {
  3478. PyObject *kv, *rv;
  3479. kv = PyUnicode_FromString(key);
  3480. if (kv == NULL) {
  3481. PyErr_Clear();
  3482. return NULL;
  3483. }
  3484. rv = PyDict_GetItem(v, kv);
  3485. Py_DECREF(kv);
  3486. return rv;
  3487. }
  3488. int
  3489. _PyDict_SetItemId(PyObject *v, _Py_Identifier *key, PyObject *item)
  3490. {
  3491. PyObject *kv;
  3492. kv = _PyUnicode_FromId(key); /* borrowed */
  3493. if (kv == NULL)
  3494. return -1;
  3495. return PyDict_SetItem(v, kv, item);
  3496. }
  3497. int
  3498. PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
  3499. {
  3500. PyObject *kv;
  3501. int err;
  3502. kv = PyUnicode_FromString(key);
  3503. if (kv == NULL)
  3504. return -1;
  3505. PyUnicode_InternInPlace(&kv); /* XXX Should we really? */
  3506. err = PyDict_SetItem(v, kv, item);
  3507. Py_DECREF(kv);
  3508. return err;
  3509. }
  3510. int
  3511. _PyDict_DelItemId(PyObject *v, _Py_Identifier *key)
  3512. {
  3513. PyObject *kv = _PyUnicode_FromId(key); /* borrowed */
  3514. if (kv == NULL)
  3515. return -1;
  3516. return PyDict_DelItem(v, kv);
  3517. }
  3518. int
  3519. PyDict_DelItemString(PyObject *v, const char *key)
  3520. {
  3521. PyObject *kv;
  3522. int err;
  3523. kv = PyUnicode_FromString(key);
  3524. if (kv == NULL)
  3525. return -1;
  3526. err = PyDict_DelItem(v, kv);
  3527. Py_DECREF(kv);
  3528. return err;
  3529. }
  3530. /* Dictionary iterator types */
  3531. typedef struct {
  3532. PyObject_HEAD
  3533. PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
  3534. Py_ssize_t di_used;
  3535. Py_ssize_t di_pos;
  3536. PyObject* di_result; /* reusable result tuple for iteritems */
  3537. Py_ssize_t len;
  3538. } dictiterobject;
  3539. static PyObject *
  3540. dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
  3541. {
  3542. dictiterobject *di;
  3543. di = PyObject_GC_New(dictiterobject, itertype);
  3544. if (di == NULL) {
  3545. return NULL;
  3546. }
  3547. di->di_dict = (PyDictObject*)Py_NewRef(dict);
  3548. di->di_used = dict->ma_used;
  3549. di->len = dict->ma_used;
  3550. if (itertype == &PyDictRevIterKey_Type ||
  3551. itertype == &PyDictRevIterItem_Type ||
  3552. itertype == &PyDictRevIterValue_Type) {
  3553. if (dict->ma_values) {
  3554. di->di_pos = dict->ma_used - 1;
  3555. }
  3556. else {
  3557. di->di_pos = dict->ma_keys->dk_nentries - 1;
  3558. }
  3559. }
  3560. else {
  3561. di->di_pos = 0;
  3562. }
  3563. if (itertype == &PyDictIterItem_Type ||
  3564. itertype == &PyDictRevIterItem_Type) {
  3565. di->di_result = PyTuple_Pack(2, Py_None, Py_None);
  3566. if (di->di_result == NULL) {
  3567. Py_DECREF(di);
  3568. return NULL;
  3569. }
  3570. }
  3571. else {
  3572. di->di_result = NULL;
  3573. }
  3574. _PyObject_GC_TRACK(di);
  3575. return (PyObject *)di;
  3576. }
  3577. static void
  3578. dictiter_dealloc(dictiterobject *di)
  3579. {
  3580. /* bpo-31095: UnTrack is needed before calling any callbacks */
  3581. _PyObject_GC_UNTRACK(di);
  3582. Py_XDECREF(di->di_dict);
  3583. Py_XDECREF(di->di_result);
  3584. PyObject_GC_Del(di);
  3585. }
  3586. static int
  3587. dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
  3588. {
  3589. Py_VISIT(di->di_dict);
  3590. Py_VISIT(di->di_result);
  3591. return 0;
  3592. }
  3593. static PyObject *
  3594. dictiter_len(dictiterobject *di, PyObject *Py_UNUSED(ignored))
  3595. {
  3596. Py_ssize_t len = 0;
  3597. if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
  3598. len = di->len;
  3599. return PyLong_FromSize_t(len);
  3600. }
  3601. PyDoc_STRVAR(length_hint_doc,
  3602. "Private method returning an estimate of len(list(it)).");
  3603. static PyObject *
  3604. dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored));
  3605. PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
  3606. static PyMethodDef dictiter_methods[] = {
  3607. {"__length_hint__", _PyCFunction_CAST(dictiter_len), METH_NOARGS,
  3608. length_hint_doc},
  3609. {"__reduce__", _PyCFunction_CAST(dictiter_reduce), METH_NOARGS,
  3610. reduce_doc},
  3611. {NULL, NULL} /* sentinel */
  3612. };
  3613. static PyObject*
  3614. dictiter_iternextkey(dictiterobject *di)
  3615. {
  3616. PyObject *key;
  3617. Py_ssize_t i;
  3618. PyDictKeysObject *k;
  3619. PyDictObject *d = di->di_dict;
  3620. if (d == NULL)
  3621. return NULL;
  3622. assert (PyDict_Check(d));
  3623. if (di->di_used != d->ma_used) {
  3624. PyErr_SetString(PyExc_RuntimeError,
  3625. "dictionary changed size during iteration");
  3626. di->di_used = -1; /* Make this state sticky */
  3627. return NULL;
  3628. }
  3629. i = di->di_pos;
  3630. k = d->ma_keys;
  3631. assert(i >= 0);
  3632. if (d->ma_values) {
  3633. if (i >= d->ma_used)
  3634. goto fail;
  3635. int index = get_index_from_order(d, i);
  3636. key = DK_UNICODE_ENTRIES(k)[index].me_key;
  3637. assert(d->ma_values->values[index] != NULL);
  3638. }
  3639. else {
  3640. Py_ssize_t n = k->dk_nentries;
  3641. if (DK_IS_UNICODE(k)) {
  3642. PyDictUnicodeEntry *entry_ptr = &DK_UNICODE_ENTRIES(k)[i];
  3643. while (i < n && entry_ptr->me_value == NULL) {
  3644. entry_ptr++;
  3645. i++;
  3646. }
  3647. if (i >= n)
  3648. goto fail;
  3649. key = entry_ptr->me_key;
  3650. }
  3651. else {
  3652. PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
  3653. while (i < n && entry_ptr->me_value == NULL) {
  3654. entry_ptr++;
  3655. i++;
  3656. }
  3657. if (i >= n)
  3658. goto fail;
  3659. key = entry_ptr->me_key;
  3660. }
  3661. }
  3662. // We found an element (key), but did not expect it
  3663. if (di->len == 0) {
  3664. PyErr_SetString(PyExc_RuntimeError,
  3665. "dictionary keys changed during iteration");
  3666. goto fail;
  3667. }
  3668. di->di_pos = i+1;
  3669. di->len--;
  3670. return Py_NewRef(key);
  3671. fail:
  3672. di->di_dict = NULL;
  3673. Py_DECREF(d);
  3674. return NULL;
  3675. }
  3676. PyTypeObject PyDictIterKey_Type = {
  3677. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  3678. "dict_keyiterator", /* tp_name */
  3679. sizeof(dictiterobject), /* tp_basicsize */
  3680. 0, /* tp_itemsize */
  3681. /* methods */
  3682. (destructor)dictiter_dealloc, /* tp_dealloc */
  3683. 0, /* tp_vectorcall_offset */
  3684. 0, /* tp_getattr */
  3685. 0, /* tp_setattr */
  3686. 0, /* tp_as_async */
  3687. 0, /* tp_repr */
  3688. 0, /* tp_as_number */
  3689. 0, /* tp_as_sequence */
  3690. 0, /* tp_as_mapping */
  3691. 0, /* tp_hash */
  3692. 0, /* tp_call */
  3693. 0, /* tp_str */
  3694. PyObject_GenericGetAttr, /* tp_getattro */
  3695. 0, /* tp_setattro */
  3696. 0, /* tp_as_buffer */
  3697. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  3698. 0, /* tp_doc */
  3699. (traverseproc)dictiter_traverse, /* tp_traverse */
  3700. 0, /* tp_clear */
  3701. 0, /* tp_richcompare */
  3702. 0, /* tp_weaklistoffset */
  3703. PyObject_SelfIter, /* tp_iter */
  3704. (iternextfunc)dictiter_iternextkey, /* tp_iternext */
  3705. dictiter_methods, /* tp_methods */
  3706. 0,
  3707. };
  3708. static PyObject *
  3709. dictiter_iternextvalue(dictiterobject *di)
  3710. {
  3711. PyObject *value;
  3712. Py_ssize_t i;
  3713. PyDictObject *d = di->di_dict;
  3714. if (d == NULL)
  3715. return NULL;
  3716. assert (PyDict_Check(d));
  3717. if (di->di_used != d->ma_used) {
  3718. PyErr_SetString(PyExc_RuntimeError,
  3719. "dictionary changed size during iteration");
  3720. di->di_used = -1; /* Make this state sticky */
  3721. return NULL;
  3722. }
  3723. i = di->di_pos;
  3724. assert(i >= 0);
  3725. if (d->ma_values) {
  3726. if (i >= d->ma_used)
  3727. goto fail;
  3728. int index = get_index_from_order(d, i);
  3729. value = d->ma_values->values[index];
  3730. assert(value != NULL);
  3731. }
  3732. else {
  3733. Py_ssize_t n = d->ma_keys->dk_nentries;
  3734. if (DK_IS_UNICODE(d->ma_keys)) {
  3735. PyDictUnicodeEntry *entry_ptr = &DK_UNICODE_ENTRIES(d->ma_keys)[i];
  3736. while (i < n && entry_ptr->me_value == NULL) {
  3737. entry_ptr++;
  3738. i++;
  3739. }
  3740. if (i >= n)
  3741. goto fail;
  3742. value = entry_ptr->me_value;
  3743. }
  3744. else {
  3745. PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
  3746. while (i < n && entry_ptr->me_value == NULL) {
  3747. entry_ptr++;
  3748. i++;
  3749. }
  3750. if (i >= n)
  3751. goto fail;
  3752. value = entry_ptr->me_value;
  3753. }
  3754. }
  3755. // We found an element, but did not expect it
  3756. if (di->len == 0) {
  3757. PyErr_SetString(PyExc_RuntimeError,
  3758. "dictionary keys changed during iteration");
  3759. goto fail;
  3760. }
  3761. di->di_pos = i+1;
  3762. di->len--;
  3763. return Py_NewRef(value);
  3764. fail:
  3765. di->di_dict = NULL;
  3766. Py_DECREF(d);
  3767. return NULL;
  3768. }
  3769. PyTypeObject PyDictIterValue_Type = {
  3770. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  3771. "dict_valueiterator", /* tp_name */
  3772. sizeof(dictiterobject), /* tp_basicsize */
  3773. 0, /* tp_itemsize */
  3774. /* methods */
  3775. (destructor)dictiter_dealloc, /* tp_dealloc */
  3776. 0, /* tp_vectorcall_offset */
  3777. 0, /* tp_getattr */
  3778. 0, /* tp_setattr */
  3779. 0, /* tp_as_async */
  3780. 0, /* tp_repr */
  3781. 0, /* tp_as_number */
  3782. 0, /* tp_as_sequence */
  3783. 0, /* tp_as_mapping */
  3784. 0, /* tp_hash */
  3785. 0, /* tp_call */
  3786. 0, /* tp_str */
  3787. PyObject_GenericGetAttr, /* tp_getattro */
  3788. 0, /* tp_setattro */
  3789. 0, /* tp_as_buffer */
  3790. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
  3791. 0, /* tp_doc */
  3792. (traverseproc)dictiter_traverse, /* tp_traverse */
  3793. 0, /* tp_clear */
  3794. 0, /* tp_richcompare */
  3795. 0, /* tp_weaklistoffset */
  3796. PyObject_SelfIter, /* tp_iter */
  3797. (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
  3798. dictiter_methods, /* tp_methods */
  3799. 0,
  3800. };
  3801. static PyObject *
  3802. dictiter_iternextitem(dictiterobject *di)
  3803. {
  3804. PyObject *key, *value, *result;
  3805. Py_ssize_t i;
  3806. PyDictObject *d = di->di_dict;
  3807. if (d == NULL)
  3808. return NULL;
  3809. assert (PyDict_Check(d));
  3810. if (di->di_used != d->ma_used) {
  3811. PyErr_SetString(PyExc_RuntimeError,
  3812. "dictionary changed size during iteration");
  3813. di->di_used = -1; /* Make this state sticky */
  3814. return NULL;
  3815. }
  3816. i = di->di_pos;
  3817. assert(i >= 0);
  3818. if (d->ma_values) {
  3819. if (i >= d->ma_used)
  3820. goto fail;
  3821. int index = get_index_from_order(d, i);
  3822. key = DK_UNICODE_ENTRIES(d->ma_keys)[index].me_key;
  3823. value = d->ma_values->values[index];
  3824. assert(value != NULL);
  3825. }
  3826. else {
  3827. Py_ssize_t n = d->ma_keys->dk_nentries;
  3828. if (DK_IS_UNICODE(d->ma_keys)) {
  3829. PyDictUnicodeEntry *entry_ptr = &DK_UNICODE_ENTRIES(d->ma_keys)[i];
  3830. while (i < n && entry_ptr->me_value == NULL) {
  3831. entry_ptr++;
  3832. i++;
  3833. }
  3834. if (i >= n)
  3835. goto fail;
  3836. key = entry_ptr->me_key;
  3837. value = entry_ptr->me_value;
  3838. }
  3839. else {
  3840. PyDictKeyEntry *entry_ptr = &DK_ENTRIES(d->ma_keys)[i];
  3841. while (i < n && entry_ptr->me_value == NULL) {
  3842. entry_ptr++;
  3843. i++;
  3844. }
  3845. if (i >= n)
  3846. goto fail;
  3847. key = entry_ptr->me_key;
  3848. value = entry_ptr->me_value;
  3849. }
  3850. }
  3851. // We found an element, but did not expect it
  3852. if (di->len == 0) {
  3853. PyErr_SetString(PyExc_RuntimeError,
  3854. "dictionary keys changed during iteration");
  3855. goto fail;
  3856. }
  3857. di->di_pos = i+1;
  3858. di->len--;
  3859. result = di->di_result;
  3860. if (Py_REFCNT(result) == 1) {
  3861. PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
  3862. PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
  3863. PyTuple_SET_ITEM(result, 0, Py_NewRef(key));
  3864. PyTuple_SET_ITEM(result, 1, Py_NewRef(value));
  3865. Py_INCREF(result);
  3866. Py_DECREF(oldkey);
  3867. Py_DECREF(oldvalue);
  3868. // bpo-42536: The GC may have untracked this result tuple. Since we're
  3869. // recycling it, make sure it's tracked again:
  3870. if (!_PyObject_GC_IS_TRACKED(result)) {
  3871. _PyObject_GC_TRACK(result);
  3872. }
  3873. }
  3874. else {
  3875. result = PyTuple_New(2);
  3876. if (result == NULL)
  3877. return NULL;
  3878. PyTuple_SET_ITEM(result, 0, Py_NewRef(key));
  3879. PyTuple_SET_ITEM(result, 1, Py_NewRef(value));
  3880. }
  3881. return result;
  3882. fail:
  3883. di->di_dict = NULL;
  3884. Py_DECREF(d);
  3885. return NULL;
  3886. }
  3887. PyTypeObject PyDictIterItem_Type = {
  3888. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  3889. "dict_itemiterator", /* tp_name */
  3890. sizeof(dictiterobject), /* tp_basicsize */
  3891. 0, /* tp_itemsize */
  3892. /* methods */
  3893. (destructor)dictiter_dealloc, /* tp_dealloc */
  3894. 0, /* tp_vectorcall_offset */
  3895. 0, /* tp_getattr */
  3896. 0, /* tp_setattr */
  3897. 0, /* tp_as_async */
  3898. 0, /* tp_repr */
  3899. 0, /* tp_as_number */
  3900. 0, /* tp_as_sequence */
  3901. 0, /* tp_as_mapping */
  3902. 0, /* tp_hash */
  3903. 0, /* tp_call */
  3904. 0, /* tp_str */
  3905. PyObject_GenericGetAttr, /* tp_getattro */
  3906. 0, /* tp_setattro */
  3907. 0, /* tp_as_buffer */
  3908. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  3909. 0, /* tp_doc */
  3910. (traverseproc)dictiter_traverse, /* tp_traverse */
  3911. 0, /* tp_clear */
  3912. 0, /* tp_richcompare */
  3913. 0, /* tp_weaklistoffset */
  3914. PyObject_SelfIter, /* tp_iter */
  3915. (iternextfunc)dictiter_iternextitem, /* tp_iternext */
  3916. dictiter_methods, /* tp_methods */
  3917. 0,
  3918. };
  3919. /* dictreviter */
  3920. static PyObject *
  3921. dictreviter_iternext(dictiterobject *di)
  3922. {
  3923. PyDictObject *d = di->di_dict;
  3924. if (d == NULL) {
  3925. return NULL;
  3926. }
  3927. assert (PyDict_Check(d));
  3928. if (di->di_used != d->ma_used) {
  3929. PyErr_SetString(PyExc_RuntimeError,
  3930. "dictionary changed size during iteration");
  3931. di->di_used = -1; /* Make this state sticky */
  3932. return NULL;
  3933. }
  3934. Py_ssize_t i = di->di_pos;
  3935. PyDictKeysObject *k = d->ma_keys;
  3936. PyObject *key, *value, *result;
  3937. if (i < 0) {
  3938. goto fail;
  3939. }
  3940. if (d->ma_values) {
  3941. int index = get_index_from_order(d, i);
  3942. key = DK_UNICODE_ENTRIES(k)[index].me_key;
  3943. value = d->ma_values->values[index];
  3944. assert (value != NULL);
  3945. }
  3946. else {
  3947. if (DK_IS_UNICODE(k)) {
  3948. PyDictUnicodeEntry *entry_ptr = &DK_UNICODE_ENTRIES(k)[i];
  3949. while (entry_ptr->me_value == NULL) {
  3950. if (--i < 0) {
  3951. goto fail;
  3952. }
  3953. entry_ptr--;
  3954. }
  3955. key = entry_ptr->me_key;
  3956. value = entry_ptr->me_value;
  3957. }
  3958. else {
  3959. PyDictKeyEntry *entry_ptr = &DK_ENTRIES(k)[i];
  3960. while (entry_ptr->me_value == NULL) {
  3961. if (--i < 0) {
  3962. goto fail;
  3963. }
  3964. entry_ptr--;
  3965. }
  3966. key = entry_ptr->me_key;
  3967. value = entry_ptr->me_value;
  3968. }
  3969. }
  3970. di->di_pos = i-1;
  3971. di->len--;
  3972. if (Py_IS_TYPE(di, &PyDictRevIterKey_Type)) {
  3973. return Py_NewRef(key);
  3974. }
  3975. else if (Py_IS_TYPE(di, &PyDictRevIterValue_Type)) {
  3976. return Py_NewRef(value);
  3977. }
  3978. else if (Py_IS_TYPE(di, &PyDictRevIterItem_Type)) {
  3979. result = di->di_result;
  3980. if (Py_REFCNT(result) == 1) {
  3981. PyObject *oldkey = PyTuple_GET_ITEM(result, 0);
  3982. PyObject *oldvalue = PyTuple_GET_ITEM(result, 1);
  3983. PyTuple_SET_ITEM(result, 0, Py_NewRef(key));
  3984. PyTuple_SET_ITEM(result, 1, Py_NewRef(value));
  3985. Py_INCREF(result);
  3986. Py_DECREF(oldkey);
  3987. Py_DECREF(oldvalue);
  3988. // bpo-42536: The GC may have untracked this result tuple. Since
  3989. // we're recycling it, make sure it's tracked again:
  3990. if (!_PyObject_GC_IS_TRACKED(result)) {
  3991. _PyObject_GC_TRACK(result);
  3992. }
  3993. }
  3994. else {
  3995. result = PyTuple_New(2);
  3996. if (result == NULL) {
  3997. return NULL;
  3998. }
  3999. PyTuple_SET_ITEM(result, 0, Py_NewRef(key));
  4000. PyTuple_SET_ITEM(result, 1, Py_NewRef(value));
  4001. }
  4002. return result;
  4003. }
  4004. else {
  4005. Py_UNREACHABLE();
  4006. }
  4007. fail:
  4008. di->di_dict = NULL;
  4009. Py_DECREF(d);
  4010. return NULL;
  4011. }
  4012. PyTypeObject PyDictRevIterKey_Type = {
  4013. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  4014. "dict_reversekeyiterator",
  4015. sizeof(dictiterobject),
  4016. .tp_dealloc = (destructor)dictiter_dealloc,
  4017. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  4018. .tp_traverse = (traverseproc)dictiter_traverse,
  4019. .tp_iter = PyObject_SelfIter,
  4020. .tp_iternext = (iternextfunc)dictreviter_iternext,
  4021. .tp_methods = dictiter_methods
  4022. };
  4023. /*[clinic input]
  4024. dict.__reversed__
  4025. Return a reverse iterator over the dict keys.
  4026. [clinic start generated code]*/
  4027. static PyObject *
  4028. dict___reversed___impl(PyDictObject *self)
  4029. /*[clinic end generated code: output=e674483336d1ed51 input=23210ef3477d8c4d]*/
  4030. {
  4031. assert (PyDict_Check(self));
  4032. return dictiter_new(self, &PyDictRevIterKey_Type);
  4033. }
  4034. static PyObject *
  4035. dictiter_reduce(dictiterobject *di, PyObject *Py_UNUSED(ignored))
  4036. {
  4037. /* copy the iterator state */
  4038. dictiterobject tmp = *di;
  4039. Py_XINCREF(tmp.di_dict);
  4040. PyObject *list = PySequence_List((PyObject*)&tmp);
  4041. Py_XDECREF(tmp.di_dict);
  4042. if (list == NULL) {
  4043. return NULL;
  4044. }
  4045. return Py_BuildValue("N(N)", _PyEval_GetBuiltin(&_Py_ID(iter)), list);
  4046. }
  4047. PyTypeObject PyDictRevIterItem_Type = {
  4048. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  4049. "dict_reverseitemiterator",
  4050. sizeof(dictiterobject),
  4051. .tp_dealloc = (destructor)dictiter_dealloc,
  4052. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  4053. .tp_traverse = (traverseproc)dictiter_traverse,
  4054. .tp_iter = PyObject_SelfIter,
  4055. .tp_iternext = (iternextfunc)dictreviter_iternext,
  4056. .tp_methods = dictiter_methods
  4057. };
  4058. PyTypeObject PyDictRevIterValue_Type = {
  4059. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  4060. "dict_reversevalueiterator",
  4061. sizeof(dictiterobject),
  4062. .tp_dealloc = (destructor)dictiter_dealloc,
  4063. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  4064. .tp_traverse = (traverseproc)dictiter_traverse,
  4065. .tp_iter = PyObject_SelfIter,
  4066. .tp_iternext = (iternextfunc)dictreviter_iternext,
  4067. .tp_methods = dictiter_methods
  4068. };
  4069. /***********************************************/
  4070. /* View objects for keys(), items(), values(). */
  4071. /***********************************************/
  4072. /* The instance lay-out is the same for all three; but the type differs. */
  4073. static void
  4074. dictview_dealloc(_PyDictViewObject *dv)
  4075. {
  4076. /* bpo-31095: UnTrack is needed before calling any callbacks */
  4077. _PyObject_GC_UNTRACK(dv);
  4078. Py_XDECREF(dv->dv_dict);
  4079. PyObject_GC_Del(dv);
  4080. }
  4081. static int
  4082. dictview_traverse(_PyDictViewObject *dv, visitproc visit, void *arg)
  4083. {
  4084. Py_VISIT(dv->dv_dict);
  4085. return 0;
  4086. }
  4087. static Py_ssize_t
  4088. dictview_len(_PyDictViewObject *dv)
  4089. {
  4090. Py_ssize_t len = 0;
  4091. if (dv->dv_dict != NULL)
  4092. len = dv->dv_dict->ma_used;
  4093. return len;
  4094. }
  4095. PyObject *
  4096. _PyDictView_New(PyObject *dict, PyTypeObject *type)
  4097. {
  4098. _PyDictViewObject *dv;
  4099. if (dict == NULL) {
  4100. PyErr_BadInternalCall();
  4101. return NULL;
  4102. }
  4103. if (!PyDict_Check(dict)) {
  4104. /* XXX Get rid of this restriction later */
  4105. PyErr_Format(PyExc_TypeError,
  4106. "%s() requires a dict argument, not '%s'",
  4107. type->tp_name, Py_TYPE(dict)->tp_name);
  4108. return NULL;
  4109. }
  4110. dv = PyObject_GC_New(_PyDictViewObject, type);
  4111. if (dv == NULL)
  4112. return NULL;
  4113. dv->dv_dict = (PyDictObject *)Py_NewRef(dict);
  4114. _PyObject_GC_TRACK(dv);
  4115. return (PyObject *)dv;
  4116. }
  4117. static PyObject *
  4118. dictview_mapping(PyObject *view, void *Py_UNUSED(ignored)) {
  4119. assert(view != NULL);
  4120. assert(PyDictKeys_Check(view)
  4121. || PyDictValues_Check(view)
  4122. || PyDictItems_Check(view));
  4123. PyObject *mapping = (PyObject *)((_PyDictViewObject *)view)->dv_dict;
  4124. return PyDictProxy_New(mapping);
  4125. }
  4126. static PyGetSetDef dictview_getset[] = {
  4127. {"mapping", dictview_mapping, (setter)NULL,
  4128. "dictionary that this view refers to", NULL},
  4129. {0}
  4130. };
  4131. /* TODO(guido): The views objects are not complete:
  4132. * support more set operations
  4133. * support arbitrary mappings?
  4134. - either these should be static or exported in dictobject.h
  4135. - if public then they should probably be in builtins
  4136. */
  4137. /* Return 1 if self is a subset of other, iterating over self;
  4138. 0 if not; -1 if an error occurred. */
  4139. static int
  4140. all_contained_in(PyObject *self, PyObject *other)
  4141. {
  4142. PyObject *iter = PyObject_GetIter(self);
  4143. int ok = 1;
  4144. if (iter == NULL)
  4145. return -1;
  4146. for (;;) {
  4147. PyObject *next = PyIter_Next(iter);
  4148. if (next == NULL) {
  4149. if (PyErr_Occurred())
  4150. ok = -1;
  4151. break;
  4152. }
  4153. ok = PySequence_Contains(other, next);
  4154. Py_DECREF(next);
  4155. if (ok <= 0)
  4156. break;
  4157. }
  4158. Py_DECREF(iter);
  4159. return ok;
  4160. }
  4161. static PyObject *
  4162. dictview_richcompare(PyObject *self, PyObject *other, int op)
  4163. {
  4164. Py_ssize_t len_self, len_other;
  4165. int ok;
  4166. PyObject *result;
  4167. assert(self != NULL);
  4168. assert(PyDictViewSet_Check(self));
  4169. assert(other != NULL);
  4170. if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other))
  4171. Py_RETURN_NOTIMPLEMENTED;
  4172. len_self = PyObject_Size(self);
  4173. if (len_self < 0)
  4174. return NULL;
  4175. len_other = PyObject_Size(other);
  4176. if (len_other < 0)
  4177. return NULL;
  4178. ok = 0;
  4179. switch(op) {
  4180. case Py_NE:
  4181. case Py_EQ:
  4182. if (len_self == len_other)
  4183. ok = all_contained_in(self, other);
  4184. if (op == Py_NE && ok >= 0)
  4185. ok = !ok;
  4186. break;
  4187. case Py_LT:
  4188. if (len_self < len_other)
  4189. ok = all_contained_in(self, other);
  4190. break;
  4191. case Py_LE:
  4192. if (len_self <= len_other)
  4193. ok = all_contained_in(self, other);
  4194. break;
  4195. case Py_GT:
  4196. if (len_self > len_other)
  4197. ok = all_contained_in(other, self);
  4198. break;
  4199. case Py_GE:
  4200. if (len_self >= len_other)
  4201. ok = all_contained_in(other, self);
  4202. break;
  4203. }
  4204. if (ok < 0)
  4205. return NULL;
  4206. result = ok ? Py_True : Py_False;
  4207. return Py_NewRef(result);
  4208. }
  4209. static PyObject *
  4210. dictview_repr(_PyDictViewObject *dv)
  4211. {
  4212. PyObject *seq;
  4213. PyObject *result = NULL;
  4214. Py_ssize_t rc;
  4215. rc = Py_ReprEnter((PyObject *)dv);
  4216. if (rc != 0) {
  4217. return rc > 0 ? PyUnicode_FromString("...") : NULL;
  4218. }
  4219. seq = PySequence_List((PyObject *)dv);
  4220. if (seq == NULL) {
  4221. goto Done;
  4222. }
  4223. result = PyUnicode_FromFormat("%s(%R)", Py_TYPE(dv)->tp_name, seq);
  4224. Py_DECREF(seq);
  4225. Done:
  4226. Py_ReprLeave((PyObject *)dv);
  4227. return result;
  4228. }
  4229. /*** dict_keys ***/
  4230. static PyObject *
  4231. dictkeys_iter(_PyDictViewObject *dv)
  4232. {
  4233. if (dv->dv_dict == NULL) {
  4234. Py_RETURN_NONE;
  4235. }
  4236. return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
  4237. }
  4238. static int
  4239. dictkeys_contains(_PyDictViewObject *dv, PyObject *obj)
  4240. {
  4241. if (dv->dv_dict == NULL)
  4242. return 0;
  4243. return PyDict_Contains((PyObject *)dv->dv_dict, obj);
  4244. }
  4245. static PySequenceMethods dictkeys_as_sequence = {
  4246. (lenfunc)dictview_len, /* sq_length */
  4247. 0, /* sq_concat */
  4248. 0, /* sq_repeat */
  4249. 0, /* sq_item */
  4250. 0, /* sq_slice */
  4251. 0, /* sq_ass_item */
  4252. 0, /* sq_ass_slice */
  4253. (objobjproc)dictkeys_contains, /* sq_contains */
  4254. };
  4255. // Create a set object from dictviews object.
  4256. // Returns a new reference.
  4257. // This utility function is used by set operations.
  4258. static PyObject*
  4259. dictviews_to_set(PyObject *self)
  4260. {
  4261. PyObject *left = self;
  4262. if (PyDictKeys_Check(self)) {
  4263. // PySet_New() has fast path for the dict object.
  4264. PyObject *dict = (PyObject *)((_PyDictViewObject *)self)->dv_dict;
  4265. if (PyDict_CheckExact(dict)) {
  4266. left = dict;
  4267. }
  4268. }
  4269. return PySet_New(left);
  4270. }
  4271. static PyObject*
  4272. dictviews_sub(PyObject *self, PyObject *other)
  4273. {
  4274. PyObject *result = dictviews_to_set(self);
  4275. if (result == NULL) {
  4276. return NULL;
  4277. }
  4278. PyObject *tmp = PyObject_CallMethodOneArg(
  4279. result, &_Py_ID(difference_update), other);
  4280. if (tmp == NULL) {
  4281. Py_DECREF(result);
  4282. return NULL;
  4283. }
  4284. Py_DECREF(tmp);
  4285. return result;
  4286. }
  4287. static int
  4288. dictitems_contains(_PyDictViewObject *dv, PyObject *obj);
  4289. PyObject *
  4290. _PyDictView_Intersect(PyObject* self, PyObject *other)
  4291. {
  4292. PyObject *result;
  4293. PyObject *it;
  4294. PyObject *key;
  4295. Py_ssize_t len_self;
  4296. int rv;
  4297. int (*dict_contains)(_PyDictViewObject *, PyObject *);
  4298. /* Python interpreter swaps parameters when dict view
  4299. is on right side of & */
  4300. if (!PyDictViewSet_Check(self)) {
  4301. PyObject *tmp = other;
  4302. other = self;
  4303. self = tmp;
  4304. }
  4305. len_self = dictview_len((_PyDictViewObject *)self);
  4306. /* if other is a set and self is smaller than other,
  4307. reuse set intersection logic */
  4308. if (PySet_CheckExact(other) && len_self <= PyObject_Size(other)) {
  4309. return PyObject_CallMethodObjArgs(
  4310. other, &_Py_ID(intersection), self, NULL);
  4311. }
  4312. /* if other is another dict view, and it is bigger than self,
  4313. swap them */
  4314. if (PyDictViewSet_Check(other)) {
  4315. Py_ssize_t len_other = dictview_len((_PyDictViewObject *)other);
  4316. if (len_other > len_self) {
  4317. PyObject *tmp = other;
  4318. other = self;
  4319. self = tmp;
  4320. }
  4321. }
  4322. /* at this point, two things should be true
  4323. 1. self is a dictview
  4324. 2. if other is a dictview then it is smaller than self */
  4325. result = PySet_New(NULL);
  4326. if (result == NULL)
  4327. return NULL;
  4328. it = PyObject_GetIter(other);
  4329. if (it == NULL) {
  4330. Py_DECREF(result);
  4331. return NULL;
  4332. }
  4333. if (PyDictKeys_Check(self)) {
  4334. dict_contains = dictkeys_contains;
  4335. }
  4336. /* else PyDictItems_Check(self) */
  4337. else {
  4338. dict_contains = dictitems_contains;
  4339. }
  4340. while ((key = PyIter_Next(it)) != NULL) {
  4341. rv = dict_contains((_PyDictViewObject *)self, key);
  4342. if (rv < 0) {
  4343. goto error;
  4344. }
  4345. if (rv) {
  4346. if (PySet_Add(result, key)) {
  4347. goto error;
  4348. }
  4349. }
  4350. Py_DECREF(key);
  4351. }
  4352. Py_DECREF(it);
  4353. if (PyErr_Occurred()) {
  4354. Py_DECREF(result);
  4355. return NULL;
  4356. }
  4357. return result;
  4358. error:
  4359. Py_DECREF(it);
  4360. Py_DECREF(result);
  4361. Py_DECREF(key);
  4362. return NULL;
  4363. }
  4364. static PyObject*
  4365. dictviews_or(PyObject* self, PyObject *other)
  4366. {
  4367. PyObject *result = dictviews_to_set(self);
  4368. if (result == NULL) {
  4369. return NULL;
  4370. }
  4371. if (_PySet_Update(result, other) < 0) {
  4372. Py_DECREF(result);
  4373. return NULL;
  4374. }
  4375. return result;
  4376. }
  4377. static PyObject *
  4378. dictitems_xor(PyObject *self, PyObject *other)
  4379. {
  4380. assert(PyDictItems_Check(self));
  4381. assert(PyDictItems_Check(other));
  4382. PyObject *d1 = (PyObject *)((_PyDictViewObject *)self)->dv_dict;
  4383. PyObject *d2 = (PyObject *)((_PyDictViewObject *)other)->dv_dict;
  4384. PyObject *temp_dict = PyDict_Copy(d1);
  4385. if (temp_dict == NULL) {
  4386. return NULL;
  4387. }
  4388. PyObject *result_set = PySet_New(NULL);
  4389. if (result_set == NULL) {
  4390. Py_CLEAR(temp_dict);
  4391. return NULL;
  4392. }
  4393. PyObject *key = NULL, *val1 = NULL, *val2 = NULL;
  4394. Py_ssize_t pos = 0;
  4395. Py_hash_t hash;
  4396. while (_PyDict_Next(d2, &pos, &key, &val2, &hash)) {
  4397. Py_INCREF(key);
  4398. Py_INCREF(val2);
  4399. val1 = _PyDict_GetItem_KnownHash(temp_dict, key, hash);
  4400. int to_delete;
  4401. if (val1 == NULL) {
  4402. if (PyErr_Occurred()) {
  4403. goto error;
  4404. }
  4405. to_delete = 0;
  4406. }
  4407. else {
  4408. Py_INCREF(val1);
  4409. to_delete = PyObject_RichCompareBool(val1, val2, Py_EQ);
  4410. if (to_delete < 0) {
  4411. goto error;
  4412. }
  4413. }
  4414. if (to_delete) {
  4415. if (_PyDict_DelItem_KnownHash(temp_dict, key, hash) < 0) {
  4416. goto error;
  4417. }
  4418. }
  4419. else {
  4420. PyObject *pair = PyTuple_Pack(2, key, val2);
  4421. if (pair == NULL) {
  4422. goto error;
  4423. }
  4424. if (PySet_Add(result_set, pair) < 0) {
  4425. Py_DECREF(pair);
  4426. goto error;
  4427. }
  4428. Py_DECREF(pair);
  4429. }
  4430. Py_DECREF(key);
  4431. Py_XDECREF(val1);
  4432. Py_DECREF(val2);
  4433. }
  4434. key = val1 = val2 = NULL;
  4435. PyObject *remaining_pairs = PyObject_CallMethodNoArgs(
  4436. temp_dict, &_Py_ID(items));
  4437. if (remaining_pairs == NULL) {
  4438. goto error;
  4439. }
  4440. if (_PySet_Update(result_set, remaining_pairs) < 0) {
  4441. Py_DECREF(remaining_pairs);
  4442. goto error;
  4443. }
  4444. Py_DECREF(temp_dict);
  4445. Py_DECREF(remaining_pairs);
  4446. return result_set;
  4447. error:
  4448. Py_XDECREF(temp_dict);
  4449. Py_XDECREF(result_set);
  4450. Py_XDECREF(key);
  4451. Py_XDECREF(val1);
  4452. Py_XDECREF(val2);
  4453. return NULL;
  4454. }
  4455. static PyObject*
  4456. dictviews_xor(PyObject* self, PyObject *other)
  4457. {
  4458. if (PyDictItems_Check(self) && PyDictItems_Check(other)) {
  4459. return dictitems_xor(self, other);
  4460. }
  4461. PyObject *result = dictviews_to_set(self);
  4462. if (result == NULL) {
  4463. return NULL;
  4464. }
  4465. PyObject *tmp = PyObject_CallMethodOneArg(
  4466. result, &_Py_ID(symmetric_difference_update), other);
  4467. if (tmp == NULL) {
  4468. Py_DECREF(result);
  4469. return NULL;
  4470. }
  4471. Py_DECREF(tmp);
  4472. return result;
  4473. }
  4474. static PyNumberMethods dictviews_as_number = {
  4475. 0, /*nb_add*/
  4476. (binaryfunc)dictviews_sub, /*nb_subtract*/
  4477. 0, /*nb_multiply*/
  4478. 0, /*nb_remainder*/
  4479. 0, /*nb_divmod*/
  4480. 0, /*nb_power*/
  4481. 0, /*nb_negative*/
  4482. 0, /*nb_positive*/
  4483. 0, /*nb_absolute*/
  4484. 0, /*nb_bool*/
  4485. 0, /*nb_invert*/
  4486. 0, /*nb_lshift*/
  4487. 0, /*nb_rshift*/
  4488. (binaryfunc)_PyDictView_Intersect, /*nb_and*/
  4489. (binaryfunc)dictviews_xor, /*nb_xor*/
  4490. (binaryfunc)dictviews_or, /*nb_or*/
  4491. };
  4492. static PyObject*
  4493. dictviews_isdisjoint(PyObject *self, PyObject *other)
  4494. {
  4495. PyObject *it;
  4496. PyObject *item = NULL;
  4497. if (self == other) {
  4498. if (dictview_len((_PyDictViewObject *)self) == 0)
  4499. Py_RETURN_TRUE;
  4500. else
  4501. Py_RETURN_FALSE;
  4502. }
  4503. /* Iterate over the shorter object (only if other is a set,
  4504. * because PySequence_Contains may be expensive otherwise): */
  4505. if (PyAnySet_Check(other) || PyDictViewSet_Check(other)) {
  4506. Py_ssize_t len_self = dictview_len((_PyDictViewObject *)self);
  4507. Py_ssize_t len_other = PyObject_Size(other);
  4508. if (len_other == -1)
  4509. return NULL;
  4510. if ((len_other > len_self)) {
  4511. PyObject *tmp = other;
  4512. other = self;
  4513. self = tmp;
  4514. }
  4515. }
  4516. it = PyObject_GetIter(other);
  4517. if (it == NULL)
  4518. return NULL;
  4519. while ((item = PyIter_Next(it)) != NULL) {
  4520. int contains = PySequence_Contains(self, item);
  4521. Py_DECREF(item);
  4522. if (contains == -1) {
  4523. Py_DECREF(it);
  4524. return NULL;
  4525. }
  4526. if (contains) {
  4527. Py_DECREF(it);
  4528. Py_RETURN_FALSE;
  4529. }
  4530. }
  4531. Py_DECREF(it);
  4532. if (PyErr_Occurred())
  4533. return NULL; /* PyIter_Next raised an exception. */
  4534. Py_RETURN_TRUE;
  4535. }
  4536. PyDoc_STRVAR(isdisjoint_doc,
  4537. "Return True if the view and the given iterable have a null intersection.");
  4538. static PyObject* dictkeys_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored));
  4539. PyDoc_STRVAR(reversed_keys_doc,
  4540. "Return a reverse iterator over the dict keys.");
  4541. static PyMethodDef dictkeys_methods[] = {
  4542. {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
  4543. isdisjoint_doc},
  4544. {"__reversed__", _PyCFunction_CAST(dictkeys_reversed), METH_NOARGS,
  4545. reversed_keys_doc},
  4546. {NULL, NULL} /* sentinel */
  4547. };
  4548. PyTypeObject PyDictKeys_Type = {
  4549. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  4550. "dict_keys", /* tp_name */
  4551. sizeof(_PyDictViewObject), /* tp_basicsize */
  4552. 0, /* tp_itemsize */
  4553. /* methods */
  4554. (destructor)dictview_dealloc, /* tp_dealloc */
  4555. 0, /* tp_vectorcall_offset */
  4556. 0, /* tp_getattr */
  4557. 0, /* tp_setattr */
  4558. 0, /* tp_as_async */
  4559. (reprfunc)dictview_repr, /* tp_repr */
  4560. &dictviews_as_number, /* tp_as_number */
  4561. &dictkeys_as_sequence, /* tp_as_sequence */
  4562. 0, /* tp_as_mapping */
  4563. 0, /* tp_hash */
  4564. 0, /* tp_call */
  4565. 0, /* tp_str */
  4566. PyObject_GenericGetAttr, /* tp_getattro */
  4567. 0, /* tp_setattro */
  4568. 0, /* tp_as_buffer */
  4569. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  4570. 0, /* tp_doc */
  4571. (traverseproc)dictview_traverse, /* tp_traverse */
  4572. 0, /* tp_clear */
  4573. dictview_richcompare, /* tp_richcompare */
  4574. 0, /* tp_weaklistoffset */
  4575. (getiterfunc)dictkeys_iter, /* tp_iter */
  4576. 0, /* tp_iternext */
  4577. dictkeys_methods, /* tp_methods */
  4578. .tp_getset = dictview_getset,
  4579. };
  4580. static PyObject *
  4581. dictkeys_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
  4582. {
  4583. return _PyDictView_New(dict, &PyDictKeys_Type);
  4584. }
  4585. static PyObject *
  4586. dictkeys_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored))
  4587. {
  4588. if (dv->dv_dict == NULL) {
  4589. Py_RETURN_NONE;
  4590. }
  4591. return dictiter_new(dv->dv_dict, &PyDictRevIterKey_Type);
  4592. }
  4593. /*** dict_items ***/
  4594. static PyObject *
  4595. dictitems_iter(_PyDictViewObject *dv)
  4596. {
  4597. if (dv->dv_dict == NULL) {
  4598. Py_RETURN_NONE;
  4599. }
  4600. return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
  4601. }
  4602. static int
  4603. dictitems_contains(_PyDictViewObject *dv, PyObject *obj)
  4604. {
  4605. int result;
  4606. PyObject *key, *value, *found;
  4607. if (dv->dv_dict == NULL)
  4608. return 0;
  4609. if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
  4610. return 0;
  4611. key = PyTuple_GET_ITEM(obj, 0);
  4612. value = PyTuple_GET_ITEM(obj, 1);
  4613. found = PyDict_GetItemWithError((PyObject *)dv->dv_dict, key);
  4614. if (found == NULL) {
  4615. if (PyErr_Occurred())
  4616. return -1;
  4617. return 0;
  4618. }
  4619. Py_INCREF(found);
  4620. result = PyObject_RichCompareBool(found, value, Py_EQ);
  4621. Py_DECREF(found);
  4622. return result;
  4623. }
  4624. static PySequenceMethods dictitems_as_sequence = {
  4625. (lenfunc)dictview_len, /* sq_length */
  4626. 0, /* sq_concat */
  4627. 0, /* sq_repeat */
  4628. 0, /* sq_item */
  4629. 0, /* sq_slice */
  4630. 0, /* sq_ass_item */
  4631. 0, /* sq_ass_slice */
  4632. (objobjproc)dictitems_contains, /* sq_contains */
  4633. };
  4634. static PyObject* dictitems_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored));
  4635. PyDoc_STRVAR(reversed_items_doc,
  4636. "Return a reverse iterator over the dict items.");
  4637. static PyMethodDef dictitems_methods[] = {
  4638. {"isdisjoint", (PyCFunction)dictviews_isdisjoint, METH_O,
  4639. isdisjoint_doc},
  4640. {"__reversed__", (PyCFunction)dictitems_reversed, METH_NOARGS,
  4641. reversed_items_doc},
  4642. {NULL, NULL} /* sentinel */
  4643. };
  4644. PyTypeObject PyDictItems_Type = {
  4645. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  4646. "dict_items", /* tp_name */
  4647. sizeof(_PyDictViewObject), /* tp_basicsize */
  4648. 0, /* tp_itemsize */
  4649. /* methods */
  4650. (destructor)dictview_dealloc, /* tp_dealloc */
  4651. 0, /* tp_vectorcall_offset */
  4652. 0, /* tp_getattr */
  4653. 0, /* tp_setattr */
  4654. 0, /* tp_as_async */
  4655. (reprfunc)dictview_repr, /* tp_repr */
  4656. &dictviews_as_number, /* tp_as_number */
  4657. &dictitems_as_sequence, /* tp_as_sequence */
  4658. 0, /* tp_as_mapping */
  4659. 0, /* tp_hash */
  4660. 0, /* tp_call */
  4661. 0, /* tp_str */
  4662. PyObject_GenericGetAttr, /* tp_getattro */
  4663. 0, /* tp_setattro */
  4664. 0, /* tp_as_buffer */
  4665. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  4666. 0, /* tp_doc */
  4667. (traverseproc)dictview_traverse, /* tp_traverse */
  4668. 0, /* tp_clear */
  4669. dictview_richcompare, /* tp_richcompare */
  4670. 0, /* tp_weaklistoffset */
  4671. (getiterfunc)dictitems_iter, /* tp_iter */
  4672. 0, /* tp_iternext */
  4673. dictitems_methods, /* tp_methods */
  4674. .tp_getset = dictview_getset,
  4675. };
  4676. static PyObject *
  4677. dictitems_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
  4678. {
  4679. return _PyDictView_New(dict, &PyDictItems_Type);
  4680. }
  4681. static PyObject *
  4682. dictitems_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored))
  4683. {
  4684. if (dv->dv_dict == NULL) {
  4685. Py_RETURN_NONE;
  4686. }
  4687. return dictiter_new(dv->dv_dict, &PyDictRevIterItem_Type);
  4688. }
  4689. /*** dict_values ***/
  4690. static PyObject *
  4691. dictvalues_iter(_PyDictViewObject *dv)
  4692. {
  4693. if (dv->dv_dict == NULL) {
  4694. Py_RETURN_NONE;
  4695. }
  4696. return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
  4697. }
  4698. static PySequenceMethods dictvalues_as_sequence = {
  4699. (lenfunc)dictview_len, /* sq_length */
  4700. 0, /* sq_concat */
  4701. 0, /* sq_repeat */
  4702. 0, /* sq_item */
  4703. 0, /* sq_slice */
  4704. 0, /* sq_ass_item */
  4705. 0, /* sq_ass_slice */
  4706. (objobjproc)0, /* sq_contains */
  4707. };
  4708. static PyObject* dictvalues_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored));
  4709. PyDoc_STRVAR(reversed_values_doc,
  4710. "Return a reverse iterator over the dict values.");
  4711. static PyMethodDef dictvalues_methods[] = {
  4712. {"__reversed__", (PyCFunction)dictvalues_reversed, METH_NOARGS,
  4713. reversed_values_doc},
  4714. {NULL, NULL} /* sentinel */
  4715. };
  4716. PyTypeObject PyDictValues_Type = {
  4717. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  4718. "dict_values", /* tp_name */
  4719. sizeof(_PyDictViewObject), /* tp_basicsize */
  4720. 0, /* tp_itemsize */
  4721. /* methods */
  4722. (destructor)dictview_dealloc, /* tp_dealloc */
  4723. 0, /* tp_vectorcall_offset */
  4724. 0, /* tp_getattr */
  4725. 0, /* tp_setattr */
  4726. 0, /* tp_as_async */
  4727. (reprfunc)dictview_repr, /* tp_repr */
  4728. 0, /* tp_as_number */
  4729. &dictvalues_as_sequence, /* tp_as_sequence */
  4730. 0, /* tp_as_mapping */
  4731. 0, /* tp_hash */
  4732. 0, /* tp_call */
  4733. 0, /* tp_str */
  4734. PyObject_GenericGetAttr, /* tp_getattro */
  4735. 0, /* tp_setattro */
  4736. 0, /* tp_as_buffer */
  4737. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  4738. 0, /* tp_doc */
  4739. (traverseproc)dictview_traverse, /* tp_traverse */
  4740. 0, /* tp_clear */
  4741. 0, /* tp_richcompare */
  4742. 0, /* tp_weaklistoffset */
  4743. (getiterfunc)dictvalues_iter, /* tp_iter */
  4744. 0, /* tp_iternext */
  4745. dictvalues_methods, /* tp_methods */
  4746. .tp_getset = dictview_getset,
  4747. };
  4748. static PyObject *
  4749. dictvalues_new(PyObject *dict, PyObject *Py_UNUSED(ignored))
  4750. {
  4751. return _PyDictView_New(dict, &PyDictValues_Type);
  4752. }
  4753. static PyObject *
  4754. dictvalues_reversed(_PyDictViewObject *dv, PyObject *Py_UNUSED(ignored))
  4755. {
  4756. if (dv->dv_dict == NULL) {
  4757. Py_RETURN_NONE;
  4758. }
  4759. return dictiter_new(dv->dv_dict, &PyDictRevIterValue_Type);
  4760. }
  4761. /* Returns NULL if cannot allocate a new PyDictKeysObject,
  4762. but does not set an error */
  4763. PyDictKeysObject *
  4764. _PyDict_NewKeysForClass(void)
  4765. {
  4766. PyInterpreterState *interp = _PyInterpreterState_GET();
  4767. PyDictKeysObject *keys = new_keys_object(
  4768. interp, NEXT_LOG2_SHARED_KEYS_MAX_SIZE, 1);
  4769. if (keys == NULL) {
  4770. PyErr_Clear();
  4771. }
  4772. else {
  4773. assert(keys->dk_nentries == 0);
  4774. /* Set to max size+1 as it will shrink by one before each new object */
  4775. keys->dk_usable = SHARED_KEYS_MAX_SIZE;
  4776. keys->dk_kind = DICT_KEYS_SPLIT;
  4777. }
  4778. return keys;
  4779. }
  4780. #define CACHED_KEYS(tp) (((PyHeapTypeObject*)tp)->ht_cached_keys)
  4781. static int
  4782. init_inline_values(PyObject *obj, PyTypeObject *tp)
  4783. {
  4784. assert(tp->tp_flags & Py_TPFLAGS_HEAPTYPE);
  4785. // assert(type->tp_dictoffset > 0); -- TO DO Update this assert.
  4786. assert(tp->tp_flags & Py_TPFLAGS_MANAGED_DICT);
  4787. PyDictKeysObject *keys = CACHED_KEYS(tp);
  4788. assert(keys != NULL);
  4789. if (keys->dk_usable > 1) {
  4790. keys->dk_usable--;
  4791. }
  4792. size_t size = shared_keys_usable_size(keys);
  4793. PyDictValues *values = new_values(size);
  4794. if (values == NULL) {
  4795. PyErr_NoMemory();
  4796. return -1;
  4797. }
  4798. assert(((uint8_t *)values)[-1] >= (size + 2));
  4799. ((uint8_t *)values)[-2] = 0;
  4800. for (size_t i = 0; i < size; i++) {
  4801. values->values[i] = NULL;
  4802. }
  4803. _PyDictOrValues_SetValues(_PyObject_DictOrValuesPointer(obj), values);
  4804. return 0;
  4805. }
  4806. int
  4807. _PyObject_InitializeDict(PyObject *obj)
  4808. {
  4809. PyInterpreterState *interp = _PyInterpreterState_GET();
  4810. PyTypeObject *tp = Py_TYPE(obj);
  4811. if (tp->tp_dictoffset == 0) {
  4812. return 0;
  4813. }
  4814. if (tp->tp_flags & Py_TPFLAGS_MANAGED_DICT) {
  4815. OBJECT_STAT_INC(new_values);
  4816. return init_inline_values(obj, tp);
  4817. }
  4818. PyObject *dict;
  4819. if (_PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
  4820. dictkeys_incref(CACHED_KEYS(tp));
  4821. dict = new_dict_with_shared_keys(interp, CACHED_KEYS(tp));
  4822. }
  4823. else {
  4824. dict = PyDict_New();
  4825. }
  4826. if (dict == NULL) {
  4827. return -1;
  4828. }
  4829. PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
  4830. *dictptr = dict;
  4831. return 0;
  4832. }
  4833. static PyObject *
  4834. make_dict_from_instance_attributes(PyInterpreterState *interp,
  4835. PyDictKeysObject *keys, PyDictValues *values)
  4836. {
  4837. dictkeys_incref(keys);
  4838. Py_ssize_t used = 0;
  4839. Py_ssize_t track = 0;
  4840. size_t size = shared_keys_usable_size(keys);
  4841. for (size_t i = 0; i < size; i++) {
  4842. PyObject *val = values->values[i];
  4843. if (val != NULL) {
  4844. used += 1;
  4845. track += _PyObject_GC_MAY_BE_TRACKED(val);
  4846. }
  4847. }
  4848. PyObject *res = new_dict(interp, keys, values, used, 0);
  4849. if (track && res) {
  4850. _PyObject_GC_TRACK(res);
  4851. }
  4852. return res;
  4853. }
  4854. PyObject *
  4855. _PyObject_MakeDictFromInstanceAttributes(PyObject *obj, PyDictValues *values)
  4856. {
  4857. PyInterpreterState *interp = _PyInterpreterState_GET();
  4858. PyDictKeysObject *keys = CACHED_KEYS(Py_TYPE(obj));
  4859. OBJECT_STAT_INC(dict_materialized_on_request);
  4860. return make_dict_from_instance_attributes(interp, keys, values);
  4861. }
  4862. int
  4863. _PyObject_StoreInstanceAttribute(PyObject *obj, PyDictValues *values,
  4864. PyObject *name, PyObject *value)
  4865. {
  4866. PyInterpreterState *interp = _PyInterpreterState_GET();
  4867. PyDictKeysObject *keys = CACHED_KEYS(Py_TYPE(obj));
  4868. assert(keys != NULL);
  4869. assert(values != NULL);
  4870. assert(Py_TYPE(obj)->tp_flags & Py_TPFLAGS_MANAGED_DICT);
  4871. Py_ssize_t ix = DKIX_EMPTY;
  4872. if (PyUnicode_CheckExact(name)) {
  4873. ix = insert_into_dictkeys(keys, name);
  4874. }
  4875. if (ix == DKIX_EMPTY) {
  4876. #ifdef Py_STATS
  4877. if (PyUnicode_CheckExact(name)) {
  4878. if (shared_keys_usable_size(keys) == SHARED_KEYS_MAX_SIZE) {
  4879. OBJECT_STAT_INC(dict_materialized_too_big);
  4880. }
  4881. else {
  4882. OBJECT_STAT_INC(dict_materialized_new_key);
  4883. }
  4884. }
  4885. else {
  4886. OBJECT_STAT_INC(dict_materialized_str_subclass);
  4887. }
  4888. #endif
  4889. PyObject *dict = make_dict_from_instance_attributes(
  4890. interp, keys, values);
  4891. if (dict == NULL) {
  4892. return -1;
  4893. }
  4894. _PyObject_DictOrValuesPointer(obj)->dict = dict;
  4895. if (value == NULL) {
  4896. return PyDict_DelItem(dict, name);
  4897. }
  4898. else {
  4899. return PyDict_SetItem(dict, name, value);
  4900. }
  4901. }
  4902. PyObject *old_value = values->values[ix];
  4903. values->values[ix] = Py_XNewRef(value);
  4904. if (old_value == NULL) {
  4905. if (value == NULL) {
  4906. PyErr_Format(PyExc_AttributeError,
  4907. "'%.100s' object has no attribute '%U'",
  4908. Py_TYPE(obj)->tp_name, name);
  4909. return -1;
  4910. }
  4911. _PyDictValues_AddToInsertionOrder(values, ix);
  4912. }
  4913. else {
  4914. if (value == NULL) {
  4915. delete_index_from_values(values, ix);
  4916. }
  4917. Py_DECREF(old_value);
  4918. }
  4919. return 0;
  4920. }
  4921. /* Sanity check for managed dicts */
  4922. #if 0
  4923. #define CHECK(val) assert(val); if (!(val)) { return 0; }
  4924. int
  4925. _PyObject_ManagedDictValidityCheck(PyObject *obj)
  4926. {
  4927. PyTypeObject *tp = Py_TYPE(obj);
  4928. CHECK(tp->tp_flags & Py_TPFLAGS_MANAGED_DICT);
  4929. PyDictOrValues *dorv_ptr = _PyObject_DictOrValuesPointer(obj);
  4930. if (_PyDictOrValues_IsValues(*dorv_ptr)) {
  4931. PyDictValues *values = _PyDictOrValues_GetValues(*dorv_ptr);
  4932. int size = ((uint8_t *)values)[-2];
  4933. int count = 0;
  4934. PyDictKeysObject *keys = CACHED_KEYS(tp);
  4935. for (Py_ssize_t i = 0; i < keys->dk_nentries; i++) {
  4936. if (values->values[i] != NULL) {
  4937. count++;
  4938. }
  4939. }
  4940. CHECK(size == count);
  4941. }
  4942. else {
  4943. if (dorv_ptr->dict != NULL) {
  4944. CHECK(PyDict_Check(dorv_ptr->dict));
  4945. }
  4946. }
  4947. return 1;
  4948. }
  4949. #endif
  4950. PyObject *
  4951. _PyObject_GetInstanceAttribute(PyObject *obj, PyDictValues *values,
  4952. PyObject *name)
  4953. {
  4954. assert(PyUnicode_CheckExact(name));
  4955. PyDictKeysObject *keys = CACHED_KEYS(Py_TYPE(obj));
  4956. assert(keys != NULL);
  4957. Py_ssize_t ix = _PyDictKeys_StringLookup(keys, name);
  4958. if (ix == DKIX_EMPTY) {
  4959. return NULL;
  4960. }
  4961. PyObject *value = values->values[ix];
  4962. return Py_XNewRef(value);
  4963. }
  4964. int
  4965. _PyObject_IsInstanceDictEmpty(PyObject *obj)
  4966. {
  4967. PyTypeObject *tp = Py_TYPE(obj);
  4968. if (tp->tp_dictoffset == 0) {
  4969. return 1;
  4970. }
  4971. PyObject *dict;
  4972. if (tp->tp_flags & Py_TPFLAGS_MANAGED_DICT) {
  4973. PyDictOrValues dorv = *_PyObject_DictOrValuesPointer(obj);
  4974. if (_PyDictOrValues_IsValues(dorv)) {
  4975. PyDictKeysObject *keys = CACHED_KEYS(tp);
  4976. for (Py_ssize_t i = 0; i < keys->dk_nentries; i++) {
  4977. if (_PyDictOrValues_GetValues(dorv)->values[i] != NULL) {
  4978. return 0;
  4979. }
  4980. }
  4981. return 1;
  4982. }
  4983. dict = _PyDictOrValues_GetDict(dorv);
  4984. }
  4985. else {
  4986. PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
  4987. dict = *dictptr;
  4988. }
  4989. if (dict == NULL) {
  4990. return 1;
  4991. }
  4992. return ((PyDictObject *)dict)->ma_used == 0;
  4993. }
  4994. void
  4995. _PyObject_FreeInstanceAttributes(PyObject *self)
  4996. {
  4997. PyTypeObject *tp = Py_TYPE(self);
  4998. assert(Py_TYPE(self)->tp_flags & Py_TPFLAGS_MANAGED_DICT);
  4999. PyDictOrValues dorv = *_PyObject_DictOrValuesPointer(self);
  5000. if (!_PyDictOrValues_IsValues(dorv)) {
  5001. return;
  5002. }
  5003. PyDictValues *values = _PyDictOrValues_GetValues(dorv);
  5004. PyDictKeysObject *keys = CACHED_KEYS(tp);
  5005. for (Py_ssize_t i = 0; i < keys->dk_nentries; i++) {
  5006. Py_XDECREF(values->values[i]);
  5007. }
  5008. free_values(values);
  5009. }
  5010. int
  5011. _PyObject_VisitManagedDict(PyObject *obj, visitproc visit, void *arg)
  5012. {
  5013. PyTypeObject *tp = Py_TYPE(obj);
  5014. if((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0) {
  5015. return 0;
  5016. }
  5017. assert(tp->tp_dictoffset);
  5018. PyDictOrValues dorv = *_PyObject_DictOrValuesPointer(obj);
  5019. if (_PyDictOrValues_IsValues(dorv)) {
  5020. PyDictValues *values = _PyDictOrValues_GetValues(dorv);
  5021. PyDictKeysObject *keys = CACHED_KEYS(tp);
  5022. for (Py_ssize_t i = 0; i < keys->dk_nentries; i++) {
  5023. Py_VISIT(values->values[i]);
  5024. }
  5025. }
  5026. else {
  5027. PyObject *dict = _PyDictOrValues_GetDict(dorv);
  5028. Py_VISIT(dict);
  5029. }
  5030. return 0;
  5031. }
  5032. void
  5033. _PyObject_ClearManagedDict(PyObject *obj)
  5034. {
  5035. PyTypeObject *tp = Py_TYPE(obj);
  5036. if((tp->tp_flags & Py_TPFLAGS_MANAGED_DICT) == 0) {
  5037. return;
  5038. }
  5039. PyDictOrValues *dorv_ptr = _PyObject_DictOrValuesPointer(obj);
  5040. if (_PyDictOrValues_IsValues(*dorv_ptr)) {
  5041. PyDictValues *values = _PyDictOrValues_GetValues(*dorv_ptr);
  5042. PyDictKeysObject *keys = CACHED_KEYS(tp);
  5043. for (Py_ssize_t i = 0; i < keys->dk_nentries; i++) {
  5044. Py_CLEAR(values->values[i]);
  5045. }
  5046. dorv_ptr->dict = NULL;
  5047. free_values(values);
  5048. }
  5049. else {
  5050. PyObject *dict = dorv_ptr->dict;
  5051. if (dict) {
  5052. dorv_ptr->dict = NULL;
  5053. Py_DECREF(dict);
  5054. }
  5055. }
  5056. }
  5057. PyObject *
  5058. PyObject_GenericGetDict(PyObject *obj, void *context)
  5059. {
  5060. PyObject *dict;
  5061. PyInterpreterState *interp = _PyInterpreterState_GET();
  5062. PyTypeObject *tp = Py_TYPE(obj);
  5063. if (_PyType_HasFeature(tp, Py_TPFLAGS_MANAGED_DICT)) {
  5064. PyDictOrValues *dorv_ptr = _PyObject_DictOrValuesPointer(obj);
  5065. if (_PyDictOrValues_IsValues(*dorv_ptr)) {
  5066. PyDictValues *values = _PyDictOrValues_GetValues(*dorv_ptr);
  5067. OBJECT_STAT_INC(dict_materialized_on_request);
  5068. dict = make_dict_from_instance_attributes(
  5069. interp, CACHED_KEYS(tp), values);
  5070. if (dict != NULL) {
  5071. dorv_ptr->dict = dict;
  5072. }
  5073. }
  5074. else {
  5075. dict = _PyDictOrValues_GetDict(*dorv_ptr);
  5076. if (dict == NULL) {
  5077. dictkeys_incref(CACHED_KEYS(tp));
  5078. dict = new_dict_with_shared_keys(interp, CACHED_KEYS(tp));
  5079. dorv_ptr->dict = dict;
  5080. }
  5081. }
  5082. }
  5083. else {
  5084. PyObject **dictptr = _PyObject_ComputedDictPointer(obj);
  5085. if (dictptr == NULL) {
  5086. PyErr_SetString(PyExc_AttributeError,
  5087. "This object has no __dict__");
  5088. return NULL;
  5089. }
  5090. dict = *dictptr;
  5091. if (dict == NULL) {
  5092. PyTypeObject *tp = Py_TYPE(obj);
  5093. if (_PyType_HasFeature(tp, Py_TPFLAGS_HEAPTYPE) && CACHED_KEYS(tp)) {
  5094. dictkeys_incref(CACHED_KEYS(tp));
  5095. *dictptr = dict = new_dict_with_shared_keys(
  5096. interp, CACHED_KEYS(tp));
  5097. }
  5098. else {
  5099. *dictptr = dict = PyDict_New();
  5100. }
  5101. }
  5102. }
  5103. return Py_XNewRef(dict);
  5104. }
  5105. int
  5106. _PyObjectDict_SetItem(PyTypeObject *tp, PyObject **dictptr,
  5107. PyObject *key, PyObject *value)
  5108. {
  5109. PyObject *dict;
  5110. int res;
  5111. PyDictKeysObject *cached;
  5112. PyInterpreterState *interp = _PyInterpreterState_GET();
  5113. assert(dictptr != NULL);
  5114. if ((tp->tp_flags & Py_TPFLAGS_HEAPTYPE) && (cached = CACHED_KEYS(tp))) {
  5115. assert(dictptr != NULL);
  5116. dict = *dictptr;
  5117. if (dict == NULL) {
  5118. dictkeys_incref(cached);
  5119. dict = new_dict_with_shared_keys(interp, cached);
  5120. if (dict == NULL)
  5121. return -1;
  5122. *dictptr = dict;
  5123. }
  5124. if (value == NULL) {
  5125. res = PyDict_DelItem(dict, key);
  5126. }
  5127. else {
  5128. res = PyDict_SetItem(dict, key, value);
  5129. }
  5130. } else {
  5131. dict = *dictptr;
  5132. if (dict == NULL) {
  5133. dict = PyDict_New();
  5134. if (dict == NULL)
  5135. return -1;
  5136. *dictptr = dict;
  5137. }
  5138. if (value == NULL) {
  5139. res = PyDict_DelItem(dict, key);
  5140. } else {
  5141. res = PyDict_SetItem(dict, key, value);
  5142. }
  5143. }
  5144. ASSERT_CONSISTENT(dict);
  5145. return res;
  5146. }
  5147. void
  5148. _PyDictKeys_DecRef(PyDictKeysObject *keys)
  5149. {
  5150. PyInterpreterState *interp = _PyInterpreterState_GET();
  5151. dictkeys_decref(interp, keys);
  5152. }
  5153. uint32_t _PyDictKeys_GetVersionForCurrentState(PyInterpreterState *interp,
  5154. PyDictKeysObject *dictkeys)
  5155. {
  5156. if (dictkeys->dk_version != 0) {
  5157. return dictkeys->dk_version;
  5158. }
  5159. if (interp->dict_state.next_keys_version == 0) {
  5160. return 0;
  5161. }
  5162. uint32_t v = interp->dict_state.next_keys_version++;
  5163. dictkeys->dk_version = v;
  5164. return v;
  5165. }
  5166. static inline int
  5167. validate_watcher_id(PyInterpreterState *interp, int watcher_id)
  5168. {
  5169. if (watcher_id < 0 || watcher_id >= DICT_MAX_WATCHERS) {
  5170. PyErr_Format(PyExc_ValueError, "Invalid dict watcher ID %d", watcher_id);
  5171. return -1;
  5172. }
  5173. if (!interp->dict_state.watchers[watcher_id]) {
  5174. PyErr_Format(PyExc_ValueError, "No dict watcher set for ID %d", watcher_id);
  5175. return -1;
  5176. }
  5177. return 0;
  5178. }
  5179. int
  5180. PyDict_Watch(int watcher_id, PyObject* dict)
  5181. {
  5182. if (!PyDict_Check(dict)) {
  5183. PyErr_SetString(PyExc_ValueError, "Cannot watch non-dictionary");
  5184. return -1;
  5185. }
  5186. PyInterpreterState *interp = _PyInterpreterState_GET();
  5187. if (validate_watcher_id(interp, watcher_id)) {
  5188. return -1;
  5189. }
  5190. ((PyDictObject*)dict)->ma_version_tag |= (1LL << watcher_id);
  5191. return 0;
  5192. }
  5193. int
  5194. PyDict_Unwatch(int watcher_id, PyObject* dict)
  5195. {
  5196. if (!PyDict_Check(dict)) {
  5197. PyErr_SetString(PyExc_ValueError, "Cannot watch non-dictionary");
  5198. return -1;
  5199. }
  5200. PyInterpreterState *interp = _PyInterpreterState_GET();
  5201. if (validate_watcher_id(interp, watcher_id)) {
  5202. return -1;
  5203. }
  5204. ((PyDictObject*)dict)->ma_version_tag &= ~(1LL << watcher_id);
  5205. return 0;
  5206. }
  5207. int
  5208. PyDict_AddWatcher(PyDict_WatchCallback callback)
  5209. {
  5210. PyInterpreterState *interp = _PyInterpreterState_GET();
  5211. for (int i = 0; i < DICT_MAX_WATCHERS; i++) {
  5212. if (!interp->dict_state.watchers[i]) {
  5213. interp->dict_state.watchers[i] = callback;
  5214. return i;
  5215. }
  5216. }
  5217. PyErr_SetString(PyExc_RuntimeError, "no more dict watcher IDs available");
  5218. return -1;
  5219. }
  5220. int
  5221. PyDict_ClearWatcher(int watcher_id)
  5222. {
  5223. PyInterpreterState *interp = _PyInterpreterState_GET();
  5224. if (validate_watcher_id(interp, watcher_id)) {
  5225. return -1;
  5226. }
  5227. interp->dict_state.watchers[watcher_id] = NULL;
  5228. return 0;
  5229. }
  5230. static const char *
  5231. dict_event_name(PyDict_WatchEvent event) {
  5232. switch (event) {
  5233. #define CASE(op) \
  5234. case PyDict_EVENT_##op: \
  5235. return "PyDict_EVENT_" #op;
  5236. PY_FOREACH_DICT_EVENT(CASE)
  5237. #undef CASE
  5238. }
  5239. Py_UNREACHABLE();
  5240. }
  5241. void
  5242. _PyDict_SendEvent(int watcher_bits,
  5243. PyDict_WatchEvent event,
  5244. PyDictObject *mp,
  5245. PyObject *key,
  5246. PyObject *value)
  5247. {
  5248. PyInterpreterState *interp = _PyInterpreterState_GET();
  5249. for (int i = 0; i < DICT_MAX_WATCHERS; i++) {
  5250. if (watcher_bits & 1) {
  5251. PyDict_WatchCallback cb = interp->dict_state.watchers[i];
  5252. if (cb && (cb(event, (PyObject*)mp, key, value) < 0)) {
  5253. // We don't want to resurrect the dict by potentially having an
  5254. // unraisablehook keep a reference to it, so we don't pass the
  5255. // dict as context, just an informative string message. Dict
  5256. // repr can call arbitrary code, so we invent a simpler version.
  5257. PyObject *context = PyUnicode_FromFormat(
  5258. "%s watcher callback for <dict at %p>",
  5259. dict_event_name(event), mp);
  5260. if (context == NULL) {
  5261. context = Py_NewRef(Py_None);
  5262. }
  5263. PyErr_WriteUnraisable(context);
  5264. Py_DECREF(context);
  5265. }
  5266. }
  5267. watcher_bits >>= 1;
  5268. }
  5269. }