unicodeobject.c 455 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712
  1. /*
  2. Unicode implementation based on original code by Fredrik Lundh,
  3. modified by Marc-Andre Lemburg <mal@lemburg.com>.
  4. Major speed upgrades to the method implementations at the Reykjavik
  5. NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
  6. Copyright (c) Corporation for National Research Initiatives.
  7. --------------------------------------------------------------------
  8. The original string type implementation is:
  9. Copyright (c) 1999 by Secret Labs AB
  10. Copyright (c) 1999 by Fredrik Lundh
  11. By obtaining, using, and/or copying this software and/or its
  12. associated documentation, you agree that you have read, understood,
  13. and will comply with the following terms and conditions:
  14. Permission to use, copy, modify, and distribute this software and its
  15. associated documentation for any purpose and without fee is hereby
  16. granted, provided that the above copyright notice appears in all
  17. copies, and that both that copyright notice and this permission notice
  18. appear in supporting documentation, and that the name of Secret Labs
  19. AB or the author not be used in advertising or publicity pertaining to
  20. distribution of the software without specific, written prior
  21. permission.
  22. SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
  23. THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  24. FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
  25. ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  26. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  27. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  28. OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  29. --------------------------------------------------------------------
  30. */
  31. #define PY_SSIZE_T_CLEAN
  32. #include "Python.h"
  33. #include "pycore_abstract.h" // _PyIndex_Check()
  34. #include "pycore_atomic_funcs.h" // _Py_atomic_size_get()
  35. #include "pycore_bytesobject.h" // _PyBytes_Repeat()
  36. #include "pycore_bytes_methods.h" // _Py_bytes_lower()
  37. #include "pycore_format.h" // F_LJUST
  38. #include "pycore_initconfig.h" // _PyStatus_OK()
  39. #include "pycore_interp.h" // PyInterpreterState.fs_codec
  40. #include "pycore_long.h" // _PyLong_FormatWriter()
  41. #include "pycore_object.h" // _PyObject_GC_TRACK(), _Py_FatalRefcountError()
  42. #include "pycore_pathconfig.h" // _Py_DumpPathConfig()
  43. #include "pycore_pylifecycle.h" // _Py_SetFileSystemEncoding()
  44. #include "pycore_pystate.h" // _PyInterpreterState_GET()
  45. #include "pycore_ucnhash.h" // _PyUnicode_Name_CAPI
  46. #include "pycore_unicodeobject.h" // struct _Py_unicode_state
  47. #include "pycore_unicodeobject_generated.h" // _PyUnicode_InitStaticStrings()
  48. #include "stringlib/eq.h" // unicode_eq()
  49. #include <stddef.h> // ptrdiff_t
  50. #ifdef MS_WINDOWS
  51. #include <windows.h>
  52. #endif
  53. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  54. # include "pycore_fileutils.h" // _Py_LocaleUsesNonUnicodeWchar()
  55. #endif
  56. /* Uncomment to display statistics on interned strings at exit
  57. in _PyUnicode_ClearInterned(). */
  58. /* #define INTERNED_STATS 1 */
  59. /*[clinic input]
  60. class str "PyObject *" "&PyUnicode_Type"
  61. [clinic start generated code]*/
  62. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=4884c934de622cf6]*/
  63. /*[python input]
  64. class Py_UCS4_converter(CConverter):
  65. type = 'Py_UCS4'
  66. converter = 'convert_uc'
  67. def converter_init(self):
  68. if self.default is not unspecified:
  69. self.c_default = ascii(self.default)
  70. if len(self.c_default) > 4 or self.c_default[0] != "'":
  71. self.c_default = hex(ord(self.default))
  72. [python start generated code]*/
  73. /*[python end generated code: output=da39a3ee5e6b4b0d input=88f5dd06cd8e7a61]*/
  74. /* --- Globals ------------------------------------------------------------
  75. NOTE: In the interpreter's initialization phase, some globals are currently
  76. initialized dynamically as needed. In the process Unicode objects may
  77. be created before the Unicode type is ready.
  78. */
  79. #ifdef __cplusplus
  80. extern "C" {
  81. #endif
  82. // Maximum code point of Unicode 6.0: 0x10ffff (1,114,111).
  83. // The value must be the same in fileutils.c.
  84. #define MAX_UNICODE 0x10ffff
  85. #ifdef Py_DEBUG
  86. # define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
  87. #else
  88. # define _PyUnicode_CHECK(op) PyUnicode_Check(op)
  89. #endif
  90. #define _PyUnicode_UTF8(op) \
  91. (_PyCompactUnicodeObject_CAST(op)->utf8)
  92. #define PyUnicode_UTF8(op) \
  93. (assert(_PyUnicode_CHECK(op)), \
  94. PyUnicode_IS_COMPACT_ASCII(op) ? \
  95. ((char*)(_PyASCIIObject_CAST(op) + 1)) : \
  96. _PyUnicode_UTF8(op))
  97. #define _PyUnicode_UTF8_LENGTH(op) \
  98. (_PyCompactUnicodeObject_CAST(op)->utf8_length)
  99. #define PyUnicode_UTF8_LENGTH(op) \
  100. (assert(_PyUnicode_CHECK(op)), \
  101. PyUnicode_IS_COMPACT_ASCII(op) ? \
  102. _PyASCIIObject_CAST(op)->length : \
  103. _PyUnicode_UTF8_LENGTH(op))
  104. #define _PyUnicode_LENGTH(op) \
  105. (_PyASCIIObject_CAST(op)->length)
  106. #define _PyUnicode_STATE(op) \
  107. (_PyASCIIObject_CAST(op)->state)
  108. #define _PyUnicode_HASH(op) \
  109. (_PyASCIIObject_CAST(op)->hash)
  110. #define _PyUnicode_KIND(op) \
  111. (assert(_PyUnicode_CHECK(op)), \
  112. _PyASCIIObject_CAST(op)->state.kind)
  113. #define _PyUnicode_GET_LENGTH(op) \
  114. (assert(_PyUnicode_CHECK(op)), \
  115. _PyASCIIObject_CAST(op)->length)
  116. #define _PyUnicode_DATA_ANY(op) \
  117. (_PyUnicodeObject_CAST(op)->data.any)
  118. #define _PyUnicode_SHARE_UTF8(op) \
  119. (assert(_PyUnicode_CHECK(op)), \
  120. assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
  121. (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
  122. /* true if the Unicode object has an allocated UTF-8 memory block
  123. (not shared with other data) */
  124. #define _PyUnicode_HAS_UTF8_MEMORY(op) \
  125. ((!PyUnicode_IS_COMPACT_ASCII(op) \
  126. && _PyUnicode_UTF8(op) \
  127. && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
  128. /* Generic helper macro to convert characters of different types.
  129. from_type and to_type have to be valid type names, begin and end
  130. are pointers to the source characters which should be of type
  131. "from_type *". to is a pointer of type "to_type *" and points to the
  132. buffer where the result characters are written to. */
  133. #define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
  134. do { \
  135. to_type *_to = (to_type *)(to); \
  136. const from_type *_iter = (const from_type *)(begin);\
  137. const from_type *_end = (const from_type *)(end);\
  138. Py_ssize_t n = (_end) - (_iter); \
  139. const from_type *_unrolled_end = \
  140. _iter + _Py_SIZE_ROUND_DOWN(n, 4); \
  141. while (_iter < (_unrolled_end)) { \
  142. _to[0] = (to_type) _iter[0]; \
  143. _to[1] = (to_type) _iter[1]; \
  144. _to[2] = (to_type) _iter[2]; \
  145. _to[3] = (to_type) _iter[3]; \
  146. _iter += 4; _to += 4; \
  147. } \
  148. while (_iter < (_end)) \
  149. *_to++ = (to_type) *_iter++; \
  150. } while (0)
  151. #define LATIN1 _Py_LATIN1_CHR
  152. #ifdef MS_WINDOWS
  153. /* On Windows, overallocate by 50% is the best factor */
  154. # define OVERALLOCATE_FACTOR 2
  155. #else
  156. /* On Linux, overallocate by 25% is the best factor */
  157. # define OVERALLOCATE_FACTOR 4
  158. #endif
  159. /* Forward declaration */
  160. static inline int
  161. _PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
  162. static inline void
  163. _PyUnicodeWriter_InitWithBuffer(_PyUnicodeWriter *writer, PyObject *buffer);
  164. static PyObject *
  165. unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
  166. const char *errors);
  167. static PyObject *
  168. unicode_decode_utf8(const char *s, Py_ssize_t size,
  169. _Py_error_handler error_handler, const char *errors,
  170. Py_ssize_t *consumed);
  171. #ifdef Py_DEBUG
  172. static inline int unicode_is_finalizing(void);
  173. static int unicode_is_singleton(PyObject *unicode);
  174. #endif
  175. // Return a borrowed reference to the empty string singleton.
  176. static inline PyObject* unicode_get_empty(void)
  177. {
  178. _Py_DECLARE_STR(empty, "");
  179. return &_Py_STR(empty);
  180. }
  181. // Return a strong reference to the empty string singleton.
  182. static inline PyObject* unicode_new_empty(void)
  183. {
  184. PyObject *empty = unicode_get_empty();
  185. return Py_NewRef(empty);
  186. }
  187. /* This dictionary holds per-interpreter interned strings.
  188. * See InternalDocs/string_interning.md for details.
  189. */
  190. static inline PyObject *get_interned_dict(PyInterpreterState *interp)
  191. {
  192. return _Py_INTERP_CACHED_OBJECT(interp, interned_strings);
  193. }
  194. /* This hashtable holds statically allocated interned strings.
  195. * See InternalDocs/string_interning.md for details.
  196. */
  197. #define INTERNED_STRINGS _PyRuntime.cached_objects.interned_strings
  198. /* Get number of all interned strings for the current interpreter. */
  199. Py_ssize_t
  200. _PyUnicode_InternedSize(void)
  201. {
  202. PyObject *dict = get_interned_dict(_PyInterpreterState_GET());
  203. return _Py_hashtable_len(INTERNED_STRINGS) + PyDict_GET_SIZE(dict);
  204. }
  205. /* Get number of immortal interned strings for the current interpreter. */
  206. Py_ssize_t
  207. _PyUnicode_InternedSize_Immortal(void)
  208. {
  209. PyObject *dict = get_interned_dict(_PyInterpreterState_GET());
  210. PyObject *key, *value;
  211. Py_ssize_t pos = 0;
  212. Py_ssize_t count = 0;
  213. // It's tempting to keep a count and avoid a loop here. But, this function
  214. // is intended for refleak tests. It spends extra work to report the true
  215. // value, to help detect bugs in optimizations.
  216. while (PyDict_Next(dict, &pos, &key, &value)) {
  217. assert(PyUnicode_CHECK_INTERNED(key) != SSTATE_INTERNED_IMMORTAL_STATIC);
  218. if (PyUnicode_CHECK_INTERNED(key) == SSTATE_INTERNED_IMMORTAL) {
  219. count++;
  220. }
  221. }
  222. return _Py_hashtable_len(INTERNED_STRINGS) + count;
  223. }
  224. static Py_hash_t unicode_hash(PyObject *);
  225. static int unicode_compare_eq(PyObject *, PyObject *);
  226. static Py_uhash_t
  227. hashtable_unicode_hash(const void *key)
  228. {
  229. return unicode_hash((PyObject *)key);
  230. }
  231. static int
  232. hashtable_unicode_compare(const void *key1, const void *key2)
  233. {
  234. PyObject *obj1 = (PyObject *)key1;
  235. PyObject *obj2 = (PyObject *)key2;
  236. if (obj1 != NULL && obj2 != NULL) {
  237. return unicode_compare_eq(obj1, obj2);
  238. }
  239. else {
  240. return obj1 == obj2;
  241. }
  242. }
  243. static int
  244. init_interned_dict(PyInterpreterState *interp)
  245. {
  246. assert(get_interned_dict(interp) == NULL);
  247. PyObject *interned = interned = PyDict_New();
  248. if (interned == NULL) {
  249. return -1;
  250. }
  251. _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = interned;
  252. return 0;
  253. }
  254. static void
  255. clear_interned_dict(PyInterpreterState *interp)
  256. {
  257. PyObject *interned = get_interned_dict(interp);
  258. if (interned != NULL) {
  259. PyDict_Clear(interned);
  260. Py_DECREF(interned);
  261. _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = NULL;
  262. }
  263. }
  264. static PyStatus
  265. init_global_interned_strings(PyInterpreterState *interp)
  266. {
  267. assert(INTERNED_STRINGS == NULL);
  268. _Py_hashtable_allocator_t hashtable_alloc = {PyMem_RawMalloc, PyMem_RawFree};
  269. INTERNED_STRINGS = _Py_hashtable_new_full(
  270. hashtable_unicode_hash,
  271. hashtable_unicode_compare,
  272. // Objects stored here are immortal and statically allocated,
  273. // so we don't need key_destroy_func & value_destroy_func:
  274. NULL,
  275. NULL,
  276. &hashtable_alloc
  277. );
  278. if (INTERNED_STRINGS == NULL) {
  279. PyErr_Clear();
  280. return _PyStatus_ERR("failed to create global interned dict");
  281. }
  282. /* Intern statically allocated string identifiers, deepfreeze strings,
  283. * and one-byte latin-1 strings.
  284. * This must be done before any module initialization so that statically
  285. * allocated string identifiers are used instead of heap allocated strings.
  286. * Deepfreeze uses the interned identifiers if present to save space
  287. * else generates them and they are interned to speed up dict lookups.
  288. */
  289. _PyUnicode_InitStaticStrings(interp);
  290. for (int i = 0; i < 256; i++) {
  291. PyObject *s = LATIN1(i);
  292. _PyUnicode_InternStatic(interp, &s);
  293. assert(s == LATIN1(i));
  294. }
  295. #ifdef Py_DEBUG
  296. assert(_PyUnicode_CheckConsistency(&_Py_STR(empty), 1));
  297. for (int i = 0; i < 256; i++) {
  298. assert(_PyUnicode_CheckConsistency(LATIN1(i), 1));
  299. }
  300. #endif
  301. return _PyStatus_OK();
  302. }
  303. static void clear_global_interned_strings(void)
  304. {
  305. if (INTERNED_STRINGS != NULL) {
  306. _Py_hashtable_destroy(INTERNED_STRINGS);
  307. INTERNED_STRINGS = NULL;
  308. }
  309. }
  310. #define _Py_RETURN_UNICODE_EMPTY() \
  311. do { \
  312. return unicode_new_empty(); \
  313. } while (0)
  314. static inline void
  315. unicode_fill(int kind, void *data, Py_UCS4 value,
  316. Py_ssize_t start, Py_ssize_t length)
  317. {
  318. assert(0 <= start);
  319. switch (kind) {
  320. case PyUnicode_1BYTE_KIND: {
  321. assert(value <= 0xff);
  322. Py_UCS1 ch = (unsigned char)value;
  323. Py_UCS1 *to = (Py_UCS1 *)data + start;
  324. memset(to, ch, length);
  325. break;
  326. }
  327. case PyUnicode_2BYTE_KIND: {
  328. assert(value <= 0xffff);
  329. Py_UCS2 ch = (Py_UCS2)value;
  330. Py_UCS2 *to = (Py_UCS2 *)data + start;
  331. const Py_UCS2 *end = to + length;
  332. for (; to < end; ++to) *to = ch;
  333. break;
  334. }
  335. case PyUnicode_4BYTE_KIND: {
  336. assert(value <= MAX_UNICODE);
  337. Py_UCS4 ch = value;
  338. Py_UCS4 * to = (Py_UCS4 *)data + start;
  339. const Py_UCS4 *end = to + length;
  340. for (; to < end; ++to) *to = ch;
  341. break;
  342. }
  343. default: Py_UNREACHABLE();
  344. }
  345. }
  346. /* Fast detection of the most frequent whitespace characters */
  347. const unsigned char _Py_ascii_whitespace[] = {
  348. 0, 0, 0, 0, 0, 0, 0, 0,
  349. /* case 0x0009: * CHARACTER TABULATION */
  350. /* case 0x000A: * LINE FEED */
  351. /* case 0x000B: * LINE TABULATION */
  352. /* case 0x000C: * FORM FEED */
  353. /* case 0x000D: * CARRIAGE RETURN */
  354. 0, 1, 1, 1, 1, 1, 0, 0,
  355. 0, 0, 0, 0, 0, 0, 0, 0,
  356. /* case 0x001C: * FILE SEPARATOR */
  357. /* case 0x001D: * GROUP SEPARATOR */
  358. /* case 0x001E: * RECORD SEPARATOR */
  359. /* case 0x001F: * UNIT SEPARATOR */
  360. 0, 0, 0, 0, 1, 1, 1, 1,
  361. /* case 0x0020: * SPACE */
  362. 1, 0, 0, 0, 0, 0, 0, 0,
  363. 0, 0, 0, 0, 0, 0, 0, 0,
  364. 0, 0, 0, 0, 0, 0, 0, 0,
  365. 0, 0, 0, 0, 0, 0, 0, 0,
  366. 0, 0, 0, 0, 0, 0, 0, 0,
  367. 0, 0, 0, 0, 0, 0, 0, 0,
  368. 0, 0, 0, 0, 0, 0, 0, 0,
  369. 0, 0, 0, 0, 0, 0, 0, 0,
  370. 0, 0, 0, 0, 0, 0, 0, 0,
  371. 0, 0, 0, 0, 0, 0, 0, 0,
  372. 0, 0, 0, 0, 0, 0, 0, 0,
  373. 0, 0, 0, 0, 0, 0, 0, 0
  374. };
  375. /* forward */
  376. static PyObject* get_latin1_char(unsigned char ch);
  377. static int unicode_modifiable(PyObject *unicode);
  378. static PyObject *
  379. _PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
  380. static PyObject *
  381. _PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
  382. static PyObject *
  383. _PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
  384. static PyObject *
  385. unicode_encode_call_errorhandler(const char *errors,
  386. PyObject **errorHandler,const char *encoding, const char *reason,
  387. PyObject *unicode, PyObject **exceptionObject,
  388. Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
  389. static void
  390. raise_encode_exception(PyObject **exceptionObject,
  391. const char *encoding,
  392. PyObject *unicode,
  393. Py_ssize_t startpos, Py_ssize_t endpos,
  394. const char *reason);
  395. /* Same for linebreaks */
  396. static const unsigned char ascii_linebreak[] = {
  397. 0, 0, 0, 0, 0, 0, 0, 0,
  398. /* 0x000A, * LINE FEED */
  399. /* 0x000B, * LINE TABULATION */
  400. /* 0x000C, * FORM FEED */
  401. /* 0x000D, * CARRIAGE RETURN */
  402. 0, 0, 1, 1, 1, 1, 0, 0,
  403. 0, 0, 0, 0, 0, 0, 0, 0,
  404. /* 0x001C, * FILE SEPARATOR */
  405. /* 0x001D, * GROUP SEPARATOR */
  406. /* 0x001E, * RECORD SEPARATOR */
  407. 0, 0, 0, 0, 1, 1, 1, 0,
  408. 0, 0, 0, 0, 0, 0, 0, 0,
  409. 0, 0, 0, 0, 0, 0, 0, 0,
  410. 0, 0, 0, 0, 0, 0, 0, 0,
  411. 0, 0, 0, 0, 0, 0, 0, 0,
  412. 0, 0, 0, 0, 0, 0, 0, 0,
  413. 0, 0, 0, 0, 0, 0, 0, 0,
  414. 0, 0, 0, 0, 0, 0, 0, 0,
  415. 0, 0, 0, 0, 0, 0, 0, 0,
  416. 0, 0, 0, 0, 0, 0, 0, 0,
  417. 0, 0, 0, 0, 0, 0, 0, 0,
  418. 0, 0, 0, 0, 0, 0, 0, 0,
  419. 0, 0, 0, 0, 0, 0, 0, 0
  420. };
  421. static int convert_uc(PyObject *obj, void *addr);
  422. struct encoding_map;
  423. #include "clinic/unicodeobject.c.h"
  424. _Py_error_handler
  425. _Py_GetErrorHandler(const char *errors)
  426. {
  427. if (errors == NULL || strcmp(errors, "strict") == 0) {
  428. return _Py_ERROR_STRICT;
  429. }
  430. if (strcmp(errors, "surrogateescape") == 0) {
  431. return _Py_ERROR_SURROGATEESCAPE;
  432. }
  433. if (strcmp(errors, "replace") == 0) {
  434. return _Py_ERROR_REPLACE;
  435. }
  436. if (strcmp(errors, "ignore") == 0) {
  437. return _Py_ERROR_IGNORE;
  438. }
  439. if (strcmp(errors, "backslashreplace") == 0) {
  440. return _Py_ERROR_BACKSLASHREPLACE;
  441. }
  442. if (strcmp(errors, "surrogatepass") == 0) {
  443. return _Py_ERROR_SURROGATEPASS;
  444. }
  445. if (strcmp(errors, "xmlcharrefreplace") == 0) {
  446. return _Py_ERROR_XMLCHARREFREPLACE;
  447. }
  448. return _Py_ERROR_OTHER;
  449. }
  450. static _Py_error_handler
  451. get_error_handler_wide(const wchar_t *errors)
  452. {
  453. if (errors == NULL || wcscmp(errors, L"strict") == 0) {
  454. return _Py_ERROR_STRICT;
  455. }
  456. if (wcscmp(errors, L"surrogateescape") == 0) {
  457. return _Py_ERROR_SURROGATEESCAPE;
  458. }
  459. if (wcscmp(errors, L"replace") == 0) {
  460. return _Py_ERROR_REPLACE;
  461. }
  462. if (wcscmp(errors, L"ignore") == 0) {
  463. return _Py_ERROR_IGNORE;
  464. }
  465. if (wcscmp(errors, L"backslashreplace") == 0) {
  466. return _Py_ERROR_BACKSLASHREPLACE;
  467. }
  468. if (wcscmp(errors, L"surrogatepass") == 0) {
  469. return _Py_ERROR_SURROGATEPASS;
  470. }
  471. if (wcscmp(errors, L"xmlcharrefreplace") == 0) {
  472. return _Py_ERROR_XMLCHARREFREPLACE;
  473. }
  474. return _Py_ERROR_OTHER;
  475. }
  476. static inline int
  477. unicode_check_encoding_errors(const char *encoding, const char *errors)
  478. {
  479. if (encoding == NULL && errors == NULL) {
  480. return 0;
  481. }
  482. PyInterpreterState *interp = _PyInterpreterState_GET();
  483. #ifndef Py_DEBUG
  484. /* In release mode, only check in development mode (-X dev) */
  485. if (!_PyInterpreterState_GetConfig(interp)->dev_mode) {
  486. return 0;
  487. }
  488. #else
  489. /* Always check in debug mode */
  490. #endif
  491. /* Avoid calling _PyCodec_Lookup() and PyCodec_LookupError() before the
  492. codec registry is ready: before_PyUnicode_InitEncodings() is called. */
  493. if (!interp->unicode.fs_codec.encoding) {
  494. return 0;
  495. }
  496. /* Disable checks during Python finalization. For example, it allows to
  497. call _PyObject_Dump() during finalization for debugging purpose. */
  498. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  499. return 0;
  500. }
  501. if (encoding != NULL
  502. // Fast path for the most common built-in encodings. Even if the codec
  503. // is cached, _PyCodec_Lookup() decodes the bytes string from UTF-8 to
  504. // create a temporary Unicode string (the key in the cache).
  505. && strcmp(encoding, "utf-8") != 0
  506. && strcmp(encoding, "utf8") != 0
  507. && strcmp(encoding, "ascii") != 0)
  508. {
  509. PyObject *handler = _PyCodec_Lookup(encoding);
  510. if (handler == NULL) {
  511. return -1;
  512. }
  513. Py_DECREF(handler);
  514. }
  515. if (errors != NULL
  516. // Fast path for the most common built-in error handlers.
  517. && strcmp(errors, "strict") != 0
  518. && strcmp(errors, "ignore") != 0
  519. && strcmp(errors, "replace") != 0
  520. && strcmp(errors, "surrogateescape") != 0
  521. && strcmp(errors, "surrogatepass") != 0)
  522. {
  523. PyObject *handler = PyCodec_LookupError(errors);
  524. if (handler == NULL) {
  525. return -1;
  526. }
  527. Py_DECREF(handler);
  528. }
  529. return 0;
  530. }
  531. int
  532. _PyUnicode_CheckConsistency(PyObject *op, int check_content)
  533. {
  534. #define CHECK(expr) \
  535. do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
  536. assert(op != NULL);
  537. CHECK(PyUnicode_Check(op));
  538. PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
  539. int kind = ascii->state.kind;
  540. if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
  541. CHECK(kind == PyUnicode_1BYTE_KIND);
  542. }
  543. else {
  544. PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
  545. void *data;
  546. if (ascii->state.compact == 1) {
  547. data = compact + 1;
  548. CHECK(kind == PyUnicode_1BYTE_KIND
  549. || kind == PyUnicode_2BYTE_KIND
  550. || kind == PyUnicode_4BYTE_KIND);
  551. CHECK(ascii->state.ascii == 0);
  552. CHECK(compact->utf8 != data);
  553. }
  554. else {
  555. PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
  556. data = unicode->data.any;
  557. CHECK(kind == PyUnicode_1BYTE_KIND
  558. || kind == PyUnicode_2BYTE_KIND
  559. || kind == PyUnicode_4BYTE_KIND);
  560. CHECK(ascii->state.compact == 0);
  561. CHECK(data != NULL);
  562. if (ascii->state.ascii) {
  563. CHECK(compact->utf8 == data);
  564. CHECK(compact->utf8_length == ascii->length);
  565. }
  566. else {
  567. CHECK(compact->utf8 != data);
  568. }
  569. }
  570. if (compact->utf8 == NULL)
  571. CHECK(compact->utf8_length == 0);
  572. }
  573. /* check that the best kind is used: O(n) operation */
  574. if (check_content) {
  575. Py_ssize_t i;
  576. Py_UCS4 maxchar = 0;
  577. const void *data;
  578. Py_UCS4 ch;
  579. data = PyUnicode_DATA(ascii);
  580. for (i=0; i < ascii->length; i++)
  581. {
  582. ch = PyUnicode_READ(kind, data, i);
  583. if (ch > maxchar)
  584. maxchar = ch;
  585. }
  586. if (kind == PyUnicode_1BYTE_KIND) {
  587. if (ascii->state.ascii == 0) {
  588. CHECK(maxchar >= 128);
  589. CHECK(maxchar <= 255);
  590. }
  591. else
  592. CHECK(maxchar < 128);
  593. }
  594. else if (kind == PyUnicode_2BYTE_KIND) {
  595. CHECK(maxchar >= 0x100);
  596. CHECK(maxchar <= 0xFFFF);
  597. }
  598. else {
  599. CHECK(maxchar >= 0x10000);
  600. CHECK(maxchar <= MAX_UNICODE);
  601. }
  602. CHECK(PyUnicode_READ(kind, data, ascii->length) == 0);
  603. }
  604. /* Check interning state */
  605. #ifdef Py_DEBUG
  606. // Note that we do not check `_Py_IsImmortal(op)`, since stable ABI
  607. // extensions can make immortal strings mortal (but with a high enough
  608. // refcount).
  609. // The other way is extremely unlikely (worth a potential failed assertion
  610. // in a debug build), so we do check `!_Py_IsImmortal(op)`.
  611. switch (PyUnicode_CHECK_INTERNED(op)) {
  612. case SSTATE_NOT_INTERNED:
  613. if (ascii->state.statically_allocated) {
  614. // This state is for two exceptions:
  615. // - strings are currently checked before they're interned
  616. // - the 256 one-latin1-character strings
  617. // are static but use SSTATE_NOT_INTERNED
  618. }
  619. else {
  620. CHECK(!_Py_IsImmortal(op));
  621. }
  622. break;
  623. case SSTATE_INTERNED_MORTAL:
  624. CHECK(!ascii->state.statically_allocated);
  625. CHECK(!_Py_IsImmortal(op));
  626. break;
  627. case SSTATE_INTERNED_IMMORTAL:
  628. CHECK(!ascii->state.statically_allocated);
  629. break;
  630. case SSTATE_INTERNED_IMMORTAL_STATIC:
  631. CHECK(ascii->state.statically_allocated);
  632. break;
  633. default:
  634. Py_UNREACHABLE();
  635. }
  636. #endif
  637. return 1;
  638. #undef CHECK
  639. }
  640. static PyObject*
  641. unicode_result(PyObject *unicode)
  642. {
  643. assert(_PyUnicode_CHECK(unicode));
  644. Py_ssize_t length = PyUnicode_GET_LENGTH(unicode);
  645. if (length == 0) {
  646. PyObject *empty = unicode_get_empty();
  647. if (unicode != empty) {
  648. Py_DECREF(unicode);
  649. Py_INCREF(empty);
  650. }
  651. return empty;
  652. }
  653. if (length == 1) {
  654. int kind = PyUnicode_KIND(unicode);
  655. if (kind == PyUnicode_1BYTE_KIND) {
  656. const Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
  657. Py_UCS1 ch = data[0];
  658. PyObject *latin1_char = LATIN1(ch);
  659. if (unicode != latin1_char) {
  660. Py_INCREF(latin1_char);
  661. Py_DECREF(unicode);
  662. }
  663. return latin1_char;
  664. }
  665. }
  666. assert(_PyUnicode_CheckConsistency(unicode, 1));
  667. return unicode;
  668. }
  669. static PyObject*
  670. unicode_result_unchanged(PyObject *unicode)
  671. {
  672. if (PyUnicode_CheckExact(unicode)) {
  673. return Py_NewRef(unicode);
  674. }
  675. else
  676. /* Subtype -- return genuine unicode string with the same value. */
  677. return _PyUnicode_Copy(unicode);
  678. }
  679. /* Implementation of the "backslashreplace" error handler for 8-bit encodings:
  680. ASCII, Latin1, UTF-8, etc. */
  681. static char*
  682. backslashreplace(_PyBytesWriter *writer, char *str,
  683. PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
  684. {
  685. Py_ssize_t size, i;
  686. Py_UCS4 ch;
  687. int kind;
  688. const void *data;
  689. kind = PyUnicode_KIND(unicode);
  690. data = PyUnicode_DATA(unicode);
  691. size = 0;
  692. /* determine replacement size */
  693. for (i = collstart; i < collend; ++i) {
  694. Py_ssize_t incr;
  695. ch = PyUnicode_READ(kind, data, i);
  696. if (ch < 0x100)
  697. incr = 2+2;
  698. else if (ch < 0x10000)
  699. incr = 2+4;
  700. else {
  701. assert(ch <= MAX_UNICODE);
  702. incr = 2+8;
  703. }
  704. if (size > PY_SSIZE_T_MAX - incr) {
  705. PyErr_SetString(PyExc_OverflowError,
  706. "encoded result is too long for a Python string");
  707. return NULL;
  708. }
  709. size += incr;
  710. }
  711. str = _PyBytesWriter_Prepare(writer, str, size);
  712. if (str == NULL)
  713. return NULL;
  714. /* generate replacement */
  715. for (i = collstart; i < collend; ++i) {
  716. ch = PyUnicode_READ(kind, data, i);
  717. *str++ = '\\';
  718. if (ch >= 0x00010000) {
  719. *str++ = 'U';
  720. *str++ = Py_hexdigits[(ch>>28)&0xf];
  721. *str++ = Py_hexdigits[(ch>>24)&0xf];
  722. *str++ = Py_hexdigits[(ch>>20)&0xf];
  723. *str++ = Py_hexdigits[(ch>>16)&0xf];
  724. *str++ = Py_hexdigits[(ch>>12)&0xf];
  725. *str++ = Py_hexdigits[(ch>>8)&0xf];
  726. }
  727. else if (ch >= 0x100) {
  728. *str++ = 'u';
  729. *str++ = Py_hexdigits[(ch>>12)&0xf];
  730. *str++ = Py_hexdigits[(ch>>8)&0xf];
  731. }
  732. else
  733. *str++ = 'x';
  734. *str++ = Py_hexdigits[(ch>>4)&0xf];
  735. *str++ = Py_hexdigits[ch&0xf];
  736. }
  737. return str;
  738. }
  739. /* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
  740. ASCII, Latin1, UTF-8, etc. */
  741. static char*
  742. xmlcharrefreplace(_PyBytesWriter *writer, char *str,
  743. PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
  744. {
  745. Py_ssize_t size, i;
  746. Py_UCS4 ch;
  747. int kind;
  748. const void *data;
  749. kind = PyUnicode_KIND(unicode);
  750. data = PyUnicode_DATA(unicode);
  751. size = 0;
  752. /* determine replacement size */
  753. for (i = collstart; i < collend; ++i) {
  754. Py_ssize_t incr;
  755. ch = PyUnicode_READ(kind, data, i);
  756. if (ch < 10)
  757. incr = 2+1+1;
  758. else if (ch < 100)
  759. incr = 2+2+1;
  760. else if (ch < 1000)
  761. incr = 2+3+1;
  762. else if (ch < 10000)
  763. incr = 2+4+1;
  764. else if (ch < 100000)
  765. incr = 2+5+1;
  766. else if (ch < 1000000)
  767. incr = 2+6+1;
  768. else {
  769. assert(ch <= MAX_UNICODE);
  770. incr = 2+7+1;
  771. }
  772. if (size > PY_SSIZE_T_MAX - incr) {
  773. PyErr_SetString(PyExc_OverflowError,
  774. "encoded result is too long for a Python string");
  775. return NULL;
  776. }
  777. size += incr;
  778. }
  779. str = _PyBytesWriter_Prepare(writer, str, size);
  780. if (str == NULL)
  781. return NULL;
  782. /* generate replacement */
  783. for (i = collstart; i < collend; ++i) {
  784. size = sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
  785. if (size < 0) {
  786. return NULL;
  787. }
  788. str += size;
  789. }
  790. return str;
  791. }
  792. /* --- Bloom Filters ----------------------------------------------------- */
  793. /* stuff to implement simple "bloom filters" for Unicode characters.
  794. to keep things simple, we use a single bitmask, using the least 5
  795. bits from each unicode characters as the bit index. */
  796. /* the linebreak mask is set up by _PyUnicode_Init() below */
  797. #if LONG_BIT >= 128
  798. #define BLOOM_WIDTH 128
  799. #elif LONG_BIT >= 64
  800. #define BLOOM_WIDTH 64
  801. #elif LONG_BIT >= 32
  802. #define BLOOM_WIDTH 32
  803. #else
  804. #error "LONG_BIT is smaller than 32"
  805. #endif
  806. #define BLOOM_MASK unsigned long
  807. static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
  808. #define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
  809. #define BLOOM_LINEBREAK(ch) \
  810. ((ch) < 128U ? ascii_linebreak[(ch)] : \
  811. (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
  812. static inline BLOOM_MASK
  813. make_bloom_mask(int kind, const void* ptr, Py_ssize_t len)
  814. {
  815. #define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
  816. do { \
  817. TYPE *data = (TYPE *)PTR; \
  818. TYPE *end = data + LEN; \
  819. Py_UCS4 ch; \
  820. for (; data != end; data++) { \
  821. ch = *data; \
  822. MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
  823. } \
  824. break; \
  825. } while (0)
  826. /* calculate simple bloom-style bitmask for a given unicode string */
  827. BLOOM_MASK mask;
  828. mask = 0;
  829. switch (kind) {
  830. case PyUnicode_1BYTE_KIND:
  831. BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
  832. break;
  833. case PyUnicode_2BYTE_KIND:
  834. BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
  835. break;
  836. case PyUnicode_4BYTE_KIND:
  837. BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
  838. break;
  839. default:
  840. Py_UNREACHABLE();
  841. }
  842. return mask;
  843. #undef BLOOM_UPDATE
  844. }
  845. static int
  846. ensure_unicode(PyObject *obj)
  847. {
  848. if (!PyUnicode_Check(obj)) {
  849. PyErr_Format(PyExc_TypeError,
  850. "must be str, not %.100s",
  851. Py_TYPE(obj)->tp_name);
  852. return -1;
  853. }
  854. return 0;
  855. }
  856. /* Compilation of templated routines */
  857. #define STRINGLIB_GET_EMPTY() unicode_get_empty()
  858. #include "stringlib/asciilib.h"
  859. #include "stringlib/fastsearch.h"
  860. #include "stringlib/partition.h"
  861. #include "stringlib/split.h"
  862. #include "stringlib/count.h"
  863. #include "stringlib/find.h"
  864. #include "stringlib/find_max_char.h"
  865. #include "stringlib/undef.h"
  866. #include "stringlib/ucs1lib.h"
  867. #include "stringlib/fastsearch.h"
  868. #include "stringlib/partition.h"
  869. #include "stringlib/split.h"
  870. #include "stringlib/count.h"
  871. #include "stringlib/find.h"
  872. #include "stringlib/replace.h"
  873. #include "stringlib/find_max_char.h"
  874. #include "stringlib/undef.h"
  875. #include "stringlib/ucs2lib.h"
  876. #include "stringlib/fastsearch.h"
  877. #include "stringlib/partition.h"
  878. #include "stringlib/split.h"
  879. #include "stringlib/count.h"
  880. #include "stringlib/find.h"
  881. #include "stringlib/replace.h"
  882. #include "stringlib/find_max_char.h"
  883. #include "stringlib/undef.h"
  884. #include "stringlib/ucs4lib.h"
  885. #include "stringlib/fastsearch.h"
  886. #include "stringlib/partition.h"
  887. #include "stringlib/split.h"
  888. #include "stringlib/count.h"
  889. #include "stringlib/find.h"
  890. #include "stringlib/replace.h"
  891. #include "stringlib/find_max_char.h"
  892. #include "stringlib/undef.h"
  893. #undef STRINGLIB_GET_EMPTY
  894. /* --- Unicode Object ----------------------------------------------------- */
  895. static inline Py_ssize_t
  896. findchar(const void *s, int kind,
  897. Py_ssize_t size, Py_UCS4 ch,
  898. int direction)
  899. {
  900. switch (kind) {
  901. case PyUnicode_1BYTE_KIND:
  902. if ((Py_UCS1) ch != ch)
  903. return -1;
  904. if (direction > 0)
  905. return ucs1lib_find_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
  906. else
  907. return ucs1lib_rfind_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
  908. case PyUnicode_2BYTE_KIND:
  909. if ((Py_UCS2) ch != ch)
  910. return -1;
  911. if (direction > 0)
  912. return ucs2lib_find_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
  913. else
  914. return ucs2lib_rfind_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
  915. case PyUnicode_4BYTE_KIND:
  916. if (direction > 0)
  917. return ucs4lib_find_char((const Py_UCS4 *) s, size, ch);
  918. else
  919. return ucs4lib_rfind_char((const Py_UCS4 *) s, size, ch);
  920. default:
  921. Py_UNREACHABLE();
  922. }
  923. }
  924. #ifdef Py_DEBUG
  925. /* Fill the data of a Unicode string with invalid characters to detect bugs
  926. earlier.
  927. _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
  928. ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
  929. invalid character in Unicode 6.0. */
  930. static void
  931. unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
  932. {
  933. int kind = PyUnicode_KIND(unicode);
  934. Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
  935. Py_ssize_t length = _PyUnicode_LENGTH(unicode);
  936. if (length <= old_length)
  937. return;
  938. memset(data + old_length * kind, 0xff, (length - old_length) * kind);
  939. }
  940. #endif
  941. static PyObject*
  942. resize_compact(PyObject *unicode, Py_ssize_t length)
  943. {
  944. Py_ssize_t char_size;
  945. Py_ssize_t struct_size;
  946. Py_ssize_t new_size;
  947. PyObject *new_unicode;
  948. #ifdef Py_DEBUG
  949. Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
  950. #endif
  951. assert(unicode_modifiable(unicode));
  952. assert(PyUnicode_IS_COMPACT(unicode));
  953. char_size = PyUnicode_KIND(unicode);
  954. if (PyUnicode_IS_ASCII(unicode))
  955. struct_size = sizeof(PyASCIIObject);
  956. else
  957. struct_size = sizeof(PyCompactUnicodeObject);
  958. if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
  959. PyErr_NoMemory();
  960. return NULL;
  961. }
  962. new_size = (struct_size + (length + 1) * char_size);
  963. if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
  964. PyObject_Free(_PyUnicode_UTF8(unicode));
  965. _PyUnicode_UTF8(unicode) = NULL;
  966. _PyUnicode_UTF8_LENGTH(unicode) = 0;
  967. }
  968. #ifdef Py_TRACE_REFS
  969. _Py_ForgetReference(unicode);
  970. #endif
  971. new_unicode = (PyObject *)PyObject_Realloc(unicode, new_size);
  972. if (new_unicode == NULL) {
  973. _Py_NewReferenceNoTotal(unicode);
  974. PyErr_NoMemory();
  975. return NULL;
  976. }
  977. unicode = new_unicode;
  978. _Py_NewReferenceNoTotal(unicode);
  979. _PyUnicode_LENGTH(unicode) = length;
  980. #ifdef Py_DEBUG
  981. unicode_fill_invalid(unicode, old_length);
  982. #endif
  983. PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
  984. length, 0);
  985. assert(_PyUnicode_CheckConsistency(unicode, 0));
  986. return unicode;
  987. }
  988. static int
  989. resize_inplace(PyObject *unicode, Py_ssize_t length)
  990. {
  991. assert(!PyUnicode_IS_COMPACT(unicode));
  992. assert(Py_REFCNT(unicode) == 1);
  993. Py_ssize_t new_size;
  994. Py_ssize_t char_size;
  995. int share_utf8;
  996. void *data;
  997. #ifdef Py_DEBUG
  998. Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
  999. #endif
  1000. data = _PyUnicode_DATA_ANY(unicode);
  1001. char_size = PyUnicode_KIND(unicode);
  1002. share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
  1003. if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
  1004. PyErr_NoMemory();
  1005. return -1;
  1006. }
  1007. new_size = (length + 1) * char_size;
  1008. if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
  1009. {
  1010. PyObject_Free(_PyUnicode_UTF8(unicode));
  1011. _PyUnicode_UTF8(unicode) = NULL;
  1012. _PyUnicode_UTF8_LENGTH(unicode) = 0;
  1013. }
  1014. data = (PyObject *)PyObject_Realloc(data, new_size);
  1015. if (data == NULL) {
  1016. PyErr_NoMemory();
  1017. return -1;
  1018. }
  1019. _PyUnicode_DATA_ANY(unicode) = data;
  1020. if (share_utf8) {
  1021. _PyUnicode_UTF8(unicode) = data;
  1022. _PyUnicode_UTF8_LENGTH(unicode) = length;
  1023. }
  1024. _PyUnicode_LENGTH(unicode) = length;
  1025. PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
  1026. #ifdef Py_DEBUG
  1027. unicode_fill_invalid(unicode, old_length);
  1028. #endif
  1029. /* check for integer overflow */
  1030. if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
  1031. PyErr_NoMemory();
  1032. return -1;
  1033. }
  1034. assert(_PyUnicode_CheckConsistency(unicode, 0));
  1035. return 0;
  1036. }
  1037. static PyObject*
  1038. resize_copy(PyObject *unicode, Py_ssize_t length)
  1039. {
  1040. Py_ssize_t copy_length;
  1041. PyObject *copy;
  1042. copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
  1043. if (copy == NULL)
  1044. return NULL;
  1045. copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
  1046. _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
  1047. return copy;
  1048. }
  1049. static const char*
  1050. unicode_kind_name(PyObject *unicode)
  1051. {
  1052. /* don't check consistency: unicode_kind_name() is called from
  1053. _PyUnicode_Dump() */
  1054. if (!PyUnicode_IS_COMPACT(unicode))
  1055. {
  1056. switch (PyUnicode_KIND(unicode))
  1057. {
  1058. case PyUnicode_1BYTE_KIND:
  1059. if (PyUnicode_IS_ASCII(unicode))
  1060. return "legacy ascii";
  1061. else
  1062. return "legacy latin1";
  1063. case PyUnicode_2BYTE_KIND:
  1064. return "legacy UCS2";
  1065. case PyUnicode_4BYTE_KIND:
  1066. return "legacy UCS4";
  1067. default:
  1068. return "<legacy invalid kind>";
  1069. }
  1070. }
  1071. switch (PyUnicode_KIND(unicode)) {
  1072. case PyUnicode_1BYTE_KIND:
  1073. if (PyUnicode_IS_ASCII(unicode))
  1074. return "ascii";
  1075. else
  1076. return "latin1";
  1077. case PyUnicode_2BYTE_KIND:
  1078. return "UCS2";
  1079. case PyUnicode_4BYTE_KIND:
  1080. return "UCS4";
  1081. default:
  1082. return "<invalid compact kind>";
  1083. }
  1084. }
  1085. #ifdef Py_DEBUG
  1086. /* Functions wrapping macros for use in debugger */
  1087. const char *_PyUnicode_utf8(void *unicode_raw){
  1088. PyObject *unicode = _PyObject_CAST(unicode_raw);
  1089. return PyUnicode_UTF8(unicode);
  1090. }
  1091. const void *_PyUnicode_compact_data(void *unicode_raw) {
  1092. PyObject *unicode = _PyObject_CAST(unicode_raw);
  1093. return _PyUnicode_COMPACT_DATA(unicode);
  1094. }
  1095. const void *_PyUnicode_data(void *unicode_raw) {
  1096. PyObject *unicode = _PyObject_CAST(unicode_raw);
  1097. printf("obj %p\n", (void*)unicode);
  1098. printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
  1099. printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
  1100. printf("ascii op %p\n", (void*)(_PyASCIIObject_CAST(unicode) + 1));
  1101. printf("compact op %p\n", (void*)(_PyCompactUnicodeObject_CAST(unicode) + 1));
  1102. printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
  1103. return PyUnicode_DATA(unicode);
  1104. }
  1105. void
  1106. _PyUnicode_Dump(PyObject *op)
  1107. {
  1108. PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
  1109. PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
  1110. PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
  1111. const void *data;
  1112. if (ascii->state.compact)
  1113. {
  1114. if (ascii->state.ascii)
  1115. data = (ascii + 1);
  1116. else
  1117. data = (compact + 1);
  1118. }
  1119. else
  1120. data = unicode->data.any;
  1121. printf("%s: len=%zu, ", unicode_kind_name(op), ascii->length);
  1122. if (!ascii->state.ascii) {
  1123. printf("utf8=%p (%zu)", (void *)compact->utf8, compact->utf8_length);
  1124. }
  1125. printf(", data=%p\n", data);
  1126. }
  1127. #endif
  1128. PyObject *
  1129. PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
  1130. {
  1131. /* Optimization for empty strings */
  1132. if (size == 0) {
  1133. return unicode_new_empty();
  1134. }
  1135. PyObject *obj;
  1136. PyCompactUnicodeObject *unicode;
  1137. void *data;
  1138. int kind;
  1139. int is_ascii;
  1140. Py_ssize_t char_size;
  1141. Py_ssize_t struct_size;
  1142. is_ascii = 0;
  1143. struct_size = sizeof(PyCompactUnicodeObject);
  1144. if (maxchar < 128) {
  1145. kind = PyUnicode_1BYTE_KIND;
  1146. char_size = 1;
  1147. is_ascii = 1;
  1148. struct_size = sizeof(PyASCIIObject);
  1149. }
  1150. else if (maxchar < 256) {
  1151. kind = PyUnicode_1BYTE_KIND;
  1152. char_size = 1;
  1153. }
  1154. else if (maxchar < 65536) {
  1155. kind = PyUnicode_2BYTE_KIND;
  1156. char_size = 2;
  1157. }
  1158. else {
  1159. if (maxchar > MAX_UNICODE) {
  1160. PyErr_SetString(PyExc_SystemError,
  1161. "invalid maximum character passed to PyUnicode_New");
  1162. return NULL;
  1163. }
  1164. kind = PyUnicode_4BYTE_KIND;
  1165. char_size = 4;
  1166. }
  1167. /* Ensure we won't overflow the size. */
  1168. if (size < 0) {
  1169. PyErr_SetString(PyExc_SystemError,
  1170. "Negative size passed to PyUnicode_New");
  1171. return NULL;
  1172. }
  1173. if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
  1174. return PyErr_NoMemory();
  1175. /* Duplicated allocation code from _PyObject_New() instead of a call to
  1176. * PyObject_New() so we are able to allocate space for the object and
  1177. * it's data buffer.
  1178. */
  1179. obj = (PyObject *) PyObject_Malloc(struct_size + (size + 1) * char_size);
  1180. if (obj == NULL) {
  1181. return PyErr_NoMemory();
  1182. }
  1183. _PyObject_Init(obj, &PyUnicode_Type);
  1184. unicode = (PyCompactUnicodeObject *)obj;
  1185. if (is_ascii)
  1186. data = ((PyASCIIObject*)obj) + 1;
  1187. else
  1188. data = unicode + 1;
  1189. _PyUnicode_LENGTH(unicode) = size;
  1190. _PyUnicode_HASH(unicode) = -1;
  1191. _PyUnicode_STATE(unicode).interned = 0;
  1192. _PyUnicode_STATE(unicode).kind = kind;
  1193. _PyUnicode_STATE(unicode).compact = 1;
  1194. _PyUnicode_STATE(unicode).ascii = is_ascii;
  1195. _PyUnicode_STATE(unicode).statically_allocated = 0;
  1196. if (is_ascii) {
  1197. ((char*)data)[size] = 0;
  1198. }
  1199. else if (kind == PyUnicode_1BYTE_KIND) {
  1200. ((char*)data)[size] = 0;
  1201. unicode->utf8 = NULL;
  1202. unicode->utf8_length = 0;
  1203. }
  1204. else {
  1205. unicode->utf8 = NULL;
  1206. unicode->utf8_length = 0;
  1207. if (kind == PyUnicode_2BYTE_KIND)
  1208. ((Py_UCS2*)data)[size] = 0;
  1209. else /* kind == PyUnicode_4BYTE_KIND */
  1210. ((Py_UCS4*)data)[size] = 0;
  1211. }
  1212. #ifdef Py_DEBUG
  1213. unicode_fill_invalid((PyObject*)unicode, 0);
  1214. #endif
  1215. assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
  1216. return obj;
  1217. }
  1218. #if SIZEOF_WCHAR_T == 2
  1219. /* Helper function to convert a 16-bits wchar_t representation to UCS4, this
  1220. will decode surrogate pairs, the other conversions are implemented as macros
  1221. for efficiency.
  1222. This function assumes that unicode can hold one more code point than wstr
  1223. characters for a terminating null character. */
  1224. static void
  1225. unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
  1226. PyObject *unicode)
  1227. {
  1228. const wchar_t *iter;
  1229. Py_UCS4 *ucs4_out;
  1230. assert(unicode != NULL);
  1231. assert(_PyUnicode_CHECK(unicode));
  1232. assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
  1233. ucs4_out = PyUnicode_4BYTE_DATA(unicode);
  1234. for (iter = begin; iter < end; ) {
  1235. assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
  1236. _PyUnicode_GET_LENGTH(unicode)));
  1237. if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
  1238. && (iter+1) < end
  1239. && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
  1240. {
  1241. *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
  1242. iter += 2;
  1243. }
  1244. else {
  1245. *ucs4_out++ = *iter;
  1246. iter++;
  1247. }
  1248. }
  1249. assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
  1250. _PyUnicode_GET_LENGTH(unicode)));
  1251. }
  1252. #endif
  1253. static int
  1254. unicode_check_modifiable(PyObject *unicode)
  1255. {
  1256. if (!unicode_modifiable(unicode)) {
  1257. PyErr_SetString(PyExc_SystemError,
  1258. "Cannot modify a string currently used");
  1259. return -1;
  1260. }
  1261. return 0;
  1262. }
  1263. static int
  1264. _copy_characters(PyObject *to, Py_ssize_t to_start,
  1265. PyObject *from, Py_ssize_t from_start,
  1266. Py_ssize_t how_many, int check_maxchar)
  1267. {
  1268. int from_kind, to_kind;
  1269. const void *from_data;
  1270. void *to_data;
  1271. assert(0 <= how_many);
  1272. assert(0 <= from_start);
  1273. assert(0 <= to_start);
  1274. assert(PyUnicode_Check(from));
  1275. assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
  1276. assert(PyUnicode_Check(to));
  1277. assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
  1278. if (how_many == 0)
  1279. return 0;
  1280. from_kind = PyUnicode_KIND(from);
  1281. from_data = PyUnicode_DATA(from);
  1282. to_kind = PyUnicode_KIND(to);
  1283. to_data = PyUnicode_DATA(to);
  1284. #ifdef Py_DEBUG
  1285. if (!check_maxchar
  1286. && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
  1287. {
  1288. Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
  1289. Py_UCS4 ch;
  1290. Py_ssize_t i;
  1291. for (i=0; i < how_many; i++) {
  1292. ch = PyUnicode_READ(from_kind, from_data, from_start + i);
  1293. assert(ch <= to_maxchar);
  1294. }
  1295. }
  1296. #endif
  1297. if (from_kind == to_kind) {
  1298. if (check_maxchar
  1299. && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
  1300. {
  1301. /* Writing Latin-1 characters into an ASCII string requires to
  1302. check that all written characters are pure ASCII */
  1303. Py_UCS4 max_char;
  1304. max_char = ucs1lib_find_max_char(from_data,
  1305. (const Py_UCS1*)from_data + how_many);
  1306. if (max_char >= 128)
  1307. return -1;
  1308. }
  1309. memcpy((char*)to_data + to_kind * to_start,
  1310. (const char*)from_data + from_kind * from_start,
  1311. to_kind * how_many);
  1312. }
  1313. else if (from_kind == PyUnicode_1BYTE_KIND
  1314. && to_kind == PyUnicode_2BYTE_KIND)
  1315. {
  1316. _PyUnicode_CONVERT_BYTES(
  1317. Py_UCS1, Py_UCS2,
  1318. PyUnicode_1BYTE_DATA(from) + from_start,
  1319. PyUnicode_1BYTE_DATA(from) + from_start + how_many,
  1320. PyUnicode_2BYTE_DATA(to) + to_start
  1321. );
  1322. }
  1323. else if (from_kind == PyUnicode_1BYTE_KIND
  1324. && to_kind == PyUnicode_4BYTE_KIND)
  1325. {
  1326. _PyUnicode_CONVERT_BYTES(
  1327. Py_UCS1, Py_UCS4,
  1328. PyUnicode_1BYTE_DATA(from) + from_start,
  1329. PyUnicode_1BYTE_DATA(from) + from_start + how_many,
  1330. PyUnicode_4BYTE_DATA(to) + to_start
  1331. );
  1332. }
  1333. else if (from_kind == PyUnicode_2BYTE_KIND
  1334. && to_kind == PyUnicode_4BYTE_KIND)
  1335. {
  1336. _PyUnicode_CONVERT_BYTES(
  1337. Py_UCS2, Py_UCS4,
  1338. PyUnicode_2BYTE_DATA(from) + from_start,
  1339. PyUnicode_2BYTE_DATA(from) + from_start + how_many,
  1340. PyUnicode_4BYTE_DATA(to) + to_start
  1341. );
  1342. }
  1343. else {
  1344. assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
  1345. if (!check_maxchar) {
  1346. if (from_kind == PyUnicode_2BYTE_KIND
  1347. && to_kind == PyUnicode_1BYTE_KIND)
  1348. {
  1349. _PyUnicode_CONVERT_BYTES(
  1350. Py_UCS2, Py_UCS1,
  1351. PyUnicode_2BYTE_DATA(from) + from_start,
  1352. PyUnicode_2BYTE_DATA(from) + from_start + how_many,
  1353. PyUnicode_1BYTE_DATA(to) + to_start
  1354. );
  1355. }
  1356. else if (from_kind == PyUnicode_4BYTE_KIND
  1357. && to_kind == PyUnicode_1BYTE_KIND)
  1358. {
  1359. _PyUnicode_CONVERT_BYTES(
  1360. Py_UCS4, Py_UCS1,
  1361. PyUnicode_4BYTE_DATA(from) + from_start,
  1362. PyUnicode_4BYTE_DATA(from) + from_start + how_many,
  1363. PyUnicode_1BYTE_DATA(to) + to_start
  1364. );
  1365. }
  1366. else if (from_kind == PyUnicode_4BYTE_KIND
  1367. && to_kind == PyUnicode_2BYTE_KIND)
  1368. {
  1369. _PyUnicode_CONVERT_BYTES(
  1370. Py_UCS4, Py_UCS2,
  1371. PyUnicode_4BYTE_DATA(from) + from_start,
  1372. PyUnicode_4BYTE_DATA(from) + from_start + how_many,
  1373. PyUnicode_2BYTE_DATA(to) + to_start
  1374. );
  1375. }
  1376. else {
  1377. Py_UNREACHABLE();
  1378. }
  1379. }
  1380. else {
  1381. const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
  1382. Py_UCS4 ch;
  1383. Py_ssize_t i;
  1384. for (i=0; i < how_many; i++) {
  1385. ch = PyUnicode_READ(from_kind, from_data, from_start + i);
  1386. if (ch > to_maxchar)
  1387. return -1;
  1388. PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
  1389. }
  1390. }
  1391. }
  1392. return 0;
  1393. }
  1394. void
  1395. _PyUnicode_FastCopyCharacters(
  1396. PyObject *to, Py_ssize_t to_start,
  1397. PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
  1398. {
  1399. (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
  1400. }
  1401. Py_ssize_t
  1402. PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
  1403. PyObject *from, Py_ssize_t from_start,
  1404. Py_ssize_t how_many)
  1405. {
  1406. int err;
  1407. if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
  1408. PyErr_BadInternalCall();
  1409. return -1;
  1410. }
  1411. if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
  1412. PyErr_SetString(PyExc_IndexError, "string index out of range");
  1413. return -1;
  1414. }
  1415. if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
  1416. PyErr_SetString(PyExc_IndexError, "string index out of range");
  1417. return -1;
  1418. }
  1419. if (how_many < 0) {
  1420. PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
  1421. return -1;
  1422. }
  1423. how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
  1424. if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
  1425. PyErr_Format(PyExc_SystemError,
  1426. "Cannot write %zi characters at %zi "
  1427. "in a string of %zi characters",
  1428. how_many, to_start, PyUnicode_GET_LENGTH(to));
  1429. return -1;
  1430. }
  1431. if (how_many == 0)
  1432. return 0;
  1433. if (unicode_check_modifiable(to))
  1434. return -1;
  1435. err = _copy_characters(to, to_start, from, from_start, how_many, 1);
  1436. if (err) {
  1437. PyErr_Format(PyExc_SystemError,
  1438. "Cannot copy %s characters "
  1439. "into a string of %s characters",
  1440. unicode_kind_name(from),
  1441. unicode_kind_name(to));
  1442. return -1;
  1443. }
  1444. return how_many;
  1445. }
  1446. /* Find the maximum code point and count the number of surrogate pairs so a
  1447. correct string length can be computed before converting a string to UCS4.
  1448. This function counts single surrogates as a character and not as a pair.
  1449. Return 0 on success, or -1 on error. */
  1450. static int
  1451. find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
  1452. Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
  1453. {
  1454. const wchar_t *iter;
  1455. Py_UCS4 ch;
  1456. assert(num_surrogates != NULL && maxchar != NULL);
  1457. *num_surrogates = 0;
  1458. *maxchar = 0;
  1459. for (iter = begin; iter < end; ) {
  1460. #if SIZEOF_WCHAR_T == 2
  1461. if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
  1462. && (iter+1) < end
  1463. && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
  1464. {
  1465. ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
  1466. ++(*num_surrogates);
  1467. iter += 2;
  1468. }
  1469. else
  1470. #endif
  1471. {
  1472. ch = *iter;
  1473. iter++;
  1474. }
  1475. if (ch > *maxchar) {
  1476. *maxchar = ch;
  1477. if (*maxchar > MAX_UNICODE) {
  1478. PyErr_Format(PyExc_ValueError,
  1479. "character U+%x is not in range [U+0000; U+%x]",
  1480. ch, MAX_UNICODE);
  1481. return -1;
  1482. }
  1483. }
  1484. }
  1485. return 0;
  1486. }
  1487. static void
  1488. unicode_dealloc(PyObject *unicode)
  1489. {
  1490. #ifdef Py_DEBUG
  1491. if (!unicode_is_finalizing() && unicode_is_singleton(unicode)) {
  1492. _Py_FatalRefcountError("deallocating an Unicode singleton");
  1493. }
  1494. #endif
  1495. if (_PyUnicode_STATE(unicode).statically_allocated) {
  1496. /* This should never get called, but we also don't want to SEGV if
  1497. * we accidentally decref an immortal string out of existence. Since
  1498. * the string is an immortal object, just re-set the reference count.
  1499. */
  1500. #ifdef Py_DEBUG
  1501. Py_UNREACHABLE();
  1502. #endif
  1503. _Py_SetImmortal(unicode);
  1504. return;
  1505. }
  1506. switch (_PyUnicode_STATE(unicode).interned) {
  1507. case SSTATE_NOT_INTERNED:
  1508. break;
  1509. case SSTATE_INTERNED_MORTAL:
  1510. /* Remove the object from the intern dict.
  1511. * Before doing so, we set the refcount to 3: the key and value
  1512. * in the interned_dict, plus one to work with.
  1513. */
  1514. assert(Py_REFCNT(unicode) == 0);
  1515. Py_SET_REFCNT(unicode, 3);
  1516. #ifdef Py_REF_DEBUG
  1517. /* let's be pedantic with the ref total */
  1518. _Py_IncRefTotal(_PyInterpreterState_GET());
  1519. _Py_IncRefTotal(_PyInterpreterState_GET());
  1520. _Py_IncRefTotal(_PyInterpreterState_GET());
  1521. #endif
  1522. PyInterpreterState *interp = _PyInterpreterState_GET();
  1523. PyObject *interned = get_interned_dict(interp);
  1524. assert(interned != NULL);
  1525. int r = PyDict_DelItem(interned, unicode);
  1526. if (r == -1) {
  1527. PyErr_WriteUnraisable(unicode);
  1528. // We don't know what happened to the string. It's probably
  1529. // best to leak it:
  1530. // - if it was not found, something is very wrong
  1531. // - if it was deleted, there are no more references to it
  1532. // so it can't cause trouble (except wasted memory)
  1533. // - if it wasn't deleted, it'll remain interned
  1534. _Py_SetImmortal(unicode);
  1535. _PyUnicode_STATE(unicode).interned = SSTATE_INTERNED_IMMORTAL;
  1536. return;
  1537. }
  1538. // Only our work reference should be left; remove it too.
  1539. assert(Py_REFCNT(unicode) == 1);
  1540. Py_SET_REFCNT(unicode, 0);
  1541. #ifdef Py_REF_DEBUG
  1542. /* let's be pedantic with the ref total */
  1543. _Py_DecRefTotal(_PyInterpreterState_GET());
  1544. #endif
  1545. break;
  1546. default:
  1547. // As with `statically_allocated` above.
  1548. #ifdef Py_REF_DEBUG
  1549. Py_UNREACHABLE();
  1550. #endif
  1551. _Py_SetImmortal(unicode);
  1552. return;
  1553. }
  1554. if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
  1555. PyObject_Free(_PyUnicode_UTF8(unicode));
  1556. }
  1557. if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode)) {
  1558. PyObject_Free(_PyUnicode_DATA_ANY(unicode));
  1559. }
  1560. Py_TYPE(unicode)->tp_free(unicode);
  1561. }
  1562. #ifdef Py_DEBUG
  1563. static int
  1564. unicode_is_singleton(PyObject *unicode)
  1565. {
  1566. if (unicode == &_Py_STR(empty)) {
  1567. return 1;
  1568. }
  1569. PyASCIIObject *ascii = _PyASCIIObject_CAST(unicode);
  1570. if (ascii->length == 1) {
  1571. Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
  1572. if (ch < 256 && LATIN1(ch) == unicode) {
  1573. return 1;
  1574. }
  1575. }
  1576. return 0;
  1577. }
  1578. #endif
  1579. static int
  1580. unicode_modifiable(PyObject *unicode)
  1581. {
  1582. assert(_PyUnicode_CHECK(unicode));
  1583. if (Py_REFCNT(unicode) != 1)
  1584. return 0;
  1585. if (_PyUnicode_HASH(unicode) != -1)
  1586. return 0;
  1587. if (PyUnicode_CHECK_INTERNED(unicode))
  1588. return 0;
  1589. if (!PyUnicode_CheckExact(unicode))
  1590. return 0;
  1591. #ifdef Py_DEBUG
  1592. /* singleton refcount is greater than 1 */
  1593. assert(!unicode_is_singleton(unicode));
  1594. #endif
  1595. return 1;
  1596. }
  1597. static int
  1598. unicode_resize(PyObject **p_unicode, Py_ssize_t length)
  1599. {
  1600. PyObject *unicode;
  1601. Py_ssize_t old_length;
  1602. assert(p_unicode != NULL);
  1603. unicode = *p_unicode;
  1604. assert(unicode != NULL);
  1605. assert(PyUnicode_Check(unicode));
  1606. assert(0 <= length);
  1607. old_length = PyUnicode_GET_LENGTH(unicode);
  1608. if (old_length == length)
  1609. return 0;
  1610. if (length == 0) {
  1611. PyObject *empty = unicode_new_empty();
  1612. Py_SETREF(*p_unicode, empty);
  1613. return 0;
  1614. }
  1615. if (!unicode_modifiable(unicode)) {
  1616. PyObject *copy = resize_copy(unicode, length);
  1617. if (copy == NULL)
  1618. return -1;
  1619. Py_SETREF(*p_unicode, copy);
  1620. return 0;
  1621. }
  1622. if (PyUnicode_IS_COMPACT(unicode)) {
  1623. PyObject *new_unicode = resize_compact(unicode, length);
  1624. if (new_unicode == NULL)
  1625. return -1;
  1626. *p_unicode = new_unicode;
  1627. return 0;
  1628. }
  1629. return resize_inplace(unicode, length);
  1630. }
  1631. int
  1632. PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
  1633. {
  1634. PyObject *unicode;
  1635. if (p_unicode == NULL) {
  1636. PyErr_BadInternalCall();
  1637. return -1;
  1638. }
  1639. unicode = *p_unicode;
  1640. if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
  1641. {
  1642. PyErr_BadInternalCall();
  1643. return -1;
  1644. }
  1645. return unicode_resize(p_unicode, length);
  1646. }
  1647. /* Copy an ASCII or latin1 char* string into a Python Unicode string.
  1648. WARNING: The function doesn't copy the terminating null character and
  1649. doesn't check the maximum character (may write a latin1 character in an
  1650. ASCII string). */
  1651. static void
  1652. unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
  1653. const char *str, Py_ssize_t len)
  1654. {
  1655. int kind = PyUnicode_KIND(unicode);
  1656. const void *data = PyUnicode_DATA(unicode);
  1657. const char *end = str + len;
  1658. assert(index + len <= PyUnicode_GET_LENGTH(unicode));
  1659. switch (kind) {
  1660. case PyUnicode_1BYTE_KIND: {
  1661. #ifdef Py_DEBUG
  1662. if (PyUnicode_IS_ASCII(unicode)) {
  1663. Py_UCS4 maxchar = ucs1lib_find_max_char(
  1664. (const Py_UCS1*)str,
  1665. (const Py_UCS1*)str + len);
  1666. assert(maxchar < 128);
  1667. }
  1668. #endif
  1669. memcpy((char *) data + index, str, len);
  1670. break;
  1671. }
  1672. case PyUnicode_2BYTE_KIND: {
  1673. Py_UCS2 *start = (Py_UCS2 *)data + index;
  1674. Py_UCS2 *ucs2 = start;
  1675. for (; str < end; ++ucs2, ++str)
  1676. *ucs2 = (Py_UCS2)*str;
  1677. assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
  1678. break;
  1679. }
  1680. case PyUnicode_4BYTE_KIND: {
  1681. Py_UCS4 *start = (Py_UCS4 *)data + index;
  1682. Py_UCS4 *ucs4 = start;
  1683. for (; str < end; ++ucs4, ++str)
  1684. *ucs4 = (Py_UCS4)*str;
  1685. assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
  1686. break;
  1687. }
  1688. default:
  1689. Py_UNREACHABLE();
  1690. }
  1691. }
  1692. static PyObject*
  1693. get_latin1_char(Py_UCS1 ch)
  1694. {
  1695. PyObject *o = LATIN1(ch);
  1696. return o;
  1697. }
  1698. static PyObject*
  1699. unicode_char(Py_UCS4 ch)
  1700. {
  1701. PyObject *unicode;
  1702. assert(ch <= MAX_UNICODE);
  1703. if (ch < 256) {
  1704. return get_latin1_char(ch);
  1705. }
  1706. unicode = PyUnicode_New(1, ch);
  1707. if (unicode == NULL)
  1708. return NULL;
  1709. assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
  1710. if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
  1711. PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
  1712. } else {
  1713. assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
  1714. PyUnicode_4BYTE_DATA(unicode)[0] = ch;
  1715. }
  1716. assert(_PyUnicode_CheckConsistency(unicode, 1));
  1717. return unicode;
  1718. }
  1719. PyObject *
  1720. PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
  1721. {
  1722. PyObject *unicode;
  1723. Py_UCS4 maxchar = 0;
  1724. Py_ssize_t num_surrogates;
  1725. if (u == NULL && size != 0) {
  1726. PyErr_BadInternalCall();
  1727. return NULL;
  1728. }
  1729. if (size == -1) {
  1730. size = wcslen(u);
  1731. }
  1732. /* If the Unicode data is known at construction time, we can apply
  1733. some optimizations which share commonly used objects. */
  1734. /* Optimization for empty strings */
  1735. if (size == 0)
  1736. _Py_RETURN_UNICODE_EMPTY();
  1737. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  1738. /* Oracle Solaris uses non-Unicode internal wchar_t form for
  1739. non-Unicode locales and hence needs conversion to UCS-4 first. */
  1740. if (_Py_LocaleUsesNonUnicodeWchar()) {
  1741. wchar_t* converted = _Py_DecodeNonUnicodeWchar(u, size);
  1742. if (!converted) {
  1743. return NULL;
  1744. }
  1745. PyObject *unicode = _PyUnicode_FromUCS4(converted, size);
  1746. PyMem_Free(converted);
  1747. return unicode;
  1748. }
  1749. #endif
  1750. /* Single character Unicode objects in the Latin-1 range are
  1751. shared when using this constructor */
  1752. if (size == 1 && (Py_UCS4)*u < 256)
  1753. return get_latin1_char((unsigned char)*u);
  1754. /* If not empty and not single character, copy the Unicode data
  1755. into the new object */
  1756. if (find_maxchar_surrogates(u, u + size,
  1757. &maxchar, &num_surrogates) == -1)
  1758. return NULL;
  1759. unicode = PyUnicode_New(size - num_surrogates, maxchar);
  1760. if (!unicode)
  1761. return NULL;
  1762. switch (PyUnicode_KIND(unicode)) {
  1763. case PyUnicode_1BYTE_KIND:
  1764. _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
  1765. u, u + size, PyUnicode_1BYTE_DATA(unicode));
  1766. break;
  1767. case PyUnicode_2BYTE_KIND:
  1768. #if Py_UNICODE_SIZE == 2
  1769. memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
  1770. #else
  1771. _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
  1772. u, u + size, PyUnicode_2BYTE_DATA(unicode));
  1773. #endif
  1774. break;
  1775. case PyUnicode_4BYTE_KIND:
  1776. #if SIZEOF_WCHAR_T == 2
  1777. /* This is the only case which has to process surrogates, thus
  1778. a simple copy loop is not enough and we need a function. */
  1779. unicode_convert_wchar_to_ucs4(u, u + size, unicode);
  1780. #else
  1781. assert(num_surrogates == 0);
  1782. memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
  1783. #endif
  1784. break;
  1785. default:
  1786. Py_UNREACHABLE();
  1787. }
  1788. return unicode_result(unicode);
  1789. }
  1790. PyObject *
  1791. PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
  1792. {
  1793. if (size < 0) {
  1794. PyErr_SetString(PyExc_SystemError,
  1795. "Negative size passed to PyUnicode_FromStringAndSize");
  1796. return NULL;
  1797. }
  1798. if (u != NULL) {
  1799. return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
  1800. }
  1801. if (size > 0) {
  1802. PyErr_SetString(PyExc_SystemError,
  1803. "NULL string with positive size with NULL passed to PyUnicode_FromStringAndSize");
  1804. return NULL;
  1805. }
  1806. return unicode_new_empty();
  1807. }
  1808. PyObject *
  1809. PyUnicode_FromString(const char *u)
  1810. {
  1811. #if defined(__has_feature)
  1812. # if __has_feature(memory_sanitizer)
  1813. __msan_unpoison_string(u);
  1814. # endif
  1815. #endif
  1816. size_t size = strlen(u);
  1817. if (size > PY_SSIZE_T_MAX) {
  1818. PyErr_SetString(PyExc_OverflowError, "input too long");
  1819. return NULL;
  1820. }
  1821. return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
  1822. }
  1823. PyObject *
  1824. _PyUnicode_FromId(_Py_Identifier *id)
  1825. {
  1826. PyInterpreterState *interp = _PyInterpreterState_GET();
  1827. struct _Py_unicode_ids *ids = &interp->unicode.ids;
  1828. Py_ssize_t index = _Py_atomic_size_get(&id->index);
  1829. if (index < 0) {
  1830. struct _Py_unicode_runtime_ids *rt_ids = &interp->runtime->unicode_state.ids;
  1831. PyThread_acquire_lock(rt_ids->lock, WAIT_LOCK);
  1832. // Check again to detect concurrent access. Another thread can have
  1833. // initialized the index while this thread waited for the lock.
  1834. index = _Py_atomic_size_get(&id->index);
  1835. if (index < 0) {
  1836. assert(rt_ids->next_index < PY_SSIZE_T_MAX);
  1837. index = rt_ids->next_index;
  1838. rt_ids->next_index++;
  1839. _Py_atomic_size_set(&id->index, index);
  1840. }
  1841. PyThread_release_lock(rt_ids->lock);
  1842. }
  1843. assert(index >= 0);
  1844. PyObject *obj;
  1845. if (index < ids->size) {
  1846. obj = ids->array[index];
  1847. if (obj) {
  1848. // Return a borrowed reference
  1849. return obj;
  1850. }
  1851. }
  1852. obj = PyUnicode_DecodeUTF8Stateful(id->string, strlen(id->string),
  1853. NULL, NULL);
  1854. if (!obj) {
  1855. return NULL;
  1856. }
  1857. _PyUnicode_InternImmortal(interp, &obj);
  1858. if (index >= ids->size) {
  1859. // Overallocate to reduce the number of realloc
  1860. Py_ssize_t new_size = Py_MAX(index * 2, 16);
  1861. Py_ssize_t item_size = sizeof(ids->array[0]);
  1862. PyObject **new_array = PyMem_Realloc(ids->array, new_size * item_size);
  1863. if (new_array == NULL) {
  1864. PyErr_NoMemory();
  1865. return NULL;
  1866. }
  1867. memset(&new_array[ids->size], 0, (new_size - ids->size) * item_size);
  1868. ids->array = new_array;
  1869. ids->size = new_size;
  1870. }
  1871. // The array stores a strong reference
  1872. ids->array[index] = obj;
  1873. // Return a borrowed reference
  1874. return obj;
  1875. }
  1876. static void
  1877. unicode_clear_identifiers(struct _Py_unicode_state *state)
  1878. {
  1879. struct _Py_unicode_ids *ids = &state->ids;
  1880. for (Py_ssize_t i=0; i < ids->size; i++) {
  1881. Py_XDECREF(ids->array[i]);
  1882. }
  1883. ids->size = 0;
  1884. PyMem_Free(ids->array);
  1885. ids->array = NULL;
  1886. // Don't reset _PyRuntime next_index: _Py_Identifier.id remains valid
  1887. // after Py_Finalize().
  1888. }
  1889. /* Internal function, doesn't check maximum character */
  1890. PyObject*
  1891. _PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
  1892. {
  1893. const unsigned char *s = (const unsigned char *)buffer;
  1894. PyObject *unicode;
  1895. if (size == 1) {
  1896. #ifdef Py_DEBUG
  1897. assert((unsigned char)s[0] < 128);
  1898. #endif
  1899. return get_latin1_char(s[0]);
  1900. }
  1901. unicode = PyUnicode_New(size, 127);
  1902. if (!unicode)
  1903. return NULL;
  1904. memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
  1905. assert(_PyUnicode_CheckConsistency(unicode, 1));
  1906. return unicode;
  1907. }
  1908. static Py_UCS4
  1909. kind_maxchar_limit(int kind)
  1910. {
  1911. switch (kind) {
  1912. case PyUnicode_1BYTE_KIND:
  1913. return 0x80;
  1914. case PyUnicode_2BYTE_KIND:
  1915. return 0x100;
  1916. case PyUnicode_4BYTE_KIND:
  1917. return 0x10000;
  1918. default:
  1919. Py_UNREACHABLE();
  1920. }
  1921. }
  1922. static PyObject*
  1923. _PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
  1924. {
  1925. PyObject *res;
  1926. unsigned char max_char;
  1927. if (size == 0) {
  1928. _Py_RETURN_UNICODE_EMPTY();
  1929. }
  1930. assert(size > 0);
  1931. if (size == 1) {
  1932. return get_latin1_char(u[0]);
  1933. }
  1934. max_char = ucs1lib_find_max_char(u, u + size);
  1935. res = PyUnicode_New(size, max_char);
  1936. if (!res)
  1937. return NULL;
  1938. memcpy(PyUnicode_1BYTE_DATA(res), u, size);
  1939. assert(_PyUnicode_CheckConsistency(res, 1));
  1940. return res;
  1941. }
  1942. static PyObject*
  1943. _PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
  1944. {
  1945. PyObject *res;
  1946. Py_UCS2 max_char;
  1947. if (size == 0)
  1948. _Py_RETURN_UNICODE_EMPTY();
  1949. assert(size > 0);
  1950. if (size == 1)
  1951. return unicode_char(u[0]);
  1952. max_char = ucs2lib_find_max_char(u, u + size);
  1953. res = PyUnicode_New(size, max_char);
  1954. if (!res)
  1955. return NULL;
  1956. if (max_char >= 256)
  1957. memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
  1958. else {
  1959. _PyUnicode_CONVERT_BYTES(
  1960. Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
  1961. }
  1962. assert(_PyUnicode_CheckConsistency(res, 1));
  1963. return res;
  1964. }
  1965. static PyObject*
  1966. _PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
  1967. {
  1968. PyObject *res;
  1969. Py_UCS4 max_char;
  1970. if (size == 0)
  1971. _Py_RETURN_UNICODE_EMPTY();
  1972. assert(size > 0);
  1973. if (size == 1)
  1974. return unicode_char(u[0]);
  1975. max_char = ucs4lib_find_max_char(u, u + size);
  1976. res = PyUnicode_New(size, max_char);
  1977. if (!res)
  1978. return NULL;
  1979. if (max_char < 256)
  1980. _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
  1981. PyUnicode_1BYTE_DATA(res));
  1982. else if (max_char < 0x10000)
  1983. _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
  1984. PyUnicode_2BYTE_DATA(res));
  1985. else
  1986. memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
  1987. assert(_PyUnicode_CheckConsistency(res, 1));
  1988. return res;
  1989. }
  1990. PyObject*
  1991. PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
  1992. {
  1993. if (size < 0) {
  1994. PyErr_SetString(PyExc_ValueError, "size must be positive");
  1995. return NULL;
  1996. }
  1997. switch (kind) {
  1998. case PyUnicode_1BYTE_KIND:
  1999. return _PyUnicode_FromUCS1(buffer, size);
  2000. case PyUnicode_2BYTE_KIND:
  2001. return _PyUnicode_FromUCS2(buffer, size);
  2002. case PyUnicode_4BYTE_KIND:
  2003. return _PyUnicode_FromUCS4(buffer, size);
  2004. default:
  2005. PyErr_SetString(PyExc_SystemError, "invalid kind");
  2006. return NULL;
  2007. }
  2008. }
  2009. Py_UCS4
  2010. _PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
  2011. {
  2012. int kind;
  2013. const void *startptr, *endptr;
  2014. assert(0 <= start);
  2015. assert(end <= PyUnicode_GET_LENGTH(unicode));
  2016. assert(start <= end);
  2017. if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
  2018. return PyUnicode_MAX_CHAR_VALUE(unicode);
  2019. if (start == end)
  2020. return 127;
  2021. if (PyUnicode_IS_ASCII(unicode))
  2022. return 127;
  2023. kind = PyUnicode_KIND(unicode);
  2024. startptr = PyUnicode_DATA(unicode);
  2025. endptr = (char *)startptr + end * kind;
  2026. startptr = (char *)startptr + start * kind;
  2027. switch(kind) {
  2028. case PyUnicode_1BYTE_KIND:
  2029. return ucs1lib_find_max_char(startptr, endptr);
  2030. case PyUnicode_2BYTE_KIND:
  2031. return ucs2lib_find_max_char(startptr, endptr);
  2032. case PyUnicode_4BYTE_KIND:
  2033. return ucs4lib_find_max_char(startptr, endptr);
  2034. default:
  2035. Py_UNREACHABLE();
  2036. }
  2037. }
  2038. /* Ensure that a string uses the most efficient storage, if it is not the
  2039. case: create a new string with of the right kind. Write NULL into *p_unicode
  2040. on error. */
  2041. static void
  2042. unicode_adjust_maxchar(PyObject **p_unicode)
  2043. {
  2044. PyObject *unicode, *copy;
  2045. Py_UCS4 max_char;
  2046. Py_ssize_t len;
  2047. int kind;
  2048. assert(p_unicode != NULL);
  2049. unicode = *p_unicode;
  2050. if (PyUnicode_IS_ASCII(unicode))
  2051. return;
  2052. len = PyUnicode_GET_LENGTH(unicode);
  2053. kind = PyUnicode_KIND(unicode);
  2054. if (kind == PyUnicode_1BYTE_KIND) {
  2055. const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
  2056. max_char = ucs1lib_find_max_char(u, u + len);
  2057. if (max_char >= 128)
  2058. return;
  2059. }
  2060. else if (kind == PyUnicode_2BYTE_KIND) {
  2061. const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
  2062. max_char = ucs2lib_find_max_char(u, u + len);
  2063. if (max_char >= 256)
  2064. return;
  2065. }
  2066. else if (kind == PyUnicode_4BYTE_KIND) {
  2067. const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
  2068. max_char = ucs4lib_find_max_char(u, u + len);
  2069. if (max_char >= 0x10000)
  2070. return;
  2071. }
  2072. else
  2073. Py_UNREACHABLE();
  2074. copy = PyUnicode_New(len, max_char);
  2075. if (copy != NULL)
  2076. _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
  2077. Py_DECREF(unicode);
  2078. *p_unicode = copy;
  2079. }
  2080. PyObject*
  2081. _PyUnicode_Copy(PyObject *unicode)
  2082. {
  2083. Py_ssize_t length;
  2084. PyObject *copy;
  2085. if (!PyUnicode_Check(unicode)) {
  2086. PyErr_BadInternalCall();
  2087. return NULL;
  2088. }
  2089. length = PyUnicode_GET_LENGTH(unicode);
  2090. copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
  2091. if (!copy)
  2092. return NULL;
  2093. assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
  2094. memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
  2095. length * PyUnicode_KIND(unicode));
  2096. assert(_PyUnicode_CheckConsistency(copy, 1));
  2097. return copy;
  2098. }
  2099. /* Widen Unicode objects to larger buffers. Don't write terminating null
  2100. character. Return NULL on error. */
  2101. static void*
  2102. unicode_askind(int skind, void const *data, Py_ssize_t len, int kind)
  2103. {
  2104. void *result;
  2105. assert(skind < kind);
  2106. switch (kind) {
  2107. case PyUnicode_2BYTE_KIND:
  2108. result = PyMem_New(Py_UCS2, len);
  2109. if (!result)
  2110. return PyErr_NoMemory();
  2111. assert(skind == PyUnicode_1BYTE_KIND);
  2112. _PyUnicode_CONVERT_BYTES(
  2113. Py_UCS1, Py_UCS2,
  2114. (const Py_UCS1 *)data,
  2115. ((const Py_UCS1 *)data) + len,
  2116. result);
  2117. return result;
  2118. case PyUnicode_4BYTE_KIND:
  2119. result = PyMem_New(Py_UCS4, len);
  2120. if (!result)
  2121. return PyErr_NoMemory();
  2122. if (skind == PyUnicode_2BYTE_KIND) {
  2123. _PyUnicode_CONVERT_BYTES(
  2124. Py_UCS2, Py_UCS4,
  2125. (const Py_UCS2 *)data,
  2126. ((const Py_UCS2 *)data) + len,
  2127. result);
  2128. }
  2129. else {
  2130. assert(skind == PyUnicode_1BYTE_KIND);
  2131. _PyUnicode_CONVERT_BYTES(
  2132. Py_UCS1, Py_UCS4,
  2133. (const Py_UCS1 *)data,
  2134. ((const Py_UCS1 *)data) + len,
  2135. result);
  2136. }
  2137. return result;
  2138. default:
  2139. Py_UNREACHABLE();
  2140. return NULL;
  2141. }
  2142. }
  2143. static Py_UCS4*
  2144. as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
  2145. int copy_null)
  2146. {
  2147. int kind;
  2148. const void *data;
  2149. Py_ssize_t len, targetlen;
  2150. kind = PyUnicode_KIND(string);
  2151. data = PyUnicode_DATA(string);
  2152. len = PyUnicode_GET_LENGTH(string);
  2153. targetlen = len;
  2154. if (copy_null)
  2155. targetlen++;
  2156. if (!target) {
  2157. target = PyMem_New(Py_UCS4, targetlen);
  2158. if (!target) {
  2159. PyErr_NoMemory();
  2160. return NULL;
  2161. }
  2162. }
  2163. else {
  2164. if (targetsize < targetlen) {
  2165. PyErr_Format(PyExc_SystemError,
  2166. "string is longer than the buffer");
  2167. if (copy_null && 0 < targetsize)
  2168. target[0] = 0;
  2169. return NULL;
  2170. }
  2171. }
  2172. if (kind == PyUnicode_1BYTE_KIND) {
  2173. const Py_UCS1 *start = (const Py_UCS1 *) data;
  2174. _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
  2175. }
  2176. else if (kind == PyUnicode_2BYTE_KIND) {
  2177. const Py_UCS2 *start = (const Py_UCS2 *) data;
  2178. _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
  2179. }
  2180. else if (kind == PyUnicode_4BYTE_KIND) {
  2181. memcpy(target, data, len * sizeof(Py_UCS4));
  2182. }
  2183. else {
  2184. Py_UNREACHABLE();
  2185. }
  2186. if (copy_null)
  2187. target[len] = 0;
  2188. return target;
  2189. }
  2190. Py_UCS4*
  2191. PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
  2192. int copy_null)
  2193. {
  2194. if (target == NULL || targetsize < 0) {
  2195. PyErr_BadInternalCall();
  2196. return NULL;
  2197. }
  2198. return as_ucs4(string, target, targetsize, copy_null);
  2199. }
  2200. Py_UCS4*
  2201. PyUnicode_AsUCS4Copy(PyObject *string)
  2202. {
  2203. return as_ucs4(string, NULL, 0, 1);
  2204. }
  2205. /* maximum number of characters required for output of %jo or %jd or %p.
  2206. We need at most ceil(log8(256)*sizeof(intmax_t)) digits,
  2207. plus 1 for the sign, plus 2 for the 0x prefix (for %p),
  2208. plus 1 for the terminal NUL. */
  2209. #define MAX_INTMAX_CHARS (5 + (sizeof(intmax_t)*8-1) / 3)
  2210. static int
  2211. unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
  2212. Py_ssize_t width, Py_ssize_t precision, int flags)
  2213. {
  2214. Py_ssize_t length, fill, arglen;
  2215. Py_UCS4 maxchar;
  2216. length = PyUnicode_GET_LENGTH(str);
  2217. if ((precision == -1 || precision >= length)
  2218. && width <= length)
  2219. return _PyUnicodeWriter_WriteStr(writer, str);
  2220. if (precision != -1)
  2221. length = Py_MIN(precision, length);
  2222. arglen = Py_MAX(length, width);
  2223. if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
  2224. maxchar = _PyUnicode_FindMaxChar(str, 0, length);
  2225. else
  2226. maxchar = writer->maxchar;
  2227. if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
  2228. return -1;
  2229. fill = Py_MAX(width - length, 0);
  2230. if (fill && !(flags & F_LJUST)) {
  2231. if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
  2232. return -1;
  2233. writer->pos += fill;
  2234. }
  2235. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  2236. str, 0, length);
  2237. writer->pos += length;
  2238. if (fill && (flags & F_LJUST)) {
  2239. if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
  2240. return -1;
  2241. writer->pos += fill;
  2242. }
  2243. return 0;
  2244. }
  2245. static int
  2246. unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
  2247. Py_ssize_t width, Py_ssize_t precision, int flags)
  2248. {
  2249. /* UTF-8 */
  2250. Py_ssize_t length;
  2251. PyObject *unicode;
  2252. int res;
  2253. if (precision == -1) {
  2254. length = strlen(str);
  2255. }
  2256. else {
  2257. length = 0;
  2258. while (length < precision && str[length]) {
  2259. length++;
  2260. }
  2261. }
  2262. unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
  2263. if (unicode == NULL)
  2264. return -1;
  2265. res = unicode_fromformat_write_str(writer, unicode, width, -1, flags);
  2266. Py_DECREF(unicode);
  2267. return res;
  2268. }
  2269. static int
  2270. unicode_fromformat_write_wcstr(_PyUnicodeWriter *writer, const wchar_t *str,
  2271. Py_ssize_t width, Py_ssize_t precision, int flags)
  2272. {
  2273. /* UTF-8 */
  2274. Py_ssize_t length;
  2275. PyObject *unicode;
  2276. int res;
  2277. if (precision == -1) {
  2278. length = wcslen(str);
  2279. }
  2280. else {
  2281. length = 0;
  2282. while (length < precision && str[length]) {
  2283. length++;
  2284. }
  2285. }
  2286. unicode = PyUnicode_FromWideChar(str, length);
  2287. if (unicode == NULL)
  2288. return -1;
  2289. res = unicode_fromformat_write_str(writer, unicode, width, -1, flags);
  2290. Py_DECREF(unicode);
  2291. return res;
  2292. }
  2293. #define F_LONG 1
  2294. #define F_LONGLONG 2
  2295. #define F_SIZE 3
  2296. #define F_PTRDIFF 4
  2297. #define F_INTMAX 5
  2298. static const char * const formats[] = {"%d", "%ld", "%lld", "%zd", "%td", "%jd"};
  2299. static const char * const formats_o[] = {"%o", "%lo", "%llo", "%zo", "%to", "%jo"};
  2300. static const char * const formats_u[] = {"%u", "%lu", "%llu", "%zu", "%tu", "%ju"};
  2301. static const char * const formats_x[] = {"%x", "%lx", "%llx", "%zx", "%tx", "%jx"};
  2302. static const char * const formats_X[] = {"%X", "%lX", "%llX", "%zX", "%tX", "%jX"};
  2303. static const char*
  2304. unicode_fromformat_arg(_PyUnicodeWriter *writer,
  2305. const char *f, va_list *vargs)
  2306. {
  2307. const char *p;
  2308. Py_ssize_t len;
  2309. int flags = 0;
  2310. Py_ssize_t width;
  2311. Py_ssize_t precision;
  2312. p = f;
  2313. f++;
  2314. if (*f == '%') {
  2315. if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
  2316. return NULL;
  2317. f++;
  2318. return f;
  2319. }
  2320. /* Parse flags. Example: "%-i" => flags=F_LJUST. */
  2321. /* Flags '+', ' ' and '#' are not particularly useful.
  2322. * They are not worth the implementation and maintenance costs.
  2323. * In addition, '#' should add "0" for "o" conversions for compatibility
  2324. * with printf, but it would confuse Python users. */
  2325. while (1) {
  2326. switch (*f++) {
  2327. case '-': flags |= F_LJUST; continue;
  2328. case '0': flags |= F_ZERO; continue;
  2329. }
  2330. f--;
  2331. break;
  2332. }
  2333. /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
  2334. width = -1;
  2335. if (*f == '*') {
  2336. width = va_arg(*vargs, int);
  2337. if (width < 0) {
  2338. flags |= F_LJUST;
  2339. width = -width;
  2340. }
  2341. f++;
  2342. }
  2343. else if (Py_ISDIGIT((unsigned)*f)) {
  2344. width = *f - '0';
  2345. f++;
  2346. while (Py_ISDIGIT((unsigned)*f)) {
  2347. if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
  2348. PyErr_SetString(PyExc_ValueError,
  2349. "width too big");
  2350. return NULL;
  2351. }
  2352. width = (width * 10) + (*f - '0');
  2353. f++;
  2354. }
  2355. }
  2356. precision = -1;
  2357. if (*f == '.') {
  2358. f++;
  2359. if (*f == '*') {
  2360. precision = va_arg(*vargs, int);
  2361. if (precision < 0) {
  2362. precision = -2;
  2363. }
  2364. f++;
  2365. }
  2366. else if (Py_ISDIGIT((unsigned)*f)) {
  2367. precision = (*f - '0');
  2368. f++;
  2369. while (Py_ISDIGIT((unsigned)*f)) {
  2370. if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
  2371. PyErr_SetString(PyExc_ValueError,
  2372. "precision too big");
  2373. return NULL;
  2374. }
  2375. precision = (precision * 10) + (*f - '0');
  2376. f++;
  2377. }
  2378. }
  2379. }
  2380. int sizemod = 0;
  2381. if (*f == 'l') {
  2382. if (f[1] == 'l') {
  2383. sizemod = F_LONGLONG;
  2384. f += 2;
  2385. }
  2386. else {
  2387. sizemod = F_LONG;
  2388. ++f;
  2389. }
  2390. }
  2391. else if (*f == 'z') {
  2392. sizemod = F_SIZE;
  2393. ++f;
  2394. }
  2395. else if (*f == 't') {
  2396. sizemod = F_PTRDIFF;
  2397. ++f;
  2398. }
  2399. else if (*f == 'j') {
  2400. sizemod = F_INTMAX;
  2401. ++f;
  2402. }
  2403. if (f[0] != '\0' && f[1] == '\0')
  2404. writer->overallocate = 0;
  2405. switch (*f) {
  2406. case 'd': case 'i': case 'o': case 'u': case 'x': case 'X':
  2407. break;
  2408. case 'c': case 'p':
  2409. if (sizemod || width >= 0 || precision >= 0) goto invalid_format;
  2410. break;
  2411. case 's':
  2412. case 'V':
  2413. if (sizemod && sizemod != F_LONG) goto invalid_format;
  2414. break;
  2415. default:
  2416. if (sizemod) goto invalid_format;
  2417. break;
  2418. }
  2419. switch (*f) {
  2420. case 'c':
  2421. {
  2422. int ordinal = va_arg(*vargs, int);
  2423. if (ordinal < 0 || ordinal > MAX_UNICODE) {
  2424. PyErr_SetString(PyExc_OverflowError,
  2425. "character argument not in range(0x110000)");
  2426. return NULL;
  2427. }
  2428. if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
  2429. return NULL;
  2430. break;
  2431. }
  2432. case 'd': case 'i':
  2433. case 'o': case 'u': case 'x': case 'X':
  2434. {
  2435. /* used by sprintf */
  2436. char buffer[MAX_INTMAX_CHARS];
  2437. const char *fmt = NULL;
  2438. switch (*f) {
  2439. case 'o': fmt = formats_o[sizemod]; break;
  2440. case 'u': fmt = formats_u[sizemod]; break;
  2441. case 'x': fmt = formats_x[sizemod]; break;
  2442. case 'X': fmt = formats_X[sizemod]; break;
  2443. default: fmt = formats[sizemod]; break;
  2444. }
  2445. int issigned = (*f == 'd' || *f == 'i');
  2446. switch (sizemod) {
  2447. case F_LONG:
  2448. len = issigned ?
  2449. sprintf(buffer, fmt, va_arg(*vargs, long)) :
  2450. sprintf(buffer, fmt, va_arg(*vargs, unsigned long));
  2451. break;
  2452. case F_LONGLONG:
  2453. len = issigned ?
  2454. sprintf(buffer, fmt, va_arg(*vargs, long long)) :
  2455. sprintf(buffer, fmt, va_arg(*vargs, unsigned long long));
  2456. break;
  2457. case F_SIZE:
  2458. len = issigned ?
  2459. sprintf(buffer, fmt, va_arg(*vargs, Py_ssize_t)) :
  2460. sprintf(buffer, fmt, va_arg(*vargs, size_t));
  2461. break;
  2462. case F_PTRDIFF:
  2463. len = sprintf(buffer, fmt, va_arg(*vargs, ptrdiff_t));
  2464. break;
  2465. case F_INTMAX:
  2466. len = issigned ?
  2467. sprintf(buffer, fmt, va_arg(*vargs, intmax_t)) :
  2468. sprintf(buffer, fmt, va_arg(*vargs, uintmax_t));
  2469. break;
  2470. default:
  2471. len = issigned ?
  2472. sprintf(buffer, fmt, va_arg(*vargs, int)) :
  2473. sprintf(buffer, fmt, va_arg(*vargs, unsigned int));
  2474. break;
  2475. }
  2476. assert(len >= 0);
  2477. int sign = (buffer[0] == '-');
  2478. len -= sign;
  2479. precision = Py_MAX(precision, len);
  2480. width = Py_MAX(width, precision + sign);
  2481. if ((flags & F_ZERO) && !(flags & F_LJUST)) {
  2482. precision = width - sign;
  2483. }
  2484. Py_ssize_t spacepad = Py_MAX(width - precision - sign, 0);
  2485. Py_ssize_t zeropad = Py_MAX(precision - len, 0);
  2486. if (_PyUnicodeWriter_Prepare(writer, width, 127) == -1)
  2487. return NULL;
  2488. if (spacepad && !(flags & F_LJUST)) {
  2489. if (PyUnicode_Fill(writer->buffer, writer->pos, spacepad, ' ') == -1)
  2490. return NULL;
  2491. writer->pos += spacepad;
  2492. }
  2493. if (sign) {
  2494. if (_PyUnicodeWriter_WriteChar(writer, '-') == -1)
  2495. return NULL;
  2496. }
  2497. if (zeropad) {
  2498. if (PyUnicode_Fill(writer->buffer, writer->pos, zeropad, '0') == -1)
  2499. return NULL;
  2500. writer->pos += zeropad;
  2501. }
  2502. if (_PyUnicodeWriter_WriteASCIIString(writer, &buffer[sign], len) < 0)
  2503. return NULL;
  2504. if (spacepad && (flags & F_LJUST)) {
  2505. if (PyUnicode_Fill(writer->buffer, writer->pos, spacepad, ' ') == -1)
  2506. return NULL;
  2507. writer->pos += spacepad;
  2508. }
  2509. break;
  2510. }
  2511. case 'p':
  2512. {
  2513. char number[MAX_INTMAX_CHARS];
  2514. len = sprintf(number, "%p", va_arg(*vargs, void*));
  2515. assert(len >= 0);
  2516. /* %p is ill-defined: ensure leading 0x. */
  2517. if (number[1] == 'X')
  2518. number[1] = 'x';
  2519. else if (number[1] != 'x') {
  2520. memmove(number + 2, number,
  2521. strlen(number) + 1);
  2522. number[0] = '0';
  2523. number[1] = 'x';
  2524. len += 2;
  2525. }
  2526. if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
  2527. return NULL;
  2528. break;
  2529. }
  2530. case 's':
  2531. {
  2532. if (sizemod) {
  2533. const wchar_t *s = va_arg(*vargs, const wchar_t*);
  2534. if (unicode_fromformat_write_wcstr(writer, s, width, precision, flags) < 0)
  2535. return NULL;
  2536. }
  2537. else {
  2538. /* UTF-8 */
  2539. const char *s = va_arg(*vargs, const char*);
  2540. if (unicode_fromformat_write_cstr(writer, s, width, precision, flags) < 0)
  2541. return NULL;
  2542. }
  2543. break;
  2544. }
  2545. case 'U':
  2546. {
  2547. PyObject *obj = va_arg(*vargs, PyObject *);
  2548. assert(obj && _PyUnicode_CHECK(obj));
  2549. if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
  2550. return NULL;
  2551. break;
  2552. }
  2553. case 'V':
  2554. {
  2555. PyObject *obj = va_arg(*vargs, PyObject *);
  2556. const char *str;
  2557. const wchar_t *wstr;
  2558. if (sizemod) {
  2559. wstr = va_arg(*vargs, const wchar_t*);
  2560. }
  2561. else {
  2562. str = va_arg(*vargs, const char *);
  2563. }
  2564. if (obj) {
  2565. assert(_PyUnicode_CHECK(obj));
  2566. if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
  2567. return NULL;
  2568. }
  2569. else if (sizemod) {
  2570. assert(wstr != NULL);
  2571. if (unicode_fromformat_write_wcstr(writer, wstr, width, precision, flags) < 0)
  2572. return NULL;
  2573. }
  2574. else {
  2575. assert(str != NULL);
  2576. if (unicode_fromformat_write_cstr(writer, str, width, precision, flags) < 0)
  2577. return NULL;
  2578. }
  2579. break;
  2580. }
  2581. case 'S':
  2582. {
  2583. PyObject *obj = va_arg(*vargs, PyObject *);
  2584. PyObject *str;
  2585. assert(obj);
  2586. str = PyObject_Str(obj);
  2587. if (!str)
  2588. return NULL;
  2589. if (unicode_fromformat_write_str(writer, str, width, precision, flags) == -1) {
  2590. Py_DECREF(str);
  2591. return NULL;
  2592. }
  2593. Py_DECREF(str);
  2594. break;
  2595. }
  2596. case 'R':
  2597. {
  2598. PyObject *obj = va_arg(*vargs, PyObject *);
  2599. PyObject *repr;
  2600. assert(obj);
  2601. repr = PyObject_Repr(obj);
  2602. if (!repr)
  2603. return NULL;
  2604. if (unicode_fromformat_write_str(writer, repr, width, precision, flags) == -1) {
  2605. Py_DECREF(repr);
  2606. return NULL;
  2607. }
  2608. Py_DECREF(repr);
  2609. break;
  2610. }
  2611. case 'A':
  2612. {
  2613. PyObject *obj = va_arg(*vargs, PyObject *);
  2614. PyObject *ascii;
  2615. assert(obj);
  2616. ascii = PyObject_ASCII(obj);
  2617. if (!ascii)
  2618. return NULL;
  2619. if (unicode_fromformat_write_str(writer, ascii, width, precision, flags) == -1) {
  2620. Py_DECREF(ascii);
  2621. return NULL;
  2622. }
  2623. Py_DECREF(ascii);
  2624. break;
  2625. }
  2626. default:
  2627. invalid_format:
  2628. PyErr_Format(PyExc_SystemError, "invalid format string: %s", p);
  2629. return NULL;
  2630. }
  2631. f++;
  2632. return f;
  2633. }
  2634. PyObject *
  2635. PyUnicode_FromFormatV(const char *format, va_list vargs)
  2636. {
  2637. va_list vargs2;
  2638. const char *f;
  2639. _PyUnicodeWriter writer;
  2640. _PyUnicodeWriter_Init(&writer);
  2641. writer.min_length = strlen(format) + 100;
  2642. writer.overallocate = 1;
  2643. // Copy varags to be able to pass a reference to a subfunction.
  2644. va_copy(vargs2, vargs);
  2645. for (f = format; *f; ) {
  2646. if (*f == '%') {
  2647. f = unicode_fromformat_arg(&writer, f, &vargs2);
  2648. if (f == NULL)
  2649. goto fail;
  2650. }
  2651. else {
  2652. const char *p;
  2653. Py_ssize_t len;
  2654. p = f;
  2655. do
  2656. {
  2657. if ((unsigned char)*p > 127) {
  2658. PyErr_Format(PyExc_ValueError,
  2659. "PyUnicode_FromFormatV() expects an ASCII-encoded format "
  2660. "string, got a non-ASCII byte: 0x%02x",
  2661. (unsigned char)*p);
  2662. goto fail;
  2663. }
  2664. p++;
  2665. }
  2666. while (*p != '\0' && *p != '%');
  2667. len = p - f;
  2668. if (*p == '\0')
  2669. writer.overallocate = 0;
  2670. if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
  2671. goto fail;
  2672. f = p;
  2673. }
  2674. }
  2675. va_end(vargs2);
  2676. return _PyUnicodeWriter_Finish(&writer);
  2677. fail:
  2678. va_end(vargs2);
  2679. _PyUnicodeWriter_Dealloc(&writer);
  2680. return NULL;
  2681. }
  2682. PyObject *
  2683. PyUnicode_FromFormat(const char *format, ...)
  2684. {
  2685. PyObject* ret;
  2686. va_list vargs;
  2687. va_start(vargs, format);
  2688. ret = PyUnicode_FromFormatV(format, vargs);
  2689. va_end(vargs);
  2690. return ret;
  2691. }
  2692. static Py_ssize_t
  2693. unicode_get_widechar_size(PyObject *unicode)
  2694. {
  2695. Py_ssize_t res;
  2696. assert(unicode != NULL);
  2697. assert(_PyUnicode_CHECK(unicode));
  2698. res = _PyUnicode_LENGTH(unicode);
  2699. #if SIZEOF_WCHAR_T == 2
  2700. if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
  2701. const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
  2702. const Py_UCS4 *end = s + res;
  2703. for (; s < end; ++s) {
  2704. if (*s > 0xFFFF) {
  2705. ++res;
  2706. }
  2707. }
  2708. }
  2709. #endif
  2710. return res;
  2711. }
  2712. static void
  2713. unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
  2714. {
  2715. assert(unicode != NULL);
  2716. assert(_PyUnicode_CHECK(unicode));
  2717. if (PyUnicode_KIND(unicode) == sizeof(wchar_t)) {
  2718. memcpy(w, PyUnicode_DATA(unicode), size * sizeof(wchar_t));
  2719. return;
  2720. }
  2721. if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
  2722. const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
  2723. for (; size--; ++s, ++w) {
  2724. *w = *s;
  2725. }
  2726. }
  2727. else {
  2728. #if SIZEOF_WCHAR_T == 4
  2729. assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
  2730. const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
  2731. for (; size--; ++s, ++w) {
  2732. *w = *s;
  2733. }
  2734. #else
  2735. assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
  2736. const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
  2737. for (; size--; ++s, ++w) {
  2738. Py_UCS4 ch = *s;
  2739. if (ch > 0xFFFF) {
  2740. assert(ch <= MAX_UNICODE);
  2741. /* encode surrogate pair in this case */
  2742. *w++ = Py_UNICODE_HIGH_SURROGATE(ch);
  2743. if (!size--)
  2744. break;
  2745. *w = Py_UNICODE_LOW_SURROGATE(ch);
  2746. }
  2747. else {
  2748. *w = ch;
  2749. }
  2750. }
  2751. #endif
  2752. }
  2753. }
  2754. #ifdef HAVE_WCHAR_H
  2755. /* Convert a Unicode object to a wide character string.
  2756. - If w is NULL: return the number of wide characters (including the null
  2757. character) required to convert the unicode object. Ignore size argument.
  2758. - Otherwise: return the number of wide characters (excluding the null
  2759. character) written into w. Write at most size wide characters (including
  2760. the null character). */
  2761. Py_ssize_t
  2762. PyUnicode_AsWideChar(PyObject *unicode,
  2763. wchar_t *w,
  2764. Py_ssize_t size)
  2765. {
  2766. Py_ssize_t res;
  2767. if (unicode == NULL) {
  2768. PyErr_BadInternalCall();
  2769. return -1;
  2770. }
  2771. if (!PyUnicode_Check(unicode)) {
  2772. PyErr_BadArgument();
  2773. return -1;
  2774. }
  2775. res = unicode_get_widechar_size(unicode);
  2776. if (w == NULL) {
  2777. return res + 1;
  2778. }
  2779. if (size > res) {
  2780. size = res + 1;
  2781. }
  2782. else {
  2783. res = size;
  2784. }
  2785. unicode_copy_as_widechar(unicode, w, size);
  2786. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  2787. /* Oracle Solaris uses non-Unicode internal wchar_t form for
  2788. non-Unicode locales and hence needs conversion first. */
  2789. if (_Py_LocaleUsesNonUnicodeWchar()) {
  2790. if (_Py_EncodeNonUnicodeWchar_InPlace(w, size) < 0) {
  2791. return -1;
  2792. }
  2793. }
  2794. #endif
  2795. return res;
  2796. }
  2797. wchar_t*
  2798. PyUnicode_AsWideCharString(PyObject *unicode,
  2799. Py_ssize_t *size)
  2800. {
  2801. wchar_t *buffer;
  2802. Py_ssize_t buflen;
  2803. if (unicode == NULL) {
  2804. PyErr_BadInternalCall();
  2805. return NULL;
  2806. }
  2807. if (!PyUnicode_Check(unicode)) {
  2808. PyErr_BadArgument();
  2809. return NULL;
  2810. }
  2811. buflen = unicode_get_widechar_size(unicode);
  2812. buffer = (wchar_t *) PyMem_New(wchar_t, (buflen + 1));
  2813. if (buffer == NULL) {
  2814. PyErr_NoMemory();
  2815. return NULL;
  2816. }
  2817. unicode_copy_as_widechar(unicode, buffer, buflen + 1);
  2818. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  2819. /* Oracle Solaris uses non-Unicode internal wchar_t form for
  2820. non-Unicode locales and hence needs conversion first. */
  2821. if (_Py_LocaleUsesNonUnicodeWchar()) {
  2822. if (_Py_EncodeNonUnicodeWchar_InPlace(buffer, (buflen + 1)) < 0) {
  2823. return NULL;
  2824. }
  2825. }
  2826. #endif
  2827. if (size != NULL) {
  2828. *size = buflen;
  2829. }
  2830. else if (wcslen(buffer) != (size_t)buflen) {
  2831. PyMem_Free(buffer);
  2832. PyErr_SetString(PyExc_ValueError,
  2833. "embedded null character");
  2834. return NULL;
  2835. }
  2836. return buffer;
  2837. }
  2838. #endif /* HAVE_WCHAR_H */
  2839. int
  2840. _PyUnicode_WideCharString_Converter(PyObject *obj, void *ptr)
  2841. {
  2842. wchar_t **p = (wchar_t **)ptr;
  2843. if (obj == NULL) {
  2844. PyMem_Free(*p);
  2845. *p = NULL;
  2846. return 1;
  2847. }
  2848. if (PyUnicode_Check(obj)) {
  2849. *p = PyUnicode_AsWideCharString(obj, NULL);
  2850. if (*p == NULL) {
  2851. return 0;
  2852. }
  2853. return Py_CLEANUP_SUPPORTED;
  2854. }
  2855. PyErr_Format(PyExc_TypeError,
  2856. "argument must be str, not %.50s",
  2857. Py_TYPE(obj)->tp_name);
  2858. return 0;
  2859. }
  2860. int
  2861. _PyUnicode_WideCharString_Opt_Converter(PyObject *obj, void *ptr)
  2862. {
  2863. wchar_t **p = (wchar_t **)ptr;
  2864. if (obj == NULL) {
  2865. PyMem_Free(*p);
  2866. *p = NULL;
  2867. return 1;
  2868. }
  2869. if (obj == Py_None) {
  2870. *p = NULL;
  2871. return 1;
  2872. }
  2873. if (PyUnicode_Check(obj)) {
  2874. *p = PyUnicode_AsWideCharString(obj, NULL);
  2875. if (*p == NULL) {
  2876. return 0;
  2877. }
  2878. return Py_CLEANUP_SUPPORTED;
  2879. }
  2880. PyErr_Format(PyExc_TypeError,
  2881. "argument must be str or None, not %.50s",
  2882. Py_TYPE(obj)->tp_name);
  2883. return 0;
  2884. }
  2885. PyObject *
  2886. PyUnicode_FromOrdinal(int ordinal)
  2887. {
  2888. if (ordinal < 0 || ordinal > MAX_UNICODE) {
  2889. PyErr_SetString(PyExc_ValueError,
  2890. "chr() arg not in range(0x110000)");
  2891. return NULL;
  2892. }
  2893. return unicode_char((Py_UCS4)ordinal);
  2894. }
  2895. PyObject *
  2896. PyUnicode_FromObject(PyObject *obj)
  2897. {
  2898. /* XXX Perhaps we should make this API an alias of
  2899. PyObject_Str() instead ?! */
  2900. if (PyUnicode_CheckExact(obj)) {
  2901. return Py_NewRef(obj);
  2902. }
  2903. if (PyUnicode_Check(obj)) {
  2904. /* For a Unicode subtype that's not a Unicode object,
  2905. return a true Unicode object with the same data. */
  2906. return _PyUnicode_Copy(obj);
  2907. }
  2908. PyErr_Format(PyExc_TypeError,
  2909. "Can't convert '%.100s' object to str implicitly",
  2910. Py_TYPE(obj)->tp_name);
  2911. return NULL;
  2912. }
  2913. PyObject *
  2914. PyUnicode_FromEncodedObject(PyObject *obj,
  2915. const char *encoding,
  2916. const char *errors)
  2917. {
  2918. Py_buffer buffer;
  2919. PyObject *v;
  2920. if (obj == NULL) {
  2921. PyErr_BadInternalCall();
  2922. return NULL;
  2923. }
  2924. /* Decoding bytes objects is the most common case and should be fast */
  2925. if (PyBytes_Check(obj)) {
  2926. if (PyBytes_GET_SIZE(obj) == 0) {
  2927. if (unicode_check_encoding_errors(encoding, errors) < 0) {
  2928. return NULL;
  2929. }
  2930. _Py_RETURN_UNICODE_EMPTY();
  2931. }
  2932. return PyUnicode_Decode(
  2933. PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
  2934. encoding, errors);
  2935. }
  2936. if (PyUnicode_Check(obj)) {
  2937. PyErr_SetString(PyExc_TypeError,
  2938. "decoding str is not supported");
  2939. return NULL;
  2940. }
  2941. /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
  2942. if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
  2943. PyErr_Format(PyExc_TypeError,
  2944. "decoding to str: need a bytes-like object, %.80s found",
  2945. Py_TYPE(obj)->tp_name);
  2946. return NULL;
  2947. }
  2948. if (buffer.len == 0) {
  2949. PyBuffer_Release(&buffer);
  2950. if (unicode_check_encoding_errors(encoding, errors) < 0) {
  2951. return NULL;
  2952. }
  2953. _Py_RETURN_UNICODE_EMPTY();
  2954. }
  2955. v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
  2956. PyBuffer_Release(&buffer);
  2957. return v;
  2958. }
  2959. /* Normalize an encoding name: similar to encodings.normalize_encoding(), but
  2960. also convert to lowercase. Return 1 on success, or 0 on error (encoding is
  2961. longer than lower_len-1). */
  2962. int
  2963. _Py_normalize_encoding(const char *encoding,
  2964. char *lower,
  2965. size_t lower_len)
  2966. {
  2967. const char *e;
  2968. char *l;
  2969. char *l_end;
  2970. int punct;
  2971. assert(encoding != NULL);
  2972. e = encoding;
  2973. l = lower;
  2974. l_end = &lower[lower_len - 1];
  2975. punct = 0;
  2976. while (1) {
  2977. char c = *e;
  2978. if (c == 0) {
  2979. break;
  2980. }
  2981. if (Py_ISALNUM(c) || c == '.') {
  2982. if (punct && l != lower) {
  2983. if (l == l_end) {
  2984. return 0;
  2985. }
  2986. *l++ = '_';
  2987. }
  2988. punct = 0;
  2989. if (l == l_end) {
  2990. return 0;
  2991. }
  2992. *l++ = Py_TOLOWER(c);
  2993. }
  2994. else {
  2995. punct = 1;
  2996. }
  2997. e++;
  2998. }
  2999. *l = '\0';
  3000. return 1;
  3001. }
  3002. PyObject *
  3003. PyUnicode_Decode(const char *s,
  3004. Py_ssize_t size,
  3005. const char *encoding,
  3006. const char *errors)
  3007. {
  3008. PyObject *buffer = NULL, *unicode;
  3009. Py_buffer info;
  3010. char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
  3011. if (unicode_check_encoding_errors(encoding, errors) < 0) {
  3012. return NULL;
  3013. }
  3014. if (size == 0) {
  3015. _Py_RETURN_UNICODE_EMPTY();
  3016. }
  3017. if (encoding == NULL) {
  3018. return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
  3019. }
  3020. /* Shortcuts for common default encodings */
  3021. if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
  3022. char *lower = buflower;
  3023. /* Fast paths */
  3024. if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
  3025. lower += 3;
  3026. if (*lower == '_') {
  3027. /* Match "utf8" and "utf_8" */
  3028. lower++;
  3029. }
  3030. if (lower[0] == '8' && lower[1] == 0) {
  3031. return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
  3032. }
  3033. else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
  3034. return PyUnicode_DecodeUTF16(s, size, errors, 0);
  3035. }
  3036. else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
  3037. return PyUnicode_DecodeUTF32(s, size, errors, 0);
  3038. }
  3039. }
  3040. else {
  3041. if (strcmp(lower, "ascii") == 0
  3042. || strcmp(lower, "us_ascii") == 0) {
  3043. return PyUnicode_DecodeASCII(s, size, errors);
  3044. }
  3045. #ifdef MS_WINDOWS
  3046. else if (strcmp(lower, "mbcs") == 0) {
  3047. return PyUnicode_DecodeMBCS(s, size, errors);
  3048. }
  3049. #endif
  3050. else if (strcmp(lower, "latin1") == 0
  3051. || strcmp(lower, "latin_1") == 0
  3052. || strcmp(lower, "iso_8859_1") == 0
  3053. || strcmp(lower, "iso8859_1") == 0) {
  3054. return PyUnicode_DecodeLatin1(s, size, errors);
  3055. }
  3056. }
  3057. }
  3058. /* Decode via the codec registry */
  3059. buffer = NULL;
  3060. if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
  3061. goto onError;
  3062. buffer = PyMemoryView_FromBuffer(&info);
  3063. if (buffer == NULL)
  3064. goto onError;
  3065. unicode = _PyCodec_DecodeText(buffer, encoding, errors);
  3066. if (unicode == NULL)
  3067. goto onError;
  3068. if (!PyUnicode_Check(unicode)) {
  3069. PyErr_Format(PyExc_TypeError,
  3070. "'%.400s' decoder returned '%.400s' instead of 'str'; "
  3071. "use codecs.decode() to decode to arbitrary types",
  3072. encoding,
  3073. Py_TYPE(unicode)->tp_name);
  3074. Py_DECREF(unicode);
  3075. goto onError;
  3076. }
  3077. Py_DECREF(buffer);
  3078. return unicode_result(unicode);
  3079. onError:
  3080. Py_XDECREF(buffer);
  3081. return NULL;
  3082. }
  3083. PyObject *
  3084. PyUnicode_AsDecodedObject(PyObject *unicode,
  3085. const char *encoding,
  3086. const char *errors)
  3087. {
  3088. if (!PyUnicode_Check(unicode)) {
  3089. PyErr_BadArgument();
  3090. return NULL;
  3091. }
  3092. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  3093. "PyUnicode_AsDecodedObject() is deprecated; "
  3094. "use PyCodec_Decode() to decode from str", 1) < 0)
  3095. return NULL;
  3096. if (encoding == NULL)
  3097. encoding = PyUnicode_GetDefaultEncoding();
  3098. /* Decode via the codec registry */
  3099. return PyCodec_Decode(unicode, encoding, errors);
  3100. }
  3101. PyObject *
  3102. PyUnicode_AsDecodedUnicode(PyObject *unicode,
  3103. const char *encoding,
  3104. const char *errors)
  3105. {
  3106. PyObject *v;
  3107. if (!PyUnicode_Check(unicode)) {
  3108. PyErr_BadArgument();
  3109. goto onError;
  3110. }
  3111. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  3112. "PyUnicode_AsDecodedUnicode() is deprecated; "
  3113. "use PyCodec_Decode() to decode from str to str", 1) < 0)
  3114. return NULL;
  3115. if (encoding == NULL)
  3116. encoding = PyUnicode_GetDefaultEncoding();
  3117. /* Decode via the codec registry */
  3118. v = PyCodec_Decode(unicode, encoding, errors);
  3119. if (v == NULL)
  3120. goto onError;
  3121. if (!PyUnicode_Check(v)) {
  3122. PyErr_Format(PyExc_TypeError,
  3123. "'%.400s' decoder returned '%.400s' instead of 'str'; "
  3124. "use codecs.decode() to decode to arbitrary types",
  3125. encoding,
  3126. Py_TYPE(unicode)->tp_name);
  3127. Py_DECREF(v);
  3128. goto onError;
  3129. }
  3130. return unicode_result(v);
  3131. onError:
  3132. return NULL;
  3133. }
  3134. PyObject *
  3135. PyUnicode_AsEncodedObject(PyObject *unicode,
  3136. const char *encoding,
  3137. const char *errors)
  3138. {
  3139. PyObject *v;
  3140. if (!PyUnicode_Check(unicode)) {
  3141. PyErr_BadArgument();
  3142. goto onError;
  3143. }
  3144. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  3145. "PyUnicode_AsEncodedObject() is deprecated; "
  3146. "use PyUnicode_AsEncodedString() to encode from str to bytes "
  3147. "or PyCodec_Encode() for generic encoding", 1) < 0)
  3148. return NULL;
  3149. if (encoding == NULL)
  3150. encoding = PyUnicode_GetDefaultEncoding();
  3151. /* Encode via the codec registry */
  3152. v = PyCodec_Encode(unicode, encoding, errors);
  3153. if (v == NULL)
  3154. goto onError;
  3155. return v;
  3156. onError:
  3157. return NULL;
  3158. }
  3159. static PyObject *
  3160. unicode_encode_locale(PyObject *unicode, _Py_error_handler error_handler,
  3161. int current_locale)
  3162. {
  3163. Py_ssize_t wlen;
  3164. wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
  3165. if (wstr == NULL) {
  3166. return NULL;
  3167. }
  3168. if ((size_t)wlen != wcslen(wstr)) {
  3169. PyErr_SetString(PyExc_ValueError, "embedded null character");
  3170. PyMem_Free(wstr);
  3171. return NULL;
  3172. }
  3173. char *str;
  3174. size_t error_pos;
  3175. const char *reason;
  3176. int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
  3177. current_locale, error_handler);
  3178. PyMem_Free(wstr);
  3179. if (res != 0) {
  3180. if (res == -2) {
  3181. PyObject *exc;
  3182. exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
  3183. "locale", unicode,
  3184. (Py_ssize_t)error_pos,
  3185. (Py_ssize_t)(error_pos+1),
  3186. reason);
  3187. if (exc != NULL) {
  3188. PyCodec_StrictErrors(exc);
  3189. Py_DECREF(exc);
  3190. }
  3191. }
  3192. else if (res == -3) {
  3193. PyErr_SetString(PyExc_ValueError, "unsupported error handler");
  3194. }
  3195. else {
  3196. PyErr_NoMemory();
  3197. }
  3198. return NULL;
  3199. }
  3200. PyObject *bytes = PyBytes_FromString(str);
  3201. PyMem_RawFree(str);
  3202. return bytes;
  3203. }
  3204. PyObject *
  3205. PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
  3206. {
  3207. _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
  3208. return unicode_encode_locale(unicode, error_handler, 1);
  3209. }
  3210. PyObject *
  3211. PyUnicode_EncodeFSDefault(PyObject *unicode)
  3212. {
  3213. PyInterpreterState *interp = _PyInterpreterState_GET();
  3214. struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
  3215. if (fs_codec->utf8) {
  3216. return unicode_encode_utf8(unicode,
  3217. fs_codec->error_handler,
  3218. fs_codec->errors);
  3219. }
  3220. #ifndef _Py_FORCE_UTF8_FS_ENCODING
  3221. else if (fs_codec->encoding) {
  3222. return PyUnicode_AsEncodedString(unicode,
  3223. fs_codec->encoding,
  3224. fs_codec->errors);
  3225. }
  3226. #endif
  3227. else {
  3228. /* Before _PyUnicode_InitEncodings() is called, the Python codec
  3229. machinery is not ready and so cannot be used:
  3230. use wcstombs() in this case. */
  3231. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  3232. const wchar_t *filesystem_errors = config->filesystem_errors;
  3233. assert(filesystem_errors != NULL);
  3234. _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
  3235. assert(errors != _Py_ERROR_UNKNOWN);
  3236. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  3237. return unicode_encode_utf8(unicode, errors, NULL);
  3238. #else
  3239. return unicode_encode_locale(unicode, errors, 0);
  3240. #endif
  3241. }
  3242. }
  3243. PyObject *
  3244. PyUnicode_AsEncodedString(PyObject *unicode,
  3245. const char *encoding,
  3246. const char *errors)
  3247. {
  3248. PyObject *v;
  3249. char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
  3250. if (!PyUnicode_Check(unicode)) {
  3251. PyErr_BadArgument();
  3252. return NULL;
  3253. }
  3254. if (unicode_check_encoding_errors(encoding, errors) < 0) {
  3255. return NULL;
  3256. }
  3257. if (encoding == NULL) {
  3258. return _PyUnicode_AsUTF8String(unicode, errors);
  3259. }
  3260. /* Shortcuts for common default encodings */
  3261. if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
  3262. char *lower = buflower;
  3263. /* Fast paths */
  3264. if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
  3265. lower += 3;
  3266. if (*lower == '_') {
  3267. /* Match "utf8" and "utf_8" */
  3268. lower++;
  3269. }
  3270. if (lower[0] == '8' && lower[1] == 0) {
  3271. return _PyUnicode_AsUTF8String(unicode, errors);
  3272. }
  3273. else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
  3274. return _PyUnicode_EncodeUTF16(unicode, errors, 0);
  3275. }
  3276. else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
  3277. return _PyUnicode_EncodeUTF32(unicode, errors, 0);
  3278. }
  3279. }
  3280. else {
  3281. if (strcmp(lower, "ascii") == 0
  3282. || strcmp(lower, "us_ascii") == 0) {
  3283. return _PyUnicode_AsASCIIString(unicode, errors);
  3284. }
  3285. #ifdef MS_WINDOWS
  3286. else if (strcmp(lower, "mbcs") == 0) {
  3287. return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
  3288. }
  3289. #endif
  3290. else if (strcmp(lower, "latin1") == 0 ||
  3291. strcmp(lower, "latin_1") == 0 ||
  3292. strcmp(lower, "iso_8859_1") == 0 ||
  3293. strcmp(lower, "iso8859_1") == 0) {
  3294. return _PyUnicode_AsLatin1String(unicode, errors);
  3295. }
  3296. }
  3297. }
  3298. /* Encode via the codec registry */
  3299. v = _PyCodec_EncodeText(unicode, encoding, errors);
  3300. if (v == NULL)
  3301. return NULL;
  3302. /* The normal path */
  3303. if (PyBytes_Check(v))
  3304. return v;
  3305. /* If the codec returns a buffer, raise a warning and convert to bytes */
  3306. if (PyByteArray_Check(v)) {
  3307. int error;
  3308. PyObject *b;
  3309. error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
  3310. "encoder %s returned bytearray instead of bytes; "
  3311. "use codecs.encode() to encode to arbitrary types",
  3312. encoding);
  3313. if (error) {
  3314. Py_DECREF(v);
  3315. return NULL;
  3316. }
  3317. b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
  3318. PyByteArray_GET_SIZE(v));
  3319. Py_DECREF(v);
  3320. return b;
  3321. }
  3322. PyErr_Format(PyExc_TypeError,
  3323. "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
  3324. "use codecs.encode() to encode to arbitrary types",
  3325. encoding,
  3326. Py_TYPE(v)->tp_name);
  3327. Py_DECREF(v);
  3328. return NULL;
  3329. }
  3330. PyObject *
  3331. PyUnicode_AsEncodedUnicode(PyObject *unicode,
  3332. const char *encoding,
  3333. const char *errors)
  3334. {
  3335. PyObject *v;
  3336. if (!PyUnicode_Check(unicode)) {
  3337. PyErr_BadArgument();
  3338. goto onError;
  3339. }
  3340. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  3341. "PyUnicode_AsEncodedUnicode() is deprecated; "
  3342. "use PyCodec_Encode() to encode from str to str", 1) < 0)
  3343. return NULL;
  3344. if (encoding == NULL)
  3345. encoding = PyUnicode_GetDefaultEncoding();
  3346. /* Encode via the codec registry */
  3347. v = PyCodec_Encode(unicode, encoding, errors);
  3348. if (v == NULL)
  3349. goto onError;
  3350. if (!PyUnicode_Check(v)) {
  3351. PyErr_Format(PyExc_TypeError,
  3352. "'%.400s' encoder returned '%.400s' instead of 'str'; "
  3353. "use codecs.encode() to encode to arbitrary types",
  3354. encoding,
  3355. Py_TYPE(v)->tp_name);
  3356. Py_DECREF(v);
  3357. goto onError;
  3358. }
  3359. return v;
  3360. onError:
  3361. return NULL;
  3362. }
  3363. static PyObject*
  3364. unicode_decode_locale(const char *str, Py_ssize_t len,
  3365. _Py_error_handler errors, int current_locale)
  3366. {
  3367. if (str[len] != '\0' || (size_t)len != strlen(str)) {
  3368. PyErr_SetString(PyExc_ValueError, "embedded null byte");
  3369. return NULL;
  3370. }
  3371. wchar_t *wstr;
  3372. size_t wlen;
  3373. const char *reason;
  3374. int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
  3375. current_locale, errors);
  3376. if (res != 0) {
  3377. if (res == -2) {
  3378. PyObject *exc;
  3379. exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
  3380. "locale", str, len,
  3381. (Py_ssize_t)wlen,
  3382. (Py_ssize_t)(wlen + 1),
  3383. reason);
  3384. if (exc != NULL) {
  3385. PyCodec_StrictErrors(exc);
  3386. Py_DECREF(exc);
  3387. }
  3388. }
  3389. else if (res == -3) {
  3390. PyErr_SetString(PyExc_ValueError, "unsupported error handler");
  3391. }
  3392. else {
  3393. PyErr_NoMemory();
  3394. }
  3395. return NULL;
  3396. }
  3397. PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
  3398. PyMem_RawFree(wstr);
  3399. return unicode;
  3400. }
  3401. PyObject*
  3402. PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
  3403. const char *errors)
  3404. {
  3405. _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
  3406. return unicode_decode_locale(str, len, error_handler, 1);
  3407. }
  3408. PyObject*
  3409. PyUnicode_DecodeLocale(const char *str, const char *errors)
  3410. {
  3411. Py_ssize_t size = (Py_ssize_t)strlen(str);
  3412. _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
  3413. return unicode_decode_locale(str, size, error_handler, 1);
  3414. }
  3415. PyObject*
  3416. PyUnicode_DecodeFSDefault(const char *s) {
  3417. Py_ssize_t size = (Py_ssize_t)strlen(s);
  3418. return PyUnicode_DecodeFSDefaultAndSize(s, size);
  3419. }
  3420. PyObject*
  3421. PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
  3422. {
  3423. PyInterpreterState *interp = _PyInterpreterState_GET();
  3424. struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
  3425. if (fs_codec->utf8) {
  3426. return unicode_decode_utf8(s, size,
  3427. fs_codec->error_handler,
  3428. fs_codec->errors,
  3429. NULL);
  3430. }
  3431. #ifndef _Py_FORCE_UTF8_FS_ENCODING
  3432. else if (fs_codec->encoding) {
  3433. return PyUnicode_Decode(s, size,
  3434. fs_codec->encoding,
  3435. fs_codec->errors);
  3436. }
  3437. #endif
  3438. else {
  3439. /* Before _PyUnicode_InitEncodings() is called, the Python codec
  3440. machinery is not ready and so cannot be used:
  3441. use mbstowcs() in this case. */
  3442. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  3443. const wchar_t *filesystem_errors = config->filesystem_errors;
  3444. assert(filesystem_errors != NULL);
  3445. _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
  3446. assert(errors != _Py_ERROR_UNKNOWN);
  3447. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  3448. return unicode_decode_utf8(s, size, errors, NULL, NULL);
  3449. #else
  3450. return unicode_decode_locale(s, size, errors, 0);
  3451. #endif
  3452. }
  3453. }
  3454. int
  3455. PyUnicode_FSConverter(PyObject* arg, void* addr)
  3456. {
  3457. PyObject *path = NULL;
  3458. PyObject *output = NULL;
  3459. Py_ssize_t size;
  3460. const char *data;
  3461. if (arg == NULL) {
  3462. Py_DECREF(*(PyObject**)addr);
  3463. *(PyObject**)addr = NULL;
  3464. return 1;
  3465. }
  3466. path = PyOS_FSPath(arg);
  3467. if (path == NULL) {
  3468. return 0;
  3469. }
  3470. if (PyBytes_Check(path)) {
  3471. output = path;
  3472. }
  3473. else { // PyOS_FSPath() guarantees its returned value is bytes or str.
  3474. output = PyUnicode_EncodeFSDefault(path);
  3475. Py_DECREF(path);
  3476. if (!output) {
  3477. return 0;
  3478. }
  3479. assert(PyBytes_Check(output));
  3480. }
  3481. size = PyBytes_GET_SIZE(output);
  3482. data = PyBytes_AS_STRING(output);
  3483. if ((size_t)size != strlen(data)) {
  3484. PyErr_SetString(PyExc_ValueError, "embedded null byte");
  3485. Py_DECREF(output);
  3486. return 0;
  3487. }
  3488. *(PyObject**)addr = output;
  3489. return Py_CLEANUP_SUPPORTED;
  3490. }
  3491. int
  3492. PyUnicode_FSDecoder(PyObject* arg, void* addr)
  3493. {
  3494. if (arg == NULL) {
  3495. Py_DECREF(*(PyObject**)addr);
  3496. *(PyObject**)addr = NULL;
  3497. return 1;
  3498. }
  3499. PyObject *path = PyOS_FSPath(arg);
  3500. if (path == NULL) {
  3501. return 0;
  3502. }
  3503. PyObject *output = NULL;
  3504. if (PyUnicode_Check(path)) {
  3505. output = path;
  3506. }
  3507. else if (PyBytes_Check(path)) {
  3508. output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path),
  3509. PyBytes_GET_SIZE(path));
  3510. Py_DECREF(path);
  3511. if (!output) {
  3512. return 0;
  3513. }
  3514. }
  3515. else {
  3516. PyErr_Format(PyExc_TypeError,
  3517. "path should be string, bytes, or os.PathLike, not %.200s",
  3518. Py_TYPE(arg)->tp_name);
  3519. Py_DECREF(path);
  3520. return 0;
  3521. }
  3522. if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
  3523. PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
  3524. PyErr_SetString(PyExc_ValueError, "embedded null character");
  3525. Py_DECREF(output);
  3526. return 0;
  3527. }
  3528. *(PyObject**)addr = output;
  3529. return Py_CLEANUP_SUPPORTED;
  3530. }
  3531. static int unicode_fill_utf8(PyObject *unicode);
  3532. const char *
  3533. PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
  3534. {
  3535. if (!PyUnicode_Check(unicode)) {
  3536. PyErr_BadArgument();
  3537. return NULL;
  3538. }
  3539. if (PyUnicode_UTF8(unicode) == NULL) {
  3540. if (unicode_fill_utf8(unicode) == -1) {
  3541. return NULL;
  3542. }
  3543. }
  3544. if (psize)
  3545. *psize = PyUnicode_UTF8_LENGTH(unicode);
  3546. return PyUnicode_UTF8(unicode);
  3547. }
  3548. const char *
  3549. PyUnicode_AsUTF8(PyObject *unicode)
  3550. {
  3551. return PyUnicode_AsUTF8AndSize(unicode, NULL);
  3552. }
  3553. /*
  3554. PyUnicode_GetSize() has been deprecated since Python 3.3
  3555. because it returned length of Py_UNICODE.
  3556. But this function is part of stable abi, because it don't
  3557. include Py_UNICODE in signature and it was not excluded from
  3558. stable abi in PEP 384.
  3559. */
  3560. PyAPI_FUNC(Py_ssize_t)
  3561. PyUnicode_GetSize(PyObject *unicode)
  3562. {
  3563. PyErr_SetString(PyExc_RuntimeError,
  3564. "PyUnicode_GetSize has been removed.");
  3565. return -1;
  3566. }
  3567. Py_ssize_t
  3568. PyUnicode_GetLength(PyObject *unicode)
  3569. {
  3570. if (!PyUnicode_Check(unicode)) {
  3571. PyErr_BadArgument();
  3572. return -1;
  3573. }
  3574. return PyUnicode_GET_LENGTH(unicode);
  3575. }
  3576. Py_UCS4
  3577. PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
  3578. {
  3579. const void *data;
  3580. int kind;
  3581. if (!PyUnicode_Check(unicode)) {
  3582. PyErr_BadArgument();
  3583. return (Py_UCS4)-1;
  3584. }
  3585. if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
  3586. PyErr_SetString(PyExc_IndexError, "string index out of range");
  3587. return (Py_UCS4)-1;
  3588. }
  3589. data = PyUnicode_DATA(unicode);
  3590. kind = PyUnicode_KIND(unicode);
  3591. return PyUnicode_READ(kind, data, index);
  3592. }
  3593. int
  3594. PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
  3595. {
  3596. if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
  3597. PyErr_BadArgument();
  3598. return -1;
  3599. }
  3600. if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
  3601. PyErr_SetString(PyExc_IndexError, "string index out of range");
  3602. return -1;
  3603. }
  3604. if (unicode_check_modifiable(unicode))
  3605. return -1;
  3606. if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
  3607. PyErr_SetString(PyExc_ValueError, "character out of range");
  3608. return -1;
  3609. }
  3610. PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
  3611. index, ch);
  3612. return 0;
  3613. }
  3614. const char *
  3615. PyUnicode_GetDefaultEncoding(void)
  3616. {
  3617. return "utf-8";
  3618. }
  3619. /* create or adjust a UnicodeDecodeError */
  3620. static void
  3621. make_decode_exception(PyObject **exceptionObject,
  3622. const char *encoding,
  3623. const char *input, Py_ssize_t length,
  3624. Py_ssize_t startpos, Py_ssize_t endpos,
  3625. const char *reason)
  3626. {
  3627. if (*exceptionObject == NULL) {
  3628. *exceptionObject = PyUnicodeDecodeError_Create(
  3629. encoding, input, length, startpos, endpos, reason);
  3630. }
  3631. else {
  3632. if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
  3633. goto onError;
  3634. if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
  3635. goto onError;
  3636. if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
  3637. goto onError;
  3638. }
  3639. return;
  3640. onError:
  3641. Py_CLEAR(*exceptionObject);
  3642. }
  3643. #ifdef MS_WINDOWS
  3644. static int
  3645. widechar_resize(wchar_t **buf, Py_ssize_t *size, Py_ssize_t newsize)
  3646. {
  3647. if (newsize > *size) {
  3648. wchar_t *newbuf = *buf;
  3649. if (PyMem_Resize(newbuf, wchar_t, newsize) == NULL) {
  3650. PyErr_NoMemory();
  3651. return -1;
  3652. }
  3653. *buf = newbuf;
  3654. }
  3655. *size = newsize;
  3656. return 0;
  3657. }
  3658. /* error handling callback helper:
  3659. build arguments, call the callback and check the arguments,
  3660. if no exception occurred, copy the replacement to the output
  3661. and adjust various state variables.
  3662. return 0 on success, -1 on error
  3663. */
  3664. static int
  3665. unicode_decode_call_errorhandler_wchar(
  3666. const char *errors, PyObject **errorHandler,
  3667. const char *encoding, const char *reason,
  3668. const char **input, const char **inend, Py_ssize_t *startinpos,
  3669. Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
  3670. wchar_t **buf, Py_ssize_t *bufsize, Py_ssize_t *outpos)
  3671. {
  3672. static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
  3673. PyObject *restuple = NULL;
  3674. PyObject *repunicode = NULL;
  3675. Py_ssize_t outsize;
  3676. Py_ssize_t insize;
  3677. Py_ssize_t requiredsize;
  3678. Py_ssize_t newpos;
  3679. PyObject *inputobj = NULL;
  3680. Py_ssize_t repwlen;
  3681. if (*errorHandler == NULL) {
  3682. *errorHandler = PyCodec_LookupError(errors);
  3683. if (*errorHandler == NULL)
  3684. goto onError;
  3685. }
  3686. make_decode_exception(exceptionObject,
  3687. encoding,
  3688. *input, *inend - *input,
  3689. *startinpos, *endinpos,
  3690. reason);
  3691. if (*exceptionObject == NULL)
  3692. goto onError;
  3693. restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
  3694. if (restuple == NULL)
  3695. goto onError;
  3696. if (!PyTuple_Check(restuple)) {
  3697. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  3698. goto onError;
  3699. }
  3700. if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
  3701. goto onError;
  3702. /* Copy back the bytes variables, which might have been modified by the
  3703. callback */
  3704. inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
  3705. if (!inputobj)
  3706. goto onError;
  3707. *input = PyBytes_AS_STRING(inputobj);
  3708. insize = PyBytes_GET_SIZE(inputobj);
  3709. *inend = *input + insize;
  3710. /* we can DECREF safely, as the exception has another reference,
  3711. so the object won't go away. */
  3712. Py_DECREF(inputobj);
  3713. if (newpos<0)
  3714. newpos = insize+newpos;
  3715. if (newpos<0 || newpos>insize) {
  3716. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
  3717. goto onError;
  3718. }
  3719. repwlen = PyUnicode_AsWideChar(repunicode, NULL, 0);
  3720. if (repwlen < 0)
  3721. goto onError;
  3722. repwlen--;
  3723. /* need more space? (at least enough for what we
  3724. have+the replacement+the rest of the string (starting
  3725. at the new input position), so we won't have to check space
  3726. when there are no errors in the rest of the string) */
  3727. requiredsize = *outpos;
  3728. if (requiredsize > PY_SSIZE_T_MAX - repwlen)
  3729. goto overflow;
  3730. requiredsize += repwlen;
  3731. if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
  3732. goto overflow;
  3733. requiredsize += insize - newpos;
  3734. outsize = *bufsize;
  3735. if (requiredsize > outsize) {
  3736. if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
  3737. requiredsize = 2*outsize;
  3738. if (widechar_resize(buf, bufsize, requiredsize) < 0) {
  3739. goto onError;
  3740. }
  3741. }
  3742. PyUnicode_AsWideChar(repunicode, *buf + *outpos, repwlen);
  3743. *outpos += repwlen;
  3744. *endinpos = newpos;
  3745. *inptr = *input + newpos;
  3746. /* we made it! */
  3747. Py_DECREF(restuple);
  3748. return 0;
  3749. overflow:
  3750. PyErr_SetString(PyExc_OverflowError,
  3751. "decoded result is too long for a Python string");
  3752. onError:
  3753. Py_XDECREF(restuple);
  3754. return -1;
  3755. }
  3756. #endif /* MS_WINDOWS */
  3757. static int
  3758. unicode_decode_call_errorhandler_writer(
  3759. const char *errors, PyObject **errorHandler,
  3760. const char *encoding, const char *reason,
  3761. const char **input, const char **inend, Py_ssize_t *startinpos,
  3762. Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
  3763. _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
  3764. {
  3765. static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
  3766. PyObject *restuple = NULL;
  3767. PyObject *repunicode = NULL;
  3768. Py_ssize_t insize;
  3769. Py_ssize_t newpos;
  3770. Py_ssize_t replen;
  3771. Py_ssize_t remain;
  3772. PyObject *inputobj = NULL;
  3773. int need_to_grow = 0;
  3774. const char *new_inptr;
  3775. if (*errorHandler == NULL) {
  3776. *errorHandler = PyCodec_LookupError(errors);
  3777. if (*errorHandler == NULL)
  3778. goto onError;
  3779. }
  3780. make_decode_exception(exceptionObject,
  3781. encoding,
  3782. *input, *inend - *input,
  3783. *startinpos, *endinpos,
  3784. reason);
  3785. if (*exceptionObject == NULL)
  3786. goto onError;
  3787. restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
  3788. if (restuple == NULL)
  3789. goto onError;
  3790. if (!PyTuple_Check(restuple)) {
  3791. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  3792. goto onError;
  3793. }
  3794. if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
  3795. goto onError;
  3796. /* Copy back the bytes variables, which might have been modified by the
  3797. callback */
  3798. inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
  3799. if (!inputobj)
  3800. goto onError;
  3801. remain = *inend - *input - *endinpos;
  3802. *input = PyBytes_AS_STRING(inputobj);
  3803. insize = PyBytes_GET_SIZE(inputobj);
  3804. *inend = *input + insize;
  3805. /* we can DECREF safely, as the exception has another reference,
  3806. so the object won't go away. */
  3807. Py_DECREF(inputobj);
  3808. if (newpos<0)
  3809. newpos = insize+newpos;
  3810. if (newpos<0 || newpos>insize) {
  3811. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
  3812. goto onError;
  3813. }
  3814. replen = PyUnicode_GET_LENGTH(repunicode);
  3815. if (replen > 1) {
  3816. writer->min_length += replen - 1;
  3817. need_to_grow = 1;
  3818. }
  3819. new_inptr = *input + newpos;
  3820. if (*inend - new_inptr > remain) {
  3821. /* We don't know the decoding algorithm here so we make the worst
  3822. assumption that one byte decodes to one unicode character.
  3823. If unfortunately one byte could decode to more unicode characters,
  3824. the decoder may write out-of-bound then. Is it possible for the
  3825. algorithms using this function? */
  3826. writer->min_length += *inend - new_inptr - remain;
  3827. need_to_grow = 1;
  3828. }
  3829. if (need_to_grow) {
  3830. writer->overallocate = 1;
  3831. if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
  3832. PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
  3833. goto onError;
  3834. }
  3835. if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
  3836. goto onError;
  3837. *endinpos = newpos;
  3838. *inptr = new_inptr;
  3839. /* we made it! */
  3840. Py_DECREF(restuple);
  3841. return 0;
  3842. onError:
  3843. Py_XDECREF(restuple);
  3844. return -1;
  3845. }
  3846. /* --- UTF-7 Codec -------------------------------------------------------- */
  3847. /* See RFC2152 for details. We encode conservatively and decode liberally. */
  3848. /* Three simple macros defining base-64. */
  3849. /* Is c a base-64 character? */
  3850. #define IS_BASE64(c) \
  3851. (((c) >= 'A' && (c) <= 'Z') || \
  3852. ((c) >= 'a' && (c) <= 'z') || \
  3853. ((c) >= '0' && (c) <= '9') || \
  3854. (c) == '+' || (c) == '/')
  3855. /* given that c is a base-64 character, what is its base-64 value? */
  3856. #define FROM_BASE64(c) \
  3857. (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
  3858. ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
  3859. ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
  3860. (c) == '+' ? 62 : 63)
  3861. /* What is the base-64 character of the bottom 6 bits of n? */
  3862. #define TO_BASE64(n) \
  3863. ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
  3864. /* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
  3865. * decoded as itself. We are permissive on decoding; the only ASCII
  3866. * byte not decoding to itself is the + which begins a base64
  3867. * string. */
  3868. #define DECODE_DIRECT(c) \
  3869. ((c) <= 127 && (c) != '+')
  3870. /* The UTF-7 encoder treats ASCII characters differently according to
  3871. * whether they are Set D, Set O, Whitespace, or special (i.e. none of
  3872. * the above). See RFC2152. This array identifies these different
  3873. * sets:
  3874. * 0 : "Set D"
  3875. * alphanumeric and '(),-./:?
  3876. * 1 : "Set O"
  3877. * !"#$%&*;<=>@[]^_`{|}
  3878. * 2 : "whitespace"
  3879. * ht nl cr sp
  3880. * 3 : special (must be base64 encoded)
  3881. * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
  3882. */
  3883. static
  3884. char utf7_category[128] = {
  3885. /* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
  3886. 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
  3887. /* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
  3888. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  3889. /* sp ! " # $ % & ' ( ) * + , - . / */
  3890. 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
  3891. /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
  3892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
  3893. /* @ A B C D E F G H I J K L M N O */
  3894. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  3895. /* P Q R S T U V W X Y Z [ \ ] ^ _ */
  3896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
  3897. /* ` a b c d e f g h i j k l m n o */
  3898. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  3899. /* p q r s t u v w x y z { | } ~ del */
  3900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
  3901. };
  3902. /* ENCODE_DIRECT: this character should be encoded as itself. The
  3903. * answer depends on whether we are encoding set O as itself, and also
  3904. * on whether we are encoding whitespace as itself. RFC2152 makes it
  3905. * clear that the answers to these questions vary between
  3906. * applications, so this code needs to be flexible. */
  3907. #define ENCODE_DIRECT(c, directO, directWS) \
  3908. ((c) < 128 && (c) > 0 && \
  3909. ((utf7_category[(c)] == 0) || \
  3910. (directWS && (utf7_category[(c)] == 2)) || \
  3911. (directO && (utf7_category[(c)] == 1))))
  3912. PyObject *
  3913. PyUnicode_DecodeUTF7(const char *s,
  3914. Py_ssize_t size,
  3915. const char *errors)
  3916. {
  3917. return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
  3918. }
  3919. /* The decoder. The only state we preserve is our read position,
  3920. * i.e. how many characters we have consumed. So if we end in the
  3921. * middle of a shift sequence we have to back off the read position
  3922. * and the output to the beginning of the sequence, otherwise we lose
  3923. * all the shift state (seen bits, number of bits seen, high
  3924. * surrogate). */
  3925. PyObject *
  3926. PyUnicode_DecodeUTF7Stateful(const char *s,
  3927. Py_ssize_t size,
  3928. const char *errors,
  3929. Py_ssize_t *consumed)
  3930. {
  3931. const char *starts = s;
  3932. Py_ssize_t startinpos;
  3933. Py_ssize_t endinpos;
  3934. const char *e;
  3935. _PyUnicodeWriter writer;
  3936. const char *errmsg = "";
  3937. int inShift = 0;
  3938. Py_ssize_t shiftOutStart;
  3939. unsigned int base64bits = 0;
  3940. unsigned long base64buffer = 0;
  3941. Py_UCS4 surrogate = 0;
  3942. PyObject *errorHandler = NULL;
  3943. PyObject *exc = NULL;
  3944. if (size == 0) {
  3945. if (consumed)
  3946. *consumed = 0;
  3947. _Py_RETURN_UNICODE_EMPTY();
  3948. }
  3949. /* Start off assuming it's all ASCII. Widen later as necessary. */
  3950. _PyUnicodeWriter_Init(&writer);
  3951. writer.min_length = size;
  3952. shiftOutStart = 0;
  3953. e = s + size;
  3954. while (s < e) {
  3955. Py_UCS4 ch;
  3956. restart:
  3957. ch = (unsigned char) *s;
  3958. if (inShift) { /* in a base-64 section */
  3959. if (IS_BASE64(ch)) { /* consume a base-64 character */
  3960. base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
  3961. base64bits += 6;
  3962. s++;
  3963. if (base64bits >= 16) {
  3964. /* we have enough bits for a UTF-16 value */
  3965. Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
  3966. base64bits -= 16;
  3967. base64buffer &= (1 << base64bits) - 1; /* clear high bits */
  3968. assert(outCh <= 0xffff);
  3969. if (surrogate) {
  3970. /* expecting a second surrogate */
  3971. if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
  3972. Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
  3973. if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
  3974. goto onError;
  3975. surrogate = 0;
  3976. continue;
  3977. }
  3978. else {
  3979. if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
  3980. goto onError;
  3981. surrogate = 0;
  3982. }
  3983. }
  3984. if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
  3985. /* first surrogate */
  3986. surrogate = outCh;
  3987. }
  3988. else {
  3989. if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
  3990. goto onError;
  3991. }
  3992. }
  3993. }
  3994. else { /* now leaving a base-64 section */
  3995. inShift = 0;
  3996. if (base64bits > 0) { /* left-over bits */
  3997. if (base64bits >= 6) {
  3998. /* We've seen at least one base-64 character */
  3999. s++;
  4000. errmsg = "partial character in shift sequence";
  4001. goto utf7Error;
  4002. }
  4003. else {
  4004. /* Some bits remain; they should be zero */
  4005. if (base64buffer != 0) {
  4006. s++;
  4007. errmsg = "non-zero padding bits in shift sequence";
  4008. goto utf7Error;
  4009. }
  4010. }
  4011. }
  4012. if (surrogate && DECODE_DIRECT(ch)) {
  4013. if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
  4014. goto onError;
  4015. }
  4016. surrogate = 0;
  4017. if (ch == '-') {
  4018. /* '-' is absorbed; other terminating
  4019. characters are preserved */
  4020. s++;
  4021. }
  4022. }
  4023. }
  4024. else if ( ch == '+' ) {
  4025. startinpos = s-starts;
  4026. s++; /* consume '+' */
  4027. if (s < e && *s == '-') { /* '+-' encodes '+' */
  4028. s++;
  4029. if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
  4030. goto onError;
  4031. }
  4032. else if (s < e && !IS_BASE64(*s)) {
  4033. s++;
  4034. errmsg = "ill-formed sequence";
  4035. goto utf7Error;
  4036. }
  4037. else { /* begin base64-encoded section */
  4038. inShift = 1;
  4039. surrogate = 0;
  4040. shiftOutStart = writer.pos;
  4041. base64bits = 0;
  4042. base64buffer = 0;
  4043. }
  4044. }
  4045. else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
  4046. s++;
  4047. if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
  4048. goto onError;
  4049. }
  4050. else {
  4051. startinpos = s-starts;
  4052. s++;
  4053. errmsg = "unexpected special character";
  4054. goto utf7Error;
  4055. }
  4056. continue;
  4057. utf7Error:
  4058. endinpos = s-starts;
  4059. if (unicode_decode_call_errorhandler_writer(
  4060. errors, &errorHandler,
  4061. "utf7", errmsg,
  4062. &starts, &e, &startinpos, &endinpos, &exc, &s,
  4063. &writer))
  4064. goto onError;
  4065. }
  4066. /* end of string */
  4067. if (inShift && !consumed) { /* in shift sequence, no more to follow */
  4068. /* if we're in an inconsistent state, that's an error */
  4069. inShift = 0;
  4070. if (surrogate ||
  4071. (base64bits >= 6) ||
  4072. (base64bits > 0 && base64buffer != 0)) {
  4073. endinpos = size;
  4074. if (unicode_decode_call_errorhandler_writer(
  4075. errors, &errorHandler,
  4076. "utf7", "unterminated shift sequence",
  4077. &starts, &e, &startinpos, &endinpos, &exc, &s,
  4078. &writer))
  4079. goto onError;
  4080. if (s < e)
  4081. goto restart;
  4082. }
  4083. }
  4084. /* return state */
  4085. if (consumed) {
  4086. if (inShift) {
  4087. *consumed = startinpos;
  4088. if (writer.pos != shiftOutStart && writer.maxchar > 127) {
  4089. PyObject *result = PyUnicode_FromKindAndData(
  4090. writer.kind, writer.data, shiftOutStart);
  4091. Py_XDECREF(errorHandler);
  4092. Py_XDECREF(exc);
  4093. _PyUnicodeWriter_Dealloc(&writer);
  4094. return result;
  4095. }
  4096. writer.pos = shiftOutStart; /* back off output */
  4097. }
  4098. else {
  4099. *consumed = s-starts;
  4100. }
  4101. }
  4102. Py_XDECREF(errorHandler);
  4103. Py_XDECREF(exc);
  4104. return _PyUnicodeWriter_Finish(&writer);
  4105. onError:
  4106. Py_XDECREF(errorHandler);
  4107. Py_XDECREF(exc);
  4108. _PyUnicodeWriter_Dealloc(&writer);
  4109. return NULL;
  4110. }
  4111. PyObject *
  4112. _PyUnicode_EncodeUTF7(PyObject *str,
  4113. int base64SetO,
  4114. int base64WhiteSpace,
  4115. const char *errors)
  4116. {
  4117. int kind;
  4118. const void *data;
  4119. Py_ssize_t len;
  4120. PyObject *v;
  4121. int inShift = 0;
  4122. Py_ssize_t i;
  4123. unsigned int base64bits = 0;
  4124. unsigned long base64buffer = 0;
  4125. char * out;
  4126. const char * start;
  4127. kind = PyUnicode_KIND(str);
  4128. data = PyUnicode_DATA(str);
  4129. len = PyUnicode_GET_LENGTH(str);
  4130. if (len == 0)
  4131. return PyBytes_FromStringAndSize(NULL, 0);
  4132. /* It might be possible to tighten this worst case */
  4133. if (len > PY_SSIZE_T_MAX / 8)
  4134. return PyErr_NoMemory();
  4135. v = PyBytes_FromStringAndSize(NULL, len * 8);
  4136. if (v == NULL)
  4137. return NULL;
  4138. start = out = PyBytes_AS_STRING(v);
  4139. for (i = 0; i < len; ++i) {
  4140. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  4141. if (inShift) {
  4142. if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
  4143. /* shifting out */
  4144. if (base64bits) { /* output remaining bits */
  4145. *out++ = TO_BASE64(base64buffer << (6-base64bits));
  4146. base64buffer = 0;
  4147. base64bits = 0;
  4148. }
  4149. inShift = 0;
  4150. /* Characters not in the BASE64 set implicitly unshift the sequence
  4151. so no '-' is required, except if the character is itself a '-' */
  4152. if (IS_BASE64(ch) || ch == '-') {
  4153. *out++ = '-';
  4154. }
  4155. *out++ = (char) ch;
  4156. }
  4157. else {
  4158. goto encode_char;
  4159. }
  4160. }
  4161. else { /* not in a shift sequence */
  4162. if (ch == '+') {
  4163. *out++ = '+';
  4164. *out++ = '-';
  4165. }
  4166. else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
  4167. *out++ = (char) ch;
  4168. }
  4169. else {
  4170. *out++ = '+';
  4171. inShift = 1;
  4172. goto encode_char;
  4173. }
  4174. }
  4175. continue;
  4176. encode_char:
  4177. if (ch >= 0x10000) {
  4178. assert(ch <= MAX_UNICODE);
  4179. /* code first surrogate */
  4180. base64bits += 16;
  4181. base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
  4182. while (base64bits >= 6) {
  4183. *out++ = TO_BASE64(base64buffer >> (base64bits-6));
  4184. base64bits -= 6;
  4185. }
  4186. /* prepare second surrogate */
  4187. ch = Py_UNICODE_LOW_SURROGATE(ch);
  4188. }
  4189. base64bits += 16;
  4190. base64buffer = (base64buffer << 16) | ch;
  4191. while (base64bits >= 6) {
  4192. *out++ = TO_BASE64(base64buffer >> (base64bits-6));
  4193. base64bits -= 6;
  4194. }
  4195. }
  4196. if (base64bits)
  4197. *out++= TO_BASE64(base64buffer << (6-base64bits) );
  4198. if (inShift)
  4199. *out++ = '-';
  4200. if (_PyBytes_Resize(&v, out - start) < 0)
  4201. return NULL;
  4202. return v;
  4203. }
  4204. #undef IS_BASE64
  4205. #undef FROM_BASE64
  4206. #undef TO_BASE64
  4207. #undef DECODE_DIRECT
  4208. #undef ENCODE_DIRECT
  4209. /* --- UTF-8 Codec -------------------------------------------------------- */
  4210. PyObject *
  4211. PyUnicode_DecodeUTF8(const char *s,
  4212. Py_ssize_t size,
  4213. const char *errors)
  4214. {
  4215. return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
  4216. }
  4217. #include "stringlib/asciilib.h"
  4218. #include "stringlib/codecs.h"
  4219. #include "stringlib/undef.h"
  4220. #include "stringlib/ucs1lib.h"
  4221. #include "stringlib/codecs.h"
  4222. #include "stringlib/undef.h"
  4223. #include "stringlib/ucs2lib.h"
  4224. #include "stringlib/codecs.h"
  4225. #include "stringlib/undef.h"
  4226. #include "stringlib/ucs4lib.h"
  4227. #include "stringlib/codecs.h"
  4228. #include "stringlib/undef.h"
  4229. /* Mask to quickly check whether a C 'size_t' contains a
  4230. non-ASCII, UTF8-encoded char. */
  4231. #if (SIZEOF_SIZE_T == 8)
  4232. # define ASCII_CHAR_MASK 0x8080808080808080ULL
  4233. #elif (SIZEOF_SIZE_T == 4)
  4234. # define ASCII_CHAR_MASK 0x80808080U
  4235. #else
  4236. # error C 'size_t' size should be either 4 or 8!
  4237. #endif
  4238. static Py_ssize_t
  4239. ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
  4240. {
  4241. const char *p = start;
  4242. #if SIZEOF_SIZE_T <= SIZEOF_VOID_P
  4243. assert(_Py_IS_ALIGNED(dest, ALIGNOF_SIZE_T));
  4244. if (_Py_IS_ALIGNED(p, ALIGNOF_SIZE_T)) {
  4245. /* Fast path, see in STRINGLIB(utf8_decode) for
  4246. an explanation. */
  4247. /* Help allocation */
  4248. const char *_p = p;
  4249. Py_UCS1 * q = dest;
  4250. while (_p + SIZEOF_SIZE_T <= end) {
  4251. size_t value = *(const size_t *) _p;
  4252. if (value & ASCII_CHAR_MASK)
  4253. break;
  4254. *((size_t *)q) = value;
  4255. _p += SIZEOF_SIZE_T;
  4256. q += SIZEOF_SIZE_T;
  4257. }
  4258. p = _p;
  4259. while (p < end) {
  4260. if ((unsigned char)*p & 0x80)
  4261. break;
  4262. *q++ = *p++;
  4263. }
  4264. return p - start;
  4265. }
  4266. #endif
  4267. while (p < end) {
  4268. /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
  4269. for an explanation. */
  4270. if (_Py_IS_ALIGNED(p, ALIGNOF_SIZE_T)) {
  4271. /* Help allocation */
  4272. const char *_p = p;
  4273. while (_p + SIZEOF_SIZE_T <= end) {
  4274. size_t value = *(const size_t *) _p;
  4275. if (value & ASCII_CHAR_MASK)
  4276. break;
  4277. _p += SIZEOF_SIZE_T;
  4278. }
  4279. p = _p;
  4280. if (_p == end)
  4281. break;
  4282. }
  4283. if ((unsigned char)*p & 0x80)
  4284. break;
  4285. ++p;
  4286. }
  4287. memcpy(dest, start, p - start);
  4288. return p - start;
  4289. }
  4290. static PyObject *
  4291. unicode_decode_utf8(const char *s, Py_ssize_t size,
  4292. _Py_error_handler error_handler, const char *errors,
  4293. Py_ssize_t *consumed)
  4294. {
  4295. if (size == 0) {
  4296. if (consumed)
  4297. *consumed = 0;
  4298. _Py_RETURN_UNICODE_EMPTY();
  4299. }
  4300. /* ASCII is equivalent to the first 128 ordinals in Unicode. */
  4301. if (size == 1 && (unsigned char)s[0] < 128) {
  4302. if (consumed) {
  4303. *consumed = 1;
  4304. }
  4305. return get_latin1_char((unsigned char)s[0]);
  4306. }
  4307. const char *starts = s;
  4308. const char *end = s + size;
  4309. // fast path: try ASCII string.
  4310. PyObject *u = PyUnicode_New(size, 127);
  4311. if (u == NULL) {
  4312. return NULL;
  4313. }
  4314. s += ascii_decode(s, end, PyUnicode_1BYTE_DATA(u));
  4315. if (s == end) {
  4316. if (consumed) {
  4317. *consumed = size;
  4318. }
  4319. return u;
  4320. }
  4321. // Use _PyUnicodeWriter after fast path is failed.
  4322. _PyUnicodeWriter writer;
  4323. _PyUnicodeWriter_InitWithBuffer(&writer, u);
  4324. writer.pos = s - starts;
  4325. Py_ssize_t startinpos, endinpos;
  4326. const char *errmsg = "";
  4327. PyObject *error_handler_obj = NULL;
  4328. PyObject *exc = NULL;
  4329. while (s < end) {
  4330. Py_UCS4 ch;
  4331. int kind = writer.kind;
  4332. if (kind == PyUnicode_1BYTE_KIND) {
  4333. if (PyUnicode_IS_ASCII(writer.buffer))
  4334. ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
  4335. else
  4336. ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
  4337. } else if (kind == PyUnicode_2BYTE_KIND) {
  4338. ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
  4339. } else {
  4340. assert(kind == PyUnicode_4BYTE_KIND);
  4341. ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
  4342. }
  4343. switch (ch) {
  4344. case 0:
  4345. if (s == end || consumed)
  4346. goto End;
  4347. errmsg = "unexpected end of data";
  4348. startinpos = s - starts;
  4349. endinpos = end - starts;
  4350. break;
  4351. case 1:
  4352. errmsg = "invalid start byte";
  4353. startinpos = s - starts;
  4354. endinpos = startinpos + 1;
  4355. break;
  4356. case 2:
  4357. if (consumed && (unsigned char)s[0] == 0xED && end - s == 2
  4358. && (unsigned char)s[1] >= 0xA0 && (unsigned char)s[1] <= 0xBF)
  4359. {
  4360. /* Truncated surrogate code in range D800-DFFF */
  4361. goto End;
  4362. }
  4363. /* fall through */
  4364. case 3:
  4365. case 4:
  4366. errmsg = "invalid continuation byte";
  4367. startinpos = s - starts;
  4368. endinpos = startinpos + ch - 1;
  4369. break;
  4370. default:
  4371. if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
  4372. goto onError;
  4373. continue;
  4374. }
  4375. if (error_handler == _Py_ERROR_UNKNOWN)
  4376. error_handler = _Py_GetErrorHandler(errors);
  4377. switch (error_handler) {
  4378. case _Py_ERROR_IGNORE:
  4379. s += (endinpos - startinpos);
  4380. break;
  4381. case _Py_ERROR_REPLACE:
  4382. if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
  4383. goto onError;
  4384. s += (endinpos - startinpos);
  4385. break;
  4386. case _Py_ERROR_SURROGATEESCAPE:
  4387. {
  4388. Py_ssize_t i;
  4389. if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
  4390. goto onError;
  4391. for (i=startinpos; i<endinpos; i++) {
  4392. ch = (Py_UCS4)(unsigned char)(starts[i]);
  4393. PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
  4394. ch + 0xdc00);
  4395. writer.pos++;
  4396. }
  4397. s += (endinpos - startinpos);
  4398. break;
  4399. }
  4400. default:
  4401. if (unicode_decode_call_errorhandler_writer(
  4402. errors, &error_handler_obj,
  4403. "utf-8", errmsg,
  4404. &starts, &end, &startinpos, &endinpos, &exc, &s,
  4405. &writer))
  4406. goto onError;
  4407. }
  4408. }
  4409. End:
  4410. if (consumed)
  4411. *consumed = s - starts;
  4412. Py_XDECREF(error_handler_obj);
  4413. Py_XDECREF(exc);
  4414. return _PyUnicodeWriter_Finish(&writer);
  4415. onError:
  4416. Py_XDECREF(error_handler_obj);
  4417. Py_XDECREF(exc);
  4418. _PyUnicodeWriter_Dealloc(&writer);
  4419. return NULL;
  4420. }
  4421. PyObject *
  4422. PyUnicode_DecodeUTF8Stateful(const char *s,
  4423. Py_ssize_t size,
  4424. const char *errors,
  4425. Py_ssize_t *consumed)
  4426. {
  4427. return unicode_decode_utf8(s, size, _Py_ERROR_UNKNOWN, errors, consumed);
  4428. }
  4429. /* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
  4430. non-zero, use strict error handler otherwise.
  4431. On success, write a pointer to a newly allocated wide character string into
  4432. *wstr (use PyMem_RawFree() to free the memory) and write the output length
  4433. (in number of wchar_t units) into *wlen (if wlen is set).
  4434. On memory allocation failure, return -1.
  4435. On decoding error (if surrogateescape is zero), return -2. If wlen is
  4436. non-NULL, write the start of the illegal byte sequence into *wlen. If reason
  4437. is not NULL, write the decoding error message into *reason. */
  4438. int
  4439. _Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
  4440. const char **reason, _Py_error_handler errors)
  4441. {
  4442. const char *orig_s = s;
  4443. const char *e;
  4444. wchar_t *unicode;
  4445. Py_ssize_t outpos;
  4446. int surrogateescape = 0;
  4447. int surrogatepass = 0;
  4448. switch (errors)
  4449. {
  4450. case _Py_ERROR_STRICT:
  4451. break;
  4452. case _Py_ERROR_SURROGATEESCAPE:
  4453. surrogateescape = 1;
  4454. break;
  4455. case _Py_ERROR_SURROGATEPASS:
  4456. surrogatepass = 1;
  4457. break;
  4458. default:
  4459. return -3;
  4460. }
  4461. /* Note: size will always be longer than the resulting Unicode
  4462. character count */
  4463. if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1 < size) {
  4464. return -1;
  4465. }
  4466. unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
  4467. if (!unicode) {
  4468. return -1;
  4469. }
  4470. /* Unpack UTF-8 encoded data */
  4471. e = s + size;
  4472. outpos = 0;
  4473. while (s < e) {
  4474. Py_UCS4 ch;
  4475. #if SIZEOF_WCHAR_T == 4
  4476. ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
  4477. #else
  4478. ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
  4479. #endif
  4480. if (ch > 0xFF) {
  4481. #if SIZEOF_WCHAR_T == 4
  4482. Py_UNREACHABLE();
  4483. #else
  4484. assert(ch > 0xFFFF && ch <= MAX_UNICODE);
  4485. /* write a surrogate pair */
  4486. unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
  4487. unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
  4488. #endif
  4489. }
  4490. else {
  4491. if (!ch && s == e) {
  4492. break;
  4493. }
  4494. if (surrogateescape) {
  4495. unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
  4496. }
  4497. else {
  4498. /* Is it a valid three-byte code? */
  4499. if (surrogatepass
  4500. && (e - s) >= 3
  4501. && (s[0] & 0xf0) == 0xe0
  4502. && (s[1] & 0xc0) == 0x80
  4503. && (s[2] & 0xc0) == 0x80)
  4504. {
  4505. ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
  4506. s += 3;
  4507. unicode[outpos++] = ch;
  4508. }
  4509. else {
  4510. PyMem_RawFree(unicode );
  4511. if (reason != NULL) {
  4512. switch (ch) {
  4513. case 0:
  4514. *reason = "unexpected end of data";
  4515. break;
  4516. case 1:
  4517. *reason = "invalid start byte";
  4518. break;
  4519. /* 2, 3, 4 */
  4520. default:
  4521. *reason = "invalid continuation byte";
  4522. break;
  4523. }
  4524. }
  4525. if (wlen != NULL) {
  4526. *wlen = s - orig_s;
  4527. }
  4528. return -2;
  4529. }
  4530. }
  4531. }
  4532. }
  4533. unicode[outpos] = L'\0';
  4534. if (wlen) {
  4535. *wlen = outpos;
  4536. }
  4537. *wstr = unicode;
  4538. return 0;
  4539. }
  4540. wchar_t*
  4541. _Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen,
  4542. size_t *wlen)
  4543. {
  4544. wchar_t *wstr;
  4545. int res = _Py_DecodeUTF8Ex(arg, arglen,
  4546. &wstr, wlen,
  4547. NULL, _Py_ERROR_SURROGATEESCAPE);
  4548. if (res != 0) {
  4549. /* _Py_DecodeUTF8Ex() must support _Py_ERROR_SURROGATEESCAPE */
  4550. assert(res != -3);
  4551. if (wlen) {
  4552. *wlen = (size_t)res;
  4553. }
  4554. return NULL;
  4555. }
  4556. return wstr;
  4557. }
  4558. /* UTF-8 encoder using the surrogateescape error handler .
  4559. On success, return 0 and write the newly allocated character string (use
  4560. PyMem_Free() to free the memory) into *str.
  4561. On encoding failure, return -2 and write the position of the invalid
  4562. surrogate character into *error_pos (if error_pos is set) and the decoding
  4563. error message into *reason (if reason is set).
  4564. On memory allocation failure, return -1. */
  4565. int
  4566. _Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
  4567. const char **reason, int raw_malloc, _Py_error_handler errors)
  4568. {
  4569. const Py_ssize_t max_char_size = 4;
  4570. Py_ssize_t len = wcslen(text);
  4571. assert(len >= 0);
  4572. int surrogateescape = 0;
  4573. int surrogatepass = 0;
  4574. switch (errors)
  4575. {
  4576. case _Py_ERROR_STRICT:
  4577. break;
  4578. case _Py_ERROR_SURROGATEESCAPE:
  4579. surrogateescape = 1;
  4580. break;
  4581. case _Py_ERROR_SURROGATEPASS:
  4582. surrogatepass = 1;
  4583. break;
  4584. default:
  4585. return -3;
  4586. }
  4587. if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
  4588. return -1;
  4589. }
  4590. char *bytes;
  4591. if (raw_malloc) {
  4592. bytes = PyMem_RawMalloc((len + 1) * max_char_size);
  4593. }
  4594. else {
  4595. bytes = PyMem_Malloc((len + 1) * max_char_size);
  4596. }
  4597. if (bytes == NULL) {
  4598. return -1;
  4599. }
  4600. char *p = bytes;
  4601. Py_ssize_t i;
  4602. for (i = 0; i < len; ) {
  4603. Py_ssize_t ch_pos = i;
  4604. Py_UCS4 ch = text[i];
  4605. i++;
  4606. #if Py_UNICODE_SIZE == 2
  4607. if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
  4608. && i < len
  4609. && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
  4610. {
  4611. ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
  4612. i++;
  4613. }
  4614. #endif
  4615. if (ch < 0x80) {
  4616. /* Encode ASCII */
  4617. *p++ = (char) ch;
  4618. }
  4619. else if (ch < 0x0800) {
  4620. /* Encode Latin-1 */
  4621. *p++ = (char)(0xc0 | (ch >> 6));
  4622. *p++ = (char)(0x80 | (ch & 0x3f));
  4623. }
  4624. else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
  4625. /* surrogateescape error handler */
  4626. if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
  4627. if (error_pos != NULL) {
  4628. *error_pos = (size_t)ch_pos;
  4629. }
  4630. if (reason != NULL) {
  4631. *reason = "encoding error";
  4632. }
  4633. if (raw_malloc) {
  4634. PyMem_RawFree(bytes);
  4635. }
  4636. else {
  4637. PyMem_Free(bytes);
  4638. }
  4639. return -2;
  4640. }
  4641. *p++ = (char)(ch & 0xff);
  4642. }
  4643. else if (ch < 0x10000) {
  4644. *p++ = (char)(0xe0 | (ch >> 12));
  4645. *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
  4646. *p++ = (char)(0x80 | (ch & 0x3f));
  4647. }
  4648. else { /* ch >= 0x10000 */
  4649. assert(ch <= MAX_UNICODE);
  4650. /* Encode UCS4 Unicode ordinals */
  4651. *p++ = (char)(0xf0 | (ch >> 18));
  4652. *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
  4653. *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
  4654. *p++ = (char)(0x80 | (ch & 0x3f));
  4655. }
  4656. }
  4657. *p++ = '\0';
  4658. size_t final_size = (p - bytes);
  4659. char *bytes2;
  4660. if (raw_malloc) {
  4661. bytes2 = PyMem_RawRealloc(bytes, final_size);
  4662. }
  4663. else {
  4664. bytes2 = PyMem_Realloc(bytes, final_size);
  4665. }
  4666. if (bytes2 == NULL) {
  4667. if (error_pos != NULL) {
  4668. *error_pos = (size_t)-1;
  4669. }
  4670. if (raw_malloc) {
  4671. PyMem_RawFree(bytes);
  4672. }
  4673. else {
  4674. PyMem_Free(bytes);
  4675. }
  4676. return -1;
  4677. }
  4678. *str = bytes2;
  4679. return 0;
  4680. }
  4681. /* Primary internal function which creates utf8 encoded bytes objects.
  4682. Allocation strategy: if the string is short, convert into a stack buffer
  4683. and allocate exactly as much space needed at the end. Else allocate the
  4684. maximum possible needed (4 result bytes per Unicode character), and return
  4685. the excess memory at the end.
  4686. */
  4687. static PyObject *
  4688. unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
  4689. const char *errors)
  4690. {
  4691. if (!PyUnicode_Check(unicode)) {
  4692. PyErr_BadArgument();
  4693. return NULL;
  4694. }
  4695. if (PyUnicode_UTF8(unicode))
  4696. return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
  4697. PyUnicode_UTF8_LENGTH(unicode));
  4698. int kind = PyUnicode_KIND(unicode);
  4699. const void *data = PyUnicode_DATA(unicode);
  4700. Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
  4701. _PyBytesWriter writer;
  4702. char *end;
  4703. switch (kind) {
  4704. default:
  4705. Py_UNREACHABLE();
  4706. case PyUnicode_1BYTE_KIND:
  4707. /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
  4708. assert(!PyUnicode_IS_ASCII(unicode));
  4709. end = ucs1lib_utf8_encoder(&writer, unicode, data, size, error_handler, errors);
  4710. break;
  4711. case PyUnicode_2BYTE_KIND:
  4712. end = ucs2lib_utf8_encoder(&writer, unicode, data, size, error_handler, errors);
  4713. break;
  4714. case PyUnicode_4BYTE_KIND:
  4715. end = ucs4lib_utf8_encoder(&writer, unicode, data, size, error_handler, errors);
  4716. break;
  4717. }
  4718. if (end == NULL) {
  4719. _PyBytesWriter_Dealloc(&writer);
  4720. return NULL;
  4721. }
  4722. return _PyBytesWriter_Finish(&writer, end);
  4723. }
  4724. static int
  4725. unicode_fill_utf8(PyObject *unicode)
  4726. {
  4727. /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
  4728. assert(!PyUnicode_IS_ASCII(unicode));
  4729. int kind = PyUnicode_KIND(unicode);
  4730. const void *data = PyUnicode_DATA(unicode);
  4731. Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
  4732. _PyBytesWriter writer;
  4733. char *end;
  4734. switch (kind) {
  4735. default:
  4736. Py_UNREACHABLE();
  4737. case PyUnicode_1BYTE_KIND:
  4738. end = ucs1lib_utf8_encoder(&writer, unicode, data, size,
  4739. _Py_ERROR_STRICT, NULL);
  4740. break;
  4741. case PyUnicode_2BYTE_KIND:
  4742. end = ucs2lib_utf8_encoder(&writer, unicode, data, size,
  4743. _Py_ERROR_STRICT, NULL);
  4744. break;
  4745. case PyUnicode_4BYTE_KIND:
  4746. end = ucs4lib_utf8_encoder(&writer, unicode, data, size,
  4747. _Py_ERROR_STRICT, NULL);
  4748. break;
  4749. }
  4750. if (end == NULL) {
  4751. _PyBytesWriter_Dealloc(&writer);
  4752. return -1;
  4753. }
  4754. const char *start = writer.use_small_buffer ? writer.small_buffer :
  4755. PyBytes_AS_STRING(writer.buffer);
  4756. Py_ssize_t len = end - start;
  4757. char *cache = PyObject_Malloc(len + 1);
  4758. if (cache == NULL) {
  4759. _PyBytesWriter_Dealloc(&writer);
  4760. PyErr_NoMemory();
  4761. return -1;
  4762. }
  4763. _PyUnicode_UTF8(unicode) = cache;
  4764. _PyUnicode_UTF8_LENGTH(unicode) = len;
  4765. memcpy(cache, start, len);
  4766. cache[len] = '\0';
  4767. _PyBytesWriter_Dealloc(&writer);
  4768. return 0;
  4769. }
  4770. PyObject *
  4771. _PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
  4772. {
  4773. return unicode_encode_utf8(unicode, _Py_ERROR_UNKNOWN, errors);
  4774. }
  4775. PyObject *
  4776. PyUnicode_AsUTF8String(PyObject *unicode)
  4777. {
  4778. return _PyUnicode_AsUTF8String(unicode, NULL);
  4779. }
  4780. /* --- UTF-32 Codec ------------------------------------------------------- */
  4781. PyObject *
  4782. PyUnicode_DecodeUTF32(const char *s,
  4783. Py_ssize_t size,
  4784. const char *errors,
  4785. int *byteorder)
  4786. {
  4787. return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
  4788. }
  4789. PyObject *
  4790. PyUnicode_DecodeUTF32Stateful(const char *s,
  4791. Py_ssize_t size,
  4792. const char *errors,
  4793. int *byteorder,
  4794. Py_ssize_t *consumed)
  4795. {
  4796. const char *starts = s;
  4797. Py_ssize_t startinpos;
  4798. Py_ssize_t endinpos;
  4799. _PyUnicodeWriter writer;
  4800. const unsigned char *q, *e;
  4801. int le, bo = 0; /* assume native ordering by default */
  4802. const char *encoding;
  4803. const char *errmsg = "";
  4804. PyObject *errorHandler = NULL;
  4805. PyObject *exc = NULL;
  4806. q = (const unsigned char *)s;
  4807. e = q + size;
  4808. if (byteorder)
  4809. bo = *byteorder;
  4810. /* Check for BOM marks (U+FEFF) in the input and adjust current
  4811. byte order setting accordingly. In native mode, the leading BOM
  4812. mark is skipped, in all other modes, it is copied to the output
  4813. stream as-is (giving a ZWNBSP character). */
  4814. if (bo == 0 && size >= 4) {
  4815. Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
  4816. if (bom == 0x0000FEFF) {
  4817. bo = -1;
  4818. q += 4;
  4819. }
  4820. else if (bom == 0xFFFE0000) {
  4821. bo = 1;
  4822. q += 4;
  4823. }
  4824. if (byteorder)
  4825. *byteorder = bo;
  4826. }
  4827. if (q == e) {
  4828. if (consumed)
  4829. *consumed = size;
  4830. _Py_RETURN_UNICODE_EMPTY();
  4831. }
  4832. #ifdef WORDS_BIGENDIAN
  4833. le = bo < 0;
  4834. #else
  4835. le = bo <= 0;
  4836. #endif
  4837. encoding = le ? "utf-32-le" : "utf-32-be";
  4838. _PyUnicodeWriter_Init(&writer);
  4839. writer.min_length = (e - q + 3) / 4;
  4840. if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
  4841. goto onError;
  4842. while (1) {
  4843. Py_UCS4 ch = 0;
  4844. Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
  4845. if (e - q >= 4) {
  4846. int kind = writer.kind;
  4847. void *data = writer.data;
  4848. const unsigned char *last = e - 4;
  4849. Py_ssize_t pos = writer.pos;
  4850. if (le) {
  4851. do {
  4852. ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
  4853. if (ch > maxch)
  4854. break;
  4855. if (kind != PyUnicode_1BYTE_KIND &&
  4856. Py_UNICODE_IS_SURROGATE(ch))
  4857. break;
  4858. PyUnicode_WRITE(kind, data, pos++, ch);
  4859. q += 4;
  4860. } while (q <= last);
  4861. }
  4862. else {
  4863. do {
  4864. ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
  4865. if (ch > maxch)
  4866. break;
  4867. if (kind != PyUnicode_1BYTE_KIND &&
  4868. Py_UNICODE_IS_SURROGATE(ch))
  4869. break;
  4870. PyUnicode_WRITE(kind, data, pos++, ch);
  4871. q += 4;
  4872. } while (q <= last);
  4873. }
  4874. writer.pos = pos;
  4875. }
  4876. if (Py_UNICODE_IS_SURROGATE(ch)) {
  4877. errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
  4878. startinpos = ((const char *)q) - starts;
  4879. endinpos = startinpos + 4;
  4880. }
  4881. else if (ch <= maxch) {
  4882. if (q == e || consumed)
  4883. break;
  4884. /* remaining bytes at the end? (size should be divisible by 4) */
  4885. errmsg = "truncated data";
  4886. startinpos = ((const char *)q) - starts;
  4887. endinpos = ((const char *)e) - starts;
  4888. }
  4889. else {
  4890. if (ch < 0x110000) {
  4891. if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
  4892. goto onError;
  4893. q += 4;
  4894. continue;
  4895. }
  4896. errmsg = "code point not in range(0x110000)";
  4897. startinpos = ((const char *)q) - starts;
  4898. endinpos = startinpos + 4;
  4899. }
  4900. /* The remaining input chars are ignored if the callback
  4901. chooses to skip the input */
  4902. if (unicode_decode_call_errorhandler_writer(
  4903. errors, &errorHandler,
  4904. encoding, errmsg,
  4905. &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
  4906. &writer))
  4907. goto onError;
  4908. }
  4909. if (consumed)
  4910. *consumed = (const char *)q-starts;
  4911. Py_XDECREF(errorHandler);
  4912. Py_XDECREF(exc);
  4913. return _PyUnicodeWriter_Finish(&writer);
  4914. onError:
  4915. _PyUnicodeWriter_Dealloc(&writer);
  4916. Py_XDECREF(errorHandler);
  4917. Py_XDECREF(exc);
  4918. return NULL;
  4919. }
  4920. PyObject *
  4921. _PyUnicode_EncodeUTF32(PyObject *str,
  4922. const char *errors,
  4923. int byteorder)
  4924. {
  4925. int kind;
  4926. const void *data;
  4927. Py_ssize_t len;
  4928. PyObject *v;
  4929. uint32_t *out;
  4930. #if PY_LITTLE_ENDIAN
  4931. int native_ordering = byteorder <= 0;
  4932. #else
  4933. int native_ordering = byteorder >= 0;
  4934. #endif
  4935. const char *encoding;
  4936. Py_ssize_t nsize, pos;
  4937. PyObject *errorHandler = NULL;
  4938. PyObject *exc = NULL;
  4939. PyObject *rep = NULL;
  4940. if (!PyUnicode_Check(str)) {
  4941. PyErr_BadArgument();
  4942. return NULL;
  4943. }
  4944. kind = PyUnicode_KIND(str);
  4945. data = PyUnicode_DATA(str);
  4946. len = PyUnicode_GET_LENGTH(str);
  4947. if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
  4948. return PyErr_NoMemory();
  4949. nsize = len + (byteorder == 0);
  4950. v = PyBytes_FromStringAndSize(NULL, nsize * 4);
  4951. if (v == NULL)
  4952. return NULL;
  4953. /* output buffer is 4-bytes aligned */
  4954. assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
  4955. out = (uint32_t *)PyBytes_AS_STRING(v);
  4956. if (byteorder == 0)
  4957. *out++ = 0xFEFF;
  4958. if (len == 0)
  4959. goto done;
  4960. if (byteorder == -1)
  4961. encoding = "utf-32-le";
  4962. else if (byteorder == 1)
  4963. encoding = "utf-32-be";
  4964. else
  4965. encoding = "utf-32";
  4966. if (kind == PyUnicode_1BYTE_KIND) {
  4967. ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
  4968. goto done;
  4969. }
  4970. pos = 0;
  4971. while (pos < len) {
  4972. Py_ssize_t newpos, repsize, moreunits;
  4973. if (kind == PyUnicode_2BYTE_KIND) {
  4974. pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
  4975. &out, native_ordering);
  4976. }
  4977. else {
  4978. assert(kind == PyUnicode_4BYTE_KIND);
  4979. pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
  4980. &out, native_ordering);
  4981. }
  4982. if (pos == len)
  4983. break;
  4984. rep = unicode_encode_call_errorhandler(
  4985. errors, &errorHandler,
  4986. encoding, "surrogates not allowed",
  4987. str, &exc, pos, pos + 1, &newpos);
  4988. if (!rep)
  4989. goto error;
  4990. if (PyBytes_Check(rep)) {
  4991. repsize = PyBytes_GET_SIZE(rep);
  4992. if (repsize & 3) {
  4993. raise_encode_exception(&exc, encoding,
  4994. str, pos, pos + 1,
  4995. "surrogates not allowed");
  4996. goto error;
  4997. }
  4998. moreunits = repsize / 4;
  4999. }
  5000. else {
  5001. assert(PyUnicode_Check(rep));
  5002. moreunits = repsize = PyUnicode_GET_LENGTH(rep);
  5003. if (!PyUnicode_IS_ASCII(rep)) {
  5004. raise_encode_exception(&exc, encoding,
  5005. str, pos, pos + 1,
  5006. "surrogates not allowed");
  5007. goto error;
  5008. }
  5009. }
  5010. moreunits += pos - newpos;
  5011. pos = newpos;
  5012. /* four bytes are reserved for each surrogate */
  5013. if (moreunits > 0) {
  5014. Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
  5015. if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
  5016. /* integer overflow */
  5017. PyErr_NoMemory();
  5018. goto error;
  5019. }
  5020. if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * moreunits) < 0)
  5021. goto error;
  5022. out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
  5023. }
  5024. if (PyBytes_Check(rep)) {
  5025. memcpy(out, PyBytes_AS_STRING(rep), repsize);
  5026. out += repsize / 4;
  5027. } else /* rep is unicode */ {
  5028. assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
  5029. ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
  5030. &out, native_ordering);
  5031. }
  5032. Py_CLEAR(rep);
  5033. }
  5034. /* Cut back to size actually needed. This is necessary for, for example,
  5035. encoding of a string containing isolated surrogates and the 'ignore'
  5036. handler is used. */
  5037. nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
  5038. if (nsize != PyBytes_GET_SIZE(v))
  5039. _PyBytes_Resize(&v, nsize);
  5040. Py_XDECREF(errorHandler);
  5041. Py_XDECREF(exc);
  5042. done:
  5043. return v;
  5044. error:
  5045. Py_XDECREF(rep);
  5046. Py_XDECREF(errorHandler);
  5047. Py_XDECREF(exc);
  5048. Py_XDECREF(v);
  5049. return NULL;
  5050. }
  5051. PyObject *
  5052. PyUnicode_AsUTF32String(PyObject *unicode)
  5053. {
  5054. return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
  5055. }
  5056. /* --- UTF-16 Codec ------------------------------------------------------- */
  5057. PyObject *
  5058. PyUnicode_DecodeUTF16(const char *s,
  5059. Py_ssize_t size,
  5060. const char *errors,
  5061. int *byteorder)
  5062. {
  5063. return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
  5064. }
  5065. PyObject *
  5066. PyUnicode_DecodeUTF16Stateful(const char *s,
  5067. Py_ssize_t size,
  5068. const char *errors,
  5069. int *byteorder,
  5070. Py_ssize_t *consumed)
  5071. {
  5072. const char *starts = s;
  5073. Py_ssize_t startinpos;
  5074. Py_ssize_t endinpos;
  5075. _PyUnicodeWriter writer;
  5076. const unsigned char *q, *e;
  5077. int bo = 0; /* assume native ordering by default */
  5078. int native_ordering;
  5079. const char *errmsg = "";
  5080. PyObject *errorHandler = NULL;
  5081. PyObject *exc = NULL;
  5082. const char *encoding;
  5083. q = (const unsigned char *)s;
  5084. e = q + size;
  5085. if (byteorder)
  5086. bo = *byteorder;
  5087. /* Check for BOM marks (U+FEFF) in the input and adjust current
  5088. byte order setting accordingly. In native mode, the leading BOM
  5089. mark is skipped, in all other modes, it is copied to the output
  5090. stream as-is (giving a ZWNBSP character). */
  5091. if (bo == 0 && size >= 2) {
  5092. const Py_UCS4 bom = (q[1] << 8) | q[0];
  5093. if (bom == 0xFEFF) {
  5094. q += 2;
  5095. bo = -1;
  5096. }
  5097. else if (bom == 0xFFFE) {
  5098. q += 2;
  5099. bo = 1;
  5100. }
  5101. if (byteorder)
  5102. *byteorder = bo;
  5103. }
  5104. if (q == e) {
  5105. if (consumed)
  5106. *consumed = size;
  5107. _Py_RETURN_UNICODE_EMPTY();
  5108. }
  5109. #if PY_LITTLE_ENDIAN
  5110. native_ordering = bo <= 0;
  5111. encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
  5112. #else
  5113. native_ordering = bo >= 0;
  5114. encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
  5115. #endif
  5116. /* Note: size will always be longer than the resulting Unicode
  5117. character count normally. Error handler will take care of
  5118. resizing when needed. */
  5119. _PyUnicodeWriter_Init(&writer);
  5120. writer.min_length = (e - q + 1) / 2;
  5121. if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
  5122. goto onError;
  5123. while (1) {
  5124. Py_UCS4 ch = 0;
  5125. if (e - q >= 2) {
  5126. int kind = writer.kind;
  5127. if (kind == PyUnicode_1BYTE_KIND) {
  5128. if (PyUnicode_IS_ASCII(writer.buffer))
  5129. ch = asciilib_utf16_decode(&q, e,
  5130. (Py_UCS1*)writer.data, &writer.pos,
  5131. native_ordering);
  5132. else
  5133. ch = ucs1lib_utf16_decode(&q, e,
  5134. (Py_UCS1*)writer.data, &writer.pos,
  5135. native_ordering);
  5136. } else if (kind == PyUnicode_2BYTE_KIND) {
  5137. ch = ucs2lib_utf16_decode(&q, e,
  5138. (Py_UCS2*)writer.data, &writer.pos,
  5139. native_ordering);
  5140. } else {
  5141. assert(kind == PyUnicode_4BYTE_KIND);
  5142. ch = ucs4lib_utf16_decode(&q, e,
  5143. (Py_UCS4*)writer.data, &writer.pos,
  5144. native_ordering);
  5145. }
  5146. }
  5147. switch (ch)
  5148. {
  5149. case 0:
  5150. /* remaining byte at the end? (size should be even) */
  5151. if (q == e || consumed)
  5152. goto End;
  5153. errmsg = "truncated data";
  5154. startinpos = ((const char *)q) - starts;
  5155. endinpos = ((const char *)e) - starts;
  5156. break;
  5157. /* The remaining input chars are ignored if the callback
  5158. chooses to skip the input */
  5159. case 1:
  5160. q -= 2;
  5161. if (consumed)
  5162. goto End;
  5163. errmsg = "unexpected end of data";
  5164. startinpos = ((const char *)q) - starts;
  5165. endinpos = ((const char *)e) - starts;
  5166. break;
  5167. case 2:
  5168. errmsg = "illegal encoding";
  5169. startinpos = ((const char *)q) - 2 - starts;
  5170. endinpos = startinpos + 2;
  5171. break;
  5172. case 3:
  5173. errmsg = "illegal UTF-16 surrogate";
  5174. startinpos = ((const char *)q) - 4 - starts;
  5175. endinpos = startinpos + 2;
  5176. break;
  5177. default:
  5178. if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
  5179. goto onError;
  5180. continue;
  5181. }
  5182. if (unicode_decode_call_errorhandler_writer(
  5183. errors,
  5184. &errorHandler,
  5185. encoding, errmsg,
  5186. &starts,
  5187. (const char **)&e,
  5188. &startinpos,
  5189. &endinpos,
  5190. &exc,
  5191. (const char **)&q,
  5192. &writer))
  5193. goto onError;
  5194. }
  5195. End:
  5196. if (consumed)
  5197. *consumed = (const char *)q-starts;
  5198. Py_XDECREF(errorHandler);
  5199. Py_XDECREF(exc);
  5200. return _PyUnicodeWriter_Finish(&writer);
  5201. onError:
  5202. _PyUnicodeWriter_Dealloc(&writer);
  5203. Py_XDECREF(errorHandler);
  5204. Py_XDECREF(exc);
  5205. return NULL;
  5206. }
  5207. PyObject *
  5208. _PyUnicode_EncodeUTF16(PyObject *str,
  5209. const char *errors,
  5210. int byteorder)
  5211. {
  5212. int kind;
  5213. const void *data;
  5214. Py_ssize_t len;
  5215. PyObject *v;
  5216. unsigned short *out;
  5217. Py_ssize_t pairs;
  5218. #if PY_BIG_ENDIAN
  5219. int native_ordering = byteorder >= 0;
  5220. #else
  5221. int native_ordering = byteorder <= 0;
  5222. #endif
  5223. const char *encoding;
  5224. Py_ssize_t nsize, pos;
  5225. PyObject *errorHandler = NULL;
  5226. PyObject *exc = NULL;
  5227. PyObject *rep = NULL;
  5228. if (!PyUnicode_Check(str)) {
  5229. PyErr_BadArgument();
  5230. return NULL;
  5231. }
  5232. kind = PyUnicode_KIND(str);
  5233. data = PyUnicode_DATA(str);
  5234. len = PyUnicode_GET_LENGTH(str);
  5235. pairs = 0;
  5236. if (kind == PyUnicode_4BYTE_KIND) {
  5237. const Py_UCS4 *in = (const Py_UCS4 *)data;
  5238. const Py_UCS4 *end = in + len;
  5239. while (in < end) {
  5240. if (*in++ >= 0x10000) {
  5241. pairs++;
  5242. }
  5243. }
  5244. }
  5245. if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
  5246. return PyErr_NoMemory();
  5247. }
  5248. nsize = len + pairs + (byteorder == 0);
  5249. v = PyBytes_FromStringAndSize(NULL, nsize * 2);
  5250. if (v == NULL) {
  5251. return NULL;
  5252. }
  5253. /* output buffer is 2-bytes aligned */
  5254. assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
  5255. out = (unsigned short *)PyBytes_AS_STRING(v);
  5256. if (byteorder == 0) {
  5257. *out++ = 0xFEFF;
  5258. }
  5259. if (len == 0) {
  5260. goto done;
  5261. }
  5262. if (kind == PyUnicode_1BYTE_KIND) {
  5263. ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
  5264. goto done;
  5265. }
  5266. if (byteorder < 0) {
  5267. encoding = "utf-16-le";
  5268. }
  5269. else if (byteorder > 0) {
  5270. encoding = "utf-16-be";
  5271. }
  5272. else {
  5273. encoding = "utf-16";
  5274. }
  5275. pos = 0;
  5276. while (pos < len) {
  5277. Py_ssize_t newpos, repsize, moreunits;
  5278. if (kind == PyUnicode_2BYTE_KIND) {
  5279. pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
  5280. &out, native_ordering);
  5281. }
  5282. else {
  5283. assert(kind == PyUnicode_4BYTE_KIND);
  5284. pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
  5285. &out, native_ordering);
  5286. }
  5287. if (pos == len)
  5288. break;
  5289. rep = unicode_encode_call_errorhandler(
  5290. errors, &errorHandler,
  5291. encoding, "surrogates not allowed",
  5292. str, &exc, pos, pos + 1, &newpos);
  5293. if (!rep)
  5294. goto error;
  5295. if (PyBytes_Check(rep)) {
  5296. repsize = PyBytes_GET_SIZE(rep);
  5297. if (repsize & 1) {
  5298. raise_encode_exception(&exc, encoding,
  5299. str, pos, pos + 1,
  5300. "surrogates not allowed");
  5301. goto error;
  5302. }
  5303. moreunits = repsize / 2;
  5304. }
  5305. else {
  5306. assert(PyUnicode_Check(rep));
  5307. moreunits = repsize = PyUnicode_GET_LENGTH(rep);
  5308. if (!PyUnicode_IS_ASCII(rep)) {
  5309. raise_encode_exception(&exc, encoding,
  5310. str, pos, pos + 1,
  5311. "surrogates not allowed");
  5312. goto error;
  5313. }
  5314. }
  5315. moreunits += pos - newpos;
  5316. pos = newpos;
  5317. /* two bytes are reserved for each surrogate */
  5318. if (moreunits > 0) {
  5319. Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
  5320. if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
  5321. /* integer overflow */
  5322. PyErr_NoMemory();
  5323. goto error;
  5324. }
  5325. if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * moreunits) < 0)
  5326. goto error;
  5327. out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
  5328. }
  5329. if (PyBytes_Check(rep)) {
  5330. memcpy(out, PyBytes_AS_STRING(rep), repsize);
  5331. out += repsize / 2;
  5332. } else /* rep is unicode */ {
  5333. assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
  5334. ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
  5335. &out, native_ordering);
  5336. }
  5337. Py_CLEAR(rep);
  5338. }
  5339. /* Cut back to size actually needed. This is necessary for, for example,
  5340. encoding of a string containing isolated surrogates and the 'ignore' handler
  5341. is used. */
  5342. nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
  5343. if (nsize != PyBytes_GET_SIZE(v))
  5344. _PyBytes_Resize(&v, nsize);
  5345. Py_XDECREF(errorHandler);
  5346. Py_XDECREF(exc);
  5347. done:
  5348. return v;
  5349. error:
  5350. Py_XDECREF(rep);
  5351. Py_XDECREF(errorHandler);
  5352. Py_XDECREF(exc);
  5353. Py_XDECREF(v);
  5354. return NULL;
  5355. #undef STORECHAR
  5356. }
  5357. PyObject *
  5358. PyUnicode_AsUTF16String(PyObject *unicode)
  5359. {
  5360. return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
  5361. }
  5362. /* --- Unicode Escape Codec ----------------------------------------------- */
  5363. PyObject *
  5364. _PyUnicode_DecodeUnicodeEscapeInternal(const char *s,
  5365. Py_ssize_t size,
  5366. const char *errors,
  5367. Py_ssize_t *consumed,
  5368. const char **first_invalid_escape)
  5369. {
  5370. const char *starts = s;
  5371. _PyUnicodeWriter writer;
  5372. const char *end;
  5373. PyObject *errorHandler = NULL;
  5374. PyObject *exc = NULL;
  5375. _PyUnicode_Name_CAPI *ucnhash_capi;
  5376. PyInterpreterState *interp = _PyInterpreterState_Get();
  5377. // so we can remember if we've seen an invalid escape char or not
  5378. *first_invalid_escape = NULL;
  5379. if (size == 0) {
  5380. if (consumed) {
  5381. *consumed = 0;
  5382. }
  5383. _Py_RETURN_UNICODE_EMPTY();
  5384. }
  5385. /* Escaped strings will always be longer than the resulting
  5386. Unicode string, so we start with size here and then reduce the
  5387. length after conversion to the true value.
  5388. (but if the error callback returns a long replacement string
  5389. we'll have to allocate more space) */
  5390. _PyUnicodeWriter_Init(&writer);
  5391. writer.min_length = size;
  5392. if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
  5393. goto onError;
  5394. }
  5395. end = s + size;
  5396. while (s < end) {
  5397. unsigned char c = (unsigned char) *s++;
  5398. Py_UCS4 ch;
  5399. int count;
  5400. const char *message;
  5401. #define WRITE_ASCII_CHAR(ch) \
  5402. do { \
  5403. assert(ch <= 127); \
  5404. assert(writer.pos < writer.size); \
  5405. PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
  5406. } while(0)
  5407. #define WRITE_CHAR(ch) \
  5408. do { \
  5409. if (ch <= writer.maxchar) { \
  5410. assert(writer.pos < writer.size); \
  5411. PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
  5412. } \
  5413. else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
  5414. goto onError; \
  5415. } \
  5416. } while(0)
  5417. /* Non-escape characters are interpreted as Unicode ordinals */
  5418. if (c != '\\') {
  5419. WRITE_CHAR(c);
  5420. continue;
  5421. }
  5422. Py_ssize_t startinpos = s - starts - 1;
  5423. /* \ - Escapes */
  5424. if (s >= end) {
  5425. message = "\\ at end of string";
  5426. goto incomplete;
  5427. }
  5428. c = (unsigned char) *s++;
  5429. assert(writer.pos < writer.size);
  5430. switch (c) {
  5431. /* \x escapes */
  5432. case '\n': continue;
  5433. case '\\': WRITE_ASCII_CHAR('\\'); continue;
  5434. case '\'': WRITE_ASCII_CHAR('\''); continue;
  5435. case '\"': WRITE_ASCII_CHAR('\"'); continue;
  5436. case 'b': WRITE_ASCII_CHAR('\b'); continue;
  5437. /* FF */
  5438. case 'f': WRITE_ASCII_CHAR('\014'); continue;
  5439. case 't': WRITE_ASCII_CHAR('\t'); continue;
  5440. case 'n': WRITE_ASCII_CHAR('\n'); continue;
  5441. case 'r': WRITE_ASCII_CHAR('\r'); continue;
  5442. /* VT */
  5443. case 'v': WRITE_ASCII_CHAR('\013'); continue;
  5444. /* BEL, not classic C */
  5445. case 'a': WRITE_ASCII_CHAR('\007'); continue;
  5446. /* \OOO (octal) escapes */
  5447. case '0': case '1': case '2': case '3':
  5448. case '4': case '5': case '6': case '7':
  5449. ch = c - '0';
  5450. if (s < end && '0' <= *s && *s <= '7') {
  5451. ch = (ch<<3) + *s++ - '0';
  5452. if (s < end && '0' <= *s && *s <= '7') {
  5453. ch = (ch<<3) + *s++ - '0';
  5454. }
  5455. }
  5456. if (ch > 0377) {
  5457. if (*first_invalid_escape == NULL) {
  5458. *first_invalid_escape = s-3; /* Back up 3 chars, since we've
  5459. already incremented s. */
  5460. }
  5461. }
  5462. WRITE_CHAR(ch);
  5463. continue;
  5464. /* hex escapes */
  5465. /* \xXX */
  5466. case 'x':
  5467. count = 2;
  5468. message = "truncated \\xXX escape";
  5469. goto hexescape;
  5470. /* \uXXXX */
  5471. case 'u':
  5472. count = 4;
  5473. message = "truncated \\uXXXX escape";
  5474. goto hexescape;
  5475. /* \UXXXXXXXX */
  5476. case 'U':
  5477. count = 8;
  5478. message = "truncated \\UXXXXXXXX escape";
  5479. hexescape:
  5480. for (ch = 0; count; ++s, --count) {
  5481. if (s >= end) {
  5482. goto incomplete;
  5483. }
  5484. c = (unsigned char)*s;
  5485. ch <<= 4;
  5486. if (c >= '0' && c <= '9') {
  5487. ch += c - '0';
  5488. }
  5489. else if (c >= 'a' && c <= 'f') {
  5490. ch += c - ('a' - 10);
  5491. }
  5492. else if (c >= 'A' && c <= 'F') {
  5493. ch += c - ('A' - 10);
  5494. }
  5495. else {
  5496. goto error;
  5497. }
  5498. }
  5499. /* when we get here, ch is a 32-bit unicode character */
  5500. if (ch > MAX_UNICODE) {
  5501. message = "illegal Unicode character";
  5502. goto error;
  5503. }
  5504. WRITE_CHAR(ch);
  5505. continue;
  5506. /* \N{name} */
  5507. case 'N':
  5508. ucnhash_capi = interp->unicode.ucnhash_capi;
  5509. if (ucnhash_capi == NULL) {
  5510. /* load the unicode data module */
  5511. ucnhash_capi = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
  5512. PyUnicodeData_CAPSULE_NAME, 1);
  5513. if (ucnhash_capi == NULL) {
  5514. PyErr_SetString(
  5515. PyExc_UnicodeError,
  5516. "\\N escapes not supported (can't load unicodedata module)"
  5517. );
  5518. goto onError;
  5519. }
  5520. interp->unicode.ucnhash_capi = ucnhash_capi;
  5521. }
  5522. message = "malformed \\N character escape";
  5523. if (s >= end) {
  5524. goto incomplete;
  5525. }
  5526. if (*s == '{') {
  5527. const char *start = ++s;
  5528. size_t namelen;
  5529. /* look for the closing brace */
  5530. while (s < end && *s != '}')
  5531. s++;
  5532. if (s >= end) {
  5533. goto incomplete;
  5534. }
  5535. namelen = s - start;
  5536. if (namelen) {
  5537. /* found a name. look it up in the unicode database */
  5538. s++;
  5539. ch = 0xffffffff; /* in case 'getcode' messes up */
  5540. if (namelen <= INT_MAX &&
  5541. ucnhash_capi->getcode(start, (int)namelen,
  5542. &ch, 0)) {
  5543. assert(ch <= MAX_UNICODE);
  5544. WRITE_CHAR(ch);
  5545. continue;
  5546. }
  5547. message = "unknown Unicode character name";
  5548. }
  5549. }
  5550. goto error;
  5551. default:
  5552. if (*first_invalid_escape == NULL) {
  5553. *first_invalid_escape = s-1; /* Back up one char, since we've
  5554. already incremented s. */
  5555. }
  5556. WRITE_ASCII_CHAR('\\');
  5557. WRITE_CHAR(c);
  5558. continue;
  5559. }
  5560. incomplete:
  5561. if (consumed) {
  5562. *consumed = startinpos;
  5563. break;
  5564. }
  5565. error:;
  5566. Py_ssize_t endinpos = s-starts;
  5567. writer.min_length = end - s + writer.pos;
  5568. if (unicode_decode_call_errorhandler_writer(
  5569. errors, &errorHandler,
  5570. "unicodeescape", message,
  5571. &starts, &end, &startinpos, &endinpos, &exc, &s,
  5572. &writer)) {
  5573. goto onError;
  5574. }
  5575. assert(end - s <= writer.size - writer.pos);
  5576. #undef WRITE_ASCII_CHAR
  5577. #undef WRITE_CHAR
  5578. }
  5579. Py_XDECREF(errorHandler);
  5580. Py_XDECREF(exc);
  5581. return _PyUnicodeWriter_Finish(&writer);
  5582. onError:
  5583. _PyUnicodeWriter_Dealloc(&writer);
  5584. Py_XDECREF(errorHandler);
  5585. Py_XDECREF(exc);
  5586. return NULL;
  5587. }
  5588. PyObject *
  5589. _PyUnicode_DecodeUnicodeEscapeStateful(const char *s,
  5590. Py_ssize_t size,
  5591. const char *errors,
  5592. Py_ssize_t *consumed)
  5593. {
  5594. const char *first_invalid_escape;
  5595. PyObject *result = _PyUnicode_DecodeUnicodeEscapeInternal(s, size, errors,
  5596. consumed,
  5597. &first_invalid_escape);
  5598. if (result == NULL)
  5599. return NULL;
  5600. if (first_invalid_escape != NULL) {
  5601. unsigned char c = *first_invalid_escape;
  5602. if ('4' <= c && c <= '7') {
  5603. if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
  5604. "invalid octal escape sequence '\\%.3s'",
  5605. first_invalid_escape) < 0)
  5606. {
  5607. Py_DECREF(result);
  5608. return NULL;
  5609. }
  5610. }
  5611. else {
  5612. if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
  5613. "invalid escape sequence '\\%c'",
  5614. c) < 0)
  5615. {
  5616. Py_DECREF(result);
  5617. return NULL;
  5618. }
  5619. }
  5620. }
  5621. return result;
  5622. }
  5623. PyObject *
  5624. PyUnicode_DecodeUnicodeEscape(const char *s,
  5625. Py_ssize_t size,
  5626. const char *errors)
  5627. {
  5628. return _PyUnicode_DecodeUnicodeEscapeStateful(s, size, errors, NULL);
  5629. }
  5630. /* Return a Unicode-Escape string version of the Unicode object. */
  5631. PyObject *
  5632. PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
  5633. {
  5634. Py_ssize_t i, len;
  5635. PyObject *repr;
  5636. char *p;
  5637. int kind;
  5638. const void *data;
  5639. Py_ssize_t expandsize;
  5640. /* Initial allocation is based on the longest-possible character
  5641. escape.
  5642. For UCS1 strings it's '\xxx', 4 bytes per source character.
  5643. For UCS2 strings it's '\uxxxx', 6 bytes per source character.
  5644. For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
  5645. */
  5646. if (!PyUnicode_Check(unicode)) {
  5647. PyErr_BadArgument();
  5648. return NULL;
  5649. }
  5650. len = PyUnicode_GET_LENGTH(unicode);
  5651. if (len == 0) {
  5652. return PyBytes_FromStringAndSize(NULL, 0);
  5653. }
  5654. kind = PyUnicode_KIND(unicode);
  5655. data = PyUnicode_DATA(unicode);
  5656. /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
  5657. bytes, and 1 byte characters 4. */
  5658. expandsize = kind * 2 + 2;
  5659. if (len > PY_SSIZE_T_MAX / expandsize) {
  5660. return PyErr_NoMemory();
  5661. }
  5662. repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
  5663. if (repr == NULL) {
  5664. return NULL;
  5665. }
  5666. p = PyBytes_AS_STRING(repr);
  5667. for (i = 0; i < len; i++) {
  5668. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  5669. /* U+0000-U+00ff range */
  5670. if (ch < 0x100) {
  5671. if (ch >= ' ' && ch < 127) {
  5672. if (ch != '\\') {
  5673. /* Copy printable US ASCII as-is */
  5674. *p++ = (char) ch;
  5675. }
  5676. /* Escape backslashes */
  5677. else {
  5678. *p++ = '\\';
  5679. *p++ = '\\';
  5680. }
  5681. }
  5682. /* Map special whitespace to '\t', \n', '\r' */
  5683. else if (ch == '\t') {
  5684. *p++ = '\\';
  5685. *p++ = 't';
  5686. }
  5687. else if (ch == '\n') {
  5688. *p++ = '\\';
  5689. *p++ = 'n';
  5690. }
  5691. else if (ch == '\r') {
  5692. *p++ = '\\';
  5693. *p++ = 'r';
  5694. }
  5695. /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
  5696. else {
  5697. *p++ = '\\';
  5698. *p++ = 'x';
  5699. *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
  5700. *p++ = Py_hexdigits[ch & 0x000F];
  5701. }
  5702. }
  5703. /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
  5704. else if (ch < 0x10000) {
  5705. *p++ = '\\';
  5706. *p++ = 'u';
  5707. *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
  5708. *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
  5709. *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
  5710. *p++ = Py_hexdigits[ch & 0x000F];
  5711. }
  5712. /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
  5713. else {
  5714. /* Make sure that the first two digits are zero */
  5715. assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
  5716. *p++ = '\\';
  5717. *p++ = 'U';
  5718. *p++ = '0';
  5719. *p++ = '0';
  5720. *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
  5721. *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
  5722. *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
  5723. *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
  5724. *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
  5725. *p++ = Py_hexdigits[ch & 0x0000000F];
  5726. }
  5727. }
  5728. assert(p - PyBytes_AS_STRING(repr) > 0);
  5729. if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
  5730. return NULL;
  5731. }
  5732. return repr;
  5733. }
  5734. /* --- Raw Unicode Escape Codec ------------------------------------------- */
  5735. PyObject *
  5736. _PyUnicode_DecodeRawUnicodeEscapeStateful(const char *s,
  5737. Py_ssize_t size,
  5738. const char *errors,
  5739. Py_ssize_t *consumed)
  5740. {
  5741. const char *starts = s;
  5742. _PyUnicodeWriter writer;
  5743. const char *end;
  5744. PyObject *errorHandler = NULL;
  5745. PyObject *exc = NULL;
  5746. if (size == 0) {
  5747. if (consumed) {
  5748. *consumed = 0;
  5749. }
  5750. _Py_RETURN_UNICODE_EMPTY();
  5751. }
  5752. /* Escaped strings will always be longer than the resulting
  5753. Unicode string, so we start with size here and then reduce the
  5754. length after conversion to the true value. (But decoding error
  5755. handler might have to resize the string) */
  5756. _PyUnicodeWriter_Init(&writer);
  5757. writer.min_length = size;
  5758. if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
  5759. goto onError;
  5760. }
  5761. end = s + size;
  5762. while (s < end) {
  5763. unsigned char c = (unsigned char) *s++;
  5764. Py_UCS4 ch;
  5765. int count;
  5766. const char *message;
  5767. #define WRITE_CHAR(ch) \
  5768. do { \
  5769. if (ch <= writer.maxchar) { \
  5770. assert(writer.pos < writer.size); \
  5771. PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
  5772. } \
  5773. else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
  5774. goto onError; \
  5775. } \
  5776. } while(0)
  5777. /* Non-escape characters are interpreted as Unicode ordinals */
  5778. if (c != '\\' || (s >= end && !consumed)) {
  5779. WRITE_CHAR(c);
  5780. continue;
  5781. }
  5782. Py_ssize_t startinpos = s - starts - 1;
  5783. /* \ - Escapes */
  5784. if (s >= end) {
  5785. assert(consumed);
  5786. // Set message to silent compiler warning.
  5787. // Actually it is never used.
  5788. message = "\\ at end of string";
  5789. goto incomplete;
  5790. }
  5791. c = (unsigned char) *s++;
  5792. if (c == 'u') {
  5793. count = 4;
  5794. message = "truncated \\uXXXX escape";
  5795. }
  5796. else if (c == 'U') {
  5797. count = 8;
  5798. message = "truncated \\UXXXXXXXX escape";
  5799. }
  5800. else {
  5801. assert(writer.pos < writer.size);
  5802. PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
  5803. WRITE_CHAR(c);
  5804. continue;
  5805. }
  5806. /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
  5807. for (ch = 0; count; ++s, --count) {
  5808. if (s >= end) {
  5809. goto incomplete;
  5810. }
  5811. c = (unsigned char)*s;
  5812. ch <<= 4;
  5813. if (c >= '0' && c <= '9') {
  5814. ch += c - '0';
  5815. }
  5816. else if (c >= 'a' && c <= 'f') {
  5817. ch += c - ('a' - 10);
  5818. }
  5819. else if (c >= 'A' && c <= 'F') {
  5820. ch += c - ('A' - 10);
  5821. }
  5822. else {
  5823. goto error;
  5824. }
  5825. }
  5826. if (ch > MAX_UNICODE) {
  5827. message = "\\Uxxxxxxxx out of range";
  5828. goto error;
  5829. }
  5830. WRITE_CHAR(ch);
  5831. continue;
  5832. incomplete:
  5833. if (consumed) {
  5834. *consumed = startinpos;
  5835. break;
  5836. }
  5837. error:;
  5838. Py_ssize_t endinpos = s-starts;
  5839. writer.min_length = end - s + writer.pos;
  5840. if (unicode_decode_call_errorhandler_writer(
  5841. errors, &errorHandler,
  5842. "rawunicodeescape", message,
  5843. &starts, &end, &startinpos, &endinpos, &exc, &s,
  5844. &writer)) {
  5845. goto onError;
  5846. }
  5847. assert(end - s <= writer.size - writer.pos);
  5848. #undef WRITE_CHAR
  5849. }
  5850. Py_XDECREF(errorHandler);
  5851. Py_XDECREF(exc);
  5852. return _PyUnicodeWriter_Finish(&writer);
  5853. onError:
  5854. _PyUnicodeWriter_Dealloc(&writer);
  5855. Py_XDECREF(errorHandler);
  5856. Py_XDECREF(exc);
  5857. return NULL;
  5858. }
  5859. PyObject *
  5860. PyUnicode_DecodeRawUnicodeEscape(const char *s,
  5861. Py_ssize_t size,
  5862. const char *errors)
  5863. {
  5864. return _PyUnicode_DecodeRawUnicodeEscapeStateful(s, size, errors, NULL);
  5865. }
  5866. PyObject *
  5867. PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
  5868. {
  5869. PyObject *repr;
  5870. char *p;
  5871. Py_ssize_t expandsize, pos;
  5872. int kind;
  5873. const void *data;
  5874. Py_ssize_t len;
  5875. if (!PyUnicode_Check(unicode)) {
  5876. PyErr_BadArgument();
  5877. return NULL;
  5878. }
  5879. kind = PyUnicode_KIND(unicode);
  5880. data = PyUnicode_DATA(unicode);
  5881. len = PyUnicode_GET_LENGTH(unicode);
  5882. if (kind == PyUnicode_1BYTE_KIND) {
  5883. return PyBytes_FromStringAndSize(data, len);
  5884. }
  5885. /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
  5886. bytes, and 1 byte characters 4. */
  5887. expandsize = kind * 2 + 2;
  5888. if (len > PY_SSIZE_T_MAX / expandsize) {
  5889. return PyErr_NoMemory();
  5890. }
  5891. repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
  5892. if (repr == NULL) {
  5893. return NULL;
  5894. }
  5895. if (len == 0) {
  5896. return repr;
  5897. }
  5898. p = PyBytes_AS_STRING(repr);
  5899. for (pos = 0; pos < len; pos++) {
  5900. Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
  5901. /* U+0000-U+00ff range: Copy 8-bit characters as-is */
  5902. if (ch < 0x100) {
  5903. *p++ = (char) ch;
  5904. }
  5905. /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
  5906. else if (ch < 0x10000) {
  5907. *p++ = '\\';
  5908. *p++ = 'u';
  5909. *p++ = Py_hexdigits[(ch >> 12) & 0xf];
  5910. *p++ = Py_hexdigits[(ch >> 8) & 0xf];
  5911. *p++ = Py_hexdigits[(ch >> 4) & 0xf];
  5912. *p++ = Py_hexdigits[ch & 15];
  5913. }
  5914. /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
  5915. else {
  5916. assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
  5917. *p++ = '\\';
  5918. *p++ = 'U';
  5919. *p++ = '0';
  5920. *p++ = '0';
  5921. *p++ = Py_hexdigits[(ch >> 20) & 0xf];
  5922. *p++ = Py_hexdigits[(ch >> 16) & 0xf];
  5923. *p++ = Py_hexdigits[(ch >> 12) & 0xf];
  5924. *p++ = Py_hexdigits[(ch >> 8) & 0xf];
  5925. *p++ = Py_hexdigits[(ch >> 4) & 0xf];
  5926. *p++ = Py_hexdigits[ch & 15];
  5927. }
  5928. }
  5929. assert(p > PyBytes_AS_STRING(repr));
  5930. if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
  5931. return NULL;
  5932. }
  5933. return repr;
  5934. }
  5935. /* --- Latin-1 Codec ------------------------------------------------------ */
  5936. PyObject *
  5937. PyUnicode_DecodeLatin1(const char *s,
  5938. Py_ssize_t size,
  5939. const char *errors)
  5940. {
  5941. /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
  5942. return _PyUnicode_FromUCS1((const unsigned char*)s, size);
  5943. }
  5944. /* create or adjust a UnicodeEncodeError */
  5945. static void
  5946. make_encode_exception(PyObject **exceptionObject,
  5947. const char *encoding,
  5948. PyObject *unicode,
  5949. Py_ssize_t startpos, Py_ssize_t endpos,
  5950. const char *reason)
  5951. {
  5952. if (*exceptionObject == NULL) {
  5953. *exceptionObject = PyObject_CallFunction(
  5954. PyExc_UnicodeEncodeError, "sOnns",
  5955. encoding, unicode, startpos, endpos, reason);
  5956. }
  5957. else {
  5958. if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
  5959. goto onError;
  5960. if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
  5961. goto onError;
  5962. if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
  5963. goto onError;
  5964. return;
  5965. onError:
  5966. Py_CLEAR(*exceptionObject);
  5967. }
  5968. }
  5969. /* raises a UnicodeEncodeError */
  5970. static void
  5971. raise_encode_exception(PyObject **exceptionObject,
  5972. const char *encoding,
  5973. PyObject *unicode,
  5974. Py_ssize_t startpos, Py_ssize_t endpos,
  5975. const char *reason)
  5976. {
  5977. make_encode_exception(exceptionObject,
  5978. encoding, unicode, startpos, endpos, reason);
  5979. if (*exceptionObject != NULL)
  5980. PyCodec_StrictErrors(*exceptionObject);
  5981. }
  5982. /* error handling callback helper:
  5983. build arguments, call the callback and check the arguments,
  5984. put the result into newpos and return the replacement string, which
  5985. has to be freed by the caller */
  5986. static PyObject *
  5987. unicode_encode_call_errorhandler(const char *errors,
  5988. PyObject **errorHandler,
  5989. const char *encoding, const char *reason,
  5990. PyObject *unicode, PyObject **exceptionObject,
  5991. Py_ssize_t startpos, Py_ssize_t endpos,
  5992. Py_ssize_t *newpos)
  5993. {
  5994. static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
  5995. Py_ssize_t len;
  5996. PyObject *restuple;
  5997. PyObject *resunicode;
  5998. if (*errorHandler == NULL) {
  5999. *errorHandler = PyCodec_LookupError(errors);
  6000. if (*errorHandler == NULL)
  6001. return NULL;
  6002. }
  6003. len = PyUnicode_GET_LENGTH(unicode);
  6004. make_encode_exception(exceptionObject,
  6005. encoding, unicode, startpos, endpos, reason);
  6006. if (*exceptionObject == NULL)
  6007. return NULL;
  6008. restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
  6009. if (restuple == NULL)
  6010. return NULL;
  6011. if (!PyTuple_Check(restuple)) {
  6012. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  6013. Py_DECREF(restuple);
  6014. return NULL;
  6015. }
  6016. if (!PyArg_ParseTuple(restuple, argparse,
  6017. &resunicode, newpos)) {
  6018. Py_DECREF(restuple);
  6019. return NULL;
  6020. }
  6021. if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
  6022. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  6023. Py_DECREF(restuple);
  6024. return NULL;
  6025. }
  6026. if (*newpos<0)
  6027. *newpos = len + *newpos;
  6028. if (*newpos<0 || *newpos>len) {
  6029. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
  6030. Py_DECREF(restuple);
  6031. return NULL;
  6032. }
  6033. Py_INCREF(resunicode);
  6034. Py_DECREF(restuple);
  6035. return resunicode;
  6036. }
  6037. static PyObject *
  6038. unicode_encode_ucs1(PyObject *unicode,
  6039. const char *errors,
  6040. const Py_UCS4 limit)
  6041. {
  6042. /* input state */
  6043. Py_ssize_t pos=0, size;
  6044. int kind;
  6045. const void *data;
  6046. /* pointer into the output */
  6047. char *str;
  6048. const char *encoding = (limit == 256) ? "latin-1" : "ascii";
  6049. const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
  6050. PyObject *error_handler_obj = NULL;
  6051. PyObject *exc = NULL;
  6052. _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
  6053. PyObject *rep = NULL;
  6054. /* output object */
  6055. _PyBytesWriter writer;
  6056. size = PyUnicode_GET_LENGTH(unicode);
  6057. kind = PyUnicode_KIND(unicode);
  6058. data = PyUnicode_DATA(unicode);
  6059. /* allocate enough for a simple encoding without
  6060. replacements, if we need more, we'll resize */
  6061. if (size == 0)
  6062. return PyBytes_FromStringAndSize(NULL, 0);
  6063. _PyBytesWriter_Init(&writer);
  6064. str = _PyBytesWriter_Alloc(&writer, size);
  6065. if (str == NULL)
  6066. return NULL;
  6067. while (pos < size) {
  6068. Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
  6069. /* can we encode this? */
  6070. if (ch < limit) {
  6071. /* no overflow check, because we know that the space is enough */
  6072. *str++ = (char)ch;
  6073. ++pos;
  6074. }
  6075. else {
  6076. Py_ssize_t newpos, i;
  6077. /* startpos for collecting unencodable chars */
  6078. Py_ssize_t collstart = pos;
  6079. Py_ssize_t collend = collstart + 1;
  6080. /* find all unecodable characters */
  6081. while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
  6082. ++collend;
  6083. /* Only overallocate the buffer if it's not the last write */
  6084. writer.overallocate = (collend < size);
  6085. /* cache callback name lookup (if not done yet, i.e. it's the first error) */
  6086. if (error_handler == _Py_ERROR_UNKNOWN)
  6087. error_handler = _Py_GetErrorHandler(errors);
  6088. switch (error_handler) {
  6089. case _Py_ERROR_STRICT:
  6090. raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
  6091. goto onError;
  6092. case _Py_ERROR_REPLACE:
  6093. memset(str, '?', collend - collstart);
  6094. str += (collend - collstart);
  6095. /* fall through */
  6096. case _Py_ERROR_IGNORE:
  6097. pos = collend;
  6098. break;
  6099. case _Py_ERROR_BACKSLASHREPLACE:
  6100. /* subtract preallocated bytes */
  6101. writer.min_size -= (collend - collstart);
  6102. str = backslashreplace(&writer, str,
  6103. unicode, collstart, collend);
  6104. if (str == NULL)
  6105. goto onError;
  6106. pos = collend;
  6107. break;
  6108. case _Py_ERROR_XMLCHARREFREPLACE:
  6109. /* subtract preallocated bytes */
  6110. writer.min_size -= (collend - collstart);
  6111. str = xmlcharrefreplace(&writer, str,
  6112. unicode, collstart, collend);
  6113. if (str == NULL)
  6114. goto onError;
  6115. pos = collend;
  6116. break;
  6117. case _Py_ERROR_SURROGATEESCAPE:
  6118. for (i = collstart; i < collend; ++i) {
  6119. ch = PyUnicode_READ(kind, data, i);
  6120. if (ch < 0xdc80 || 0xdcff < ch) {
  6121. /* Not a UTF-8b surrogate */
  6122. break;
  6123. }
  6124. *str++ = (char)(ch - 0xdc00);
  6125. ++pos;
  6126. }
  6127. if (i >= collend)
  6128. break;
  6129. collstart = pos;
  6130. assert(collstart != collend);
  6131. /* fall through */
  6132. default:
  6133. rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
  6134. encoding, reason, unicode, &exc,
  6135. collstart, collend, &newpos);
  6136. if (rep == NULL)
  6137. goto onError;
  6138. if (newpos < collstart) {
  6139. writer.overallocate = 1;
  6140. str = _PyBytesWriter_Prepare(&writer, str,
  6141. collstart - newpos);
  6142. if (str == NULL)
  6143. goto onError;
  6144. }
  6145. else {
  6146. /* subtract preallocated bytes */
  6147. writer.min_size -= newpos - collstart;
  6148. /* Only overallocate the buffer if it's not the last write */
  6149. writer.overallocate = (newpos < size);
  6150. }
  6151. if (PyBytes_Check(rep)) {
  6152. /* Directly copy bytes result to output. */
  6153. str = _PyBytesWriter_WriteBytes(&writer, str,
  6154. PyBytes_AS_STRING(rep),
  6155. PyBytes_GET_SIZE(rep));
  6156. }
  6157. else {
  6158. assert(PyUnicode_Check(rep));
  6159. if (limit == 256 ?
  6160. PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
  6161. !PyUnicode_IS_ASCII(rep))
  6162. {
  6163. /* Not all characters are smaller than limit */
  6164. raise_encode_exception(&exc, encoding, unicode,
  6165. collstart, collend, reason);
  6166. goto onError;
  6167. }
  6168. assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
  6169. str = _PyBytesWriter_WriteBytes(&writer, str,
  6170. PyUnicode_DATA(rep),
  6171. PyUnicode_GET_LENGTH(rep));
  6172. }
  6173. if (str == NULL)
  6174. goto onError;
  6175. pos = newpos;
  6176. Py_CLEAR(rep);
  6177. }
  6178. /* If overallocation was disabled, ensure that it was the last
  6179. write. Otherwise, we missed an optimization */
  6180. assert(writer.overallocate || pos == size);
  6181. }
  6182. }
  6183. Py_XDECREF(error_handler_obj);
  6184. Py_XDECREF(exc);
  6185. return _PyBytesWriter_Finish(&writer, str);
  6186. onError:
  6187. Py_XDECREF(rep);
  6188. _PyBytesWriter_Dealloc(&writer);
  6189. Py_XDECREF(error_handler_obj);
  6190. Py_XDECREF(exc);
  6191. return NULL;
  6192. }
  6193. PyObject *
  6194. _PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
  6195. {
  6196. if (!PyUnicode_Check(unicode)) {
  6197. PyErr_BadArgument();
  6198. return NULL;
  6199. }
  6200. /* Fast path: if it is a one-byte string, construct
  6201. bytes object directly. */
  6202. if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
  6203. return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
  6204. PyUnicode_GET_LENGTH(unicode));
  6205. /* Non-Latin-1 characters present. Defer to above function to
  6206. raise the exception. */
  6207. return unicode_encode_ucs1(unicode, errors, 256);
  6208. }
  6209. PyObject*
  6210. PyUnicode_AsLatin1String(PyObject *unicode)
  6211. {
  6212. return _PyUnicode_AsLatin1String(unicode, NULL);
  6213. }
  6214. /* --- 7-bit ASCII Codec -------------------------------------------------- */
  6215. PyObject *
  6216. PyUnicode_DecodeASCII(const char *s,
  6217. Py_ssize_t size,
  6218. const char *errors)
  6219. {
  6220. const char *starts = s;
  6221. const char *e = s + size;
  6222. PyObject *error_handler_obj = NULL;
  6223. PyObject *exc = NULL;
  6224. _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
  6225. if (size == 0)
  6226. _Py_RETURN_UNICODE_EMPTY();
  6227. /* ASCII is equivalent to the first 128 ordinals in Unicode. */
  6228. if (size == 1 && (unsigned char)s[0] < 128) {
  6229. return get_latin1_char((unsigned char)s[0]);
  6230. }
  6231. // Shortcut for simple case
  6232. PyObject *u = PyUnicode_New(size, 127);
  6233. if (u == NULL) {
  6234. return NULL;
  6235. }
  6236. Py_ssize_t outpos = ascii_decode(s, e, PyUnicode_1BYTE_DATA(u));
  6237. if (outpos == size) {
  6238. return u;
  6239. }
  6240. _PyUnicodeWriter writer;
  6241. _PyUnicodeWriter_InitWithBuffer(&writer, u);
  6242. writer.pos = outpos;
  6243. s += outpos;
  6244. int kind = writer.kind;
  6245. void *data = writer.data;
  6246. Py_ssize_t startinpos, endinpos;
  6247. while (s < e) {
  6248. unsigned char c = (unsigned char)*s;
  6249. if (c < 128) {
  6250. PyUnicode_WRITE(kind, data, writer.pos, c);
  6251. writer.pos++;
  6252. ++s;
  6253. continue;
  6254. }
  6255. /* byte outsize range 0x00..0x7f: call the error handler */
  6256. if (error_handler == _Py_ERROR_UNKNOWN)
  6257. error_handler = _Py_GetErrorHandler(errors);
  6258. switch (error_handler)
  6259. {
  6260. case _Py_ERROR_REPLACE:
  6261. case _Py_ERROR_SURROGATEESCAPE:
  6262. /* Fast-path: the error handler only writes one character,
  6263. but we may switch to UCS2 at the first write */
  6264. if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
  6265. goto onError;
  6266. kind = writer.kind;
  6267. data = writer.data;
  6268. if (error_handler == _Py_ERROR_REPLACE)
  6269. PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
  6270. else
  6271. PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
  6272. writer.pos++;
  6273. ++s;
  6274. break;
  6275. case _Py_ERROR_IGNORE:
  6276. ++s;
  6277. break;
  6278. default:
  6279. startinpos = s-starts;
  6280. endinpos = startinpos + 1;
  6281. if (unicode_decode_call_errorhandler_writer(
  6282. errors, &error_handler_obj,
  6283. "ascii", "ordinal not in range(128)",
  6284. &starts, &e, &startinpos, &endinpos, &exc, &s,
  6285. &writer))
  6286. goto onError;
  6287. kind = writer.kind;
  6288. data = writer.data;
  6289. }
  6290. }
  6291. Py_XDECREF(error_handler_obj);
  6292. Py_XDECREF(exc);
  6293. return _PyUnicodeWriter_Finish(&writer);
  6294. onError:
  6295. _PyUnicodeWriter_Dealloc(&writer);
  6296. Py_XDECREF(error_handler_obj);
  6297. Py_XDECREF(exc);
  6298. return NULL;
  6299. }
  6300. PyObject *
  6301. _PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
  6302. {
  6303. if (!PyUnicode_Check(unicode)) {
  6304. PyErr_BadArgument();
  6305. return NULL;
  6306. }
  6307. /* Fast path: if it is an ASCII-only string, construct bytes object
  6308. directly. Else defer to above function to raise the exception. */
  6309. if (PyUnicode_IS_ASCII(unicode))
  6310. return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
  6311. PyUnicode_GET_LENGTH(unicode));
  6312. return unicode_encode_ucs1(unicode, errors, 128);
  6313. }
  6314. PyObject *
  6315. PyUnicode_AsASCIIString(PyObject *unicode)
  6316. {
  6317. return _PyUnicode_AsASCIIString(unicode, NULL);
  6318. }
  6319. #ifdef MS_WINDOWS
  6320. /* --- MBCS codecs for Windows -------------------------------------------- */
  6321. #if SIZEOF_INT < SIZEOF_SIZE_T
  6322. #define NEED_RETRY
  6323. #endif
  6324. /* INT_MAX is the theoretical largest chunk (or INT_MAX / 2 when
  6325. transcoding from UTF-16), but INT_MAX / 4 performs better in
  6326. both cases also and avoids partial characters overrunning the
  6327. length limit in MultiByteToWideChar on Windows */
  6328. #define DECODING_CHUNK_SIZE (INT_MAX/4)
  6329. #ifndef WC_ERR_INVALID_CHARS
  6330. # define WC_ERR_INVALID_CHARS 0x0080
  6331. #endif
  6332. static const char*
  6333. code_page_name(UINT code_page, PyObject **obj)
  6334. {
  6335. *obj = NULL;
  6336. if (code_page == CP_ACP)
  6337. return "mbcs";
  6338. if (code_page == CP_UTF7)
  6339. return "CP_UTF7";
  6340. if (code_page == CP_UTF8)
  6341. return "CP_UTF8";
  6342. *obj = PyBytes_FromFormat("cp%u", code_page);
  6343. if (*obj == NULL)
  6344. return NULL;
  6345. return PyBytes_AS_STRING(*obj);
  6346. }
  6347. static DWORD
  6348. decode_code_page_flags(UINT code_page)
  6349. {
  6350. if (code_page == CP_UTF7) {
  6351. /* The CP_UTF7 decoder only supports flags=0 */
  6352. return 0;
  6353. }
  6354. else
  6355. return MB_ERR_INVALID_CHARS;
  6356. }
  6357. /*
  6358. * Decode a byte string from a Windows code page into unicode object in strict
  6359. * mode.
  6360. *
  6361. * Returns consumed size if succeed, returns -2 on decode error, or raise an
  6362. * OSError and returns -1 on other error.
  6363. */
  6364. static int
  6365. decode_code_page_strict(UINT code_page,
  6366. wchar_t **buf,
  6367. Py_ssize_t *bufsize,
  6368. const char *in,
  6369. int insize)
  6370. {
  6371. DWORD flags = MB_ERR_INVALID_CHARS;
  6372. wchar_t *out;
  6373. DWORD outsize;
  6374. /* First get the size of the result */
  6375. assert(insize > 0);
  6376. while ((outsize = MultiByteToWideChar(code_page, flags,
  6377. in, insize, NULL, 0)) <= 0)
  6378. {
  6379. if (!flags || GetLastError() != ERROR_INVALID_FLAGS) {
  6380. goto error;
  6381. }
  6382. /* For some code pages (e.g. UTF-7) flags must be set to 0. */
  6383. flags = 0;
  6384. }
  6385. /* Extend a wchar_t* buffer */
  6386. Py_ssize_t n = *bufsize; /* Get the current length */
  6387. if (widechar_resize(buf, bufsize, n + outsize) < 0) {
  6388. return -1;
  6389. }
  6390. out = *buf + n;
  6391. /* Do the conversion */
  6392. outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
  6393. if (outsize <= 0)
  6394. goto error;
  6395. return insize;
  6396. error:
  6397. if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
  6398. return -2;
  6399. PyErr_SetFromWindowsErr(0);
  6400. return -1;
  6401. }
  6402. /*
  6403. * Decode a byte string from a code page into unicode object with an error
  6404. * handler.
  6405. *
  6406. * Returns consumed size if succeed, or raise an OSError or
  6407. * UnicodeDecodeError exception and returns -1 on error.
  6408. */
  6409. static int
  6410. decode_code_page_errors(UINT code_page,
  6411. wchar_t **buf,
  6412. Py_ssize_t *bufsize,
  6413. const char *in, const int size,
  6414. const char *errors, int final)
  6415. {
  6416. const char *startin = in;
  6417. const char *endin = in + size;
  6418. DWORD flags = MB_ERR_INVALID_CHARS;
  6419. /* Ideally, we should get reason from FormatMessage. This is the Windows
  6420. 2000 English version of the message. */
  6421. const char *reason = "No mapping for the Unicode character exists "
  6422. "in the target code page.";
  6423. /* each step cannot decode more than 1 character, but a character can be
  6424. represented as a surrogate pair */
  6425. wchar_t buffer[2], *out;
  6426. int insize;
  6427. Py_ssize_t outsize;
  6428. PyObject *errorHandler = NULL;
  6429. PyObject *exc = NULL;
  6430. PyObject *encoding_obj = NULL;
  6431. const char *encoding;
  6432. DWORD err;
  6433. int ret = -1;
  6434. assert(size > 0);
  6435. encoding = code_page_name(code_page, &encoding_obj);
  6436. if (encoding == NULL)
  6437. return -1;
  6438. if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
  6439. /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
  6440. UnicodeDecodeError. */
  6441. make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
  6442. if (exc != NULL) {
  6443. PyCodec_StrictErrors(exc);
  6444. Py_CLEAR(exc);
  6445. }
  6446. goto error;
  6447. }
  6448. /* Extend a wchar_t* buffer */
  6449. Py_ssize_t n = *bufsize; /* Get the current length */
  6450. if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
  6451. PyErr_NoMemory();
  6452. goto error;
  6453. }
  6454. if (widechar_resize(buf, bufsize, n + size * Py_ARRAY_LENGTH(buffer)) < 0) {
  6455. goto error;
  6456. }
  6457. out = *buf + n;
  6458. /* Decode the byte string character per character */
  6459. while (in < endin)
  6460. {
  6461. /* Decode a character */
  6462. insize = 1;
  6463. do
  6464. {
  6465. outsize = MultiByteToWideChar(code_page, flags,
  6466. in, insize,
  6467. buffer, Py_ARRAY_LENGTH(buffer));
  6468. if (outsize > 0)
  6469. break;
  6470. err = GetLastError();
  6471. if (err == ERROR_INVALID_FLAGS && flags) {
  6472. /* For some code pages (e.g. UTF-7) flags must be set to 0. */
  6473. flags = 0;
  6474. continue;
  6475. }
  6476. if (err != ERROR_NO_UNICODE_TRANSLATION
  6477. && err != ERROR_INSUFFICIENT_BUFFER)
  6478. {
  6479. PyErr_SetFromWindowsErr(err);
  6480. goto error;
  6481. }
  6482. insize++;
  6483. }
  6484. /* 4=maximum length of a UTF-8 sequence */
  6485. while (insize <= 4 && (in + insize) <= endin);
  6486. if (outsize <= 0) {
  6487. Py_ssize_t startinpos, endinpos, outpos;
  6488. /* last character in partial decode? */
  6489. if (in + insize >= endin && !final)
  6490. break;
  6491. startinpos = in - startin;
  6492. endinpos = startinpos + 1;
  6493. outpos = out - *buf;
  6494. if (unicode_decode_call_errorhandler_wchar(
  6495. errors, &errorHandler,
  6496. encoding, reason,
  6497. &startin, &endin, &startinpos, &endinpos, &exc, &in,
  6498. buf, bufsize, &outpos))
  6499. {
  6500. goto error;
  6501. }
  6502. out = *buf + outpos;
  6503. }
  6504. else {
  6505. in += insize;
  6506. memcpy(out, buffer, outsize * sizeof(wchar_t));
  6507. out += outsize;
  6508. }
  6509. }
  6510. /* Shrink the buffer */
  6511. assert(out - *buf <= *bufsize);
  6512. *bufsize = out - *buf;
  6513. /* (in - startin) <= size and size is an int */
  6514. ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
  6515. error:
  6516. Py_XDECREF(encoding_obj);
  6517. Py_XDECREF(errorHandler);
  6518. Py_XDECREF(exc);
  6519. return ret;
  6520. }
  6521. static PyObject *
  6522. decode_code_page_stateful(int code_page,
  6523. const char *s, Py_ssize_t size,
  6524. const char *errors, Py_ssize_t *consumed)
  6525. {
  6526. wchar_t *buf = NULL;
  6527. Py_ssize_t bufsize = 0;
  6528. int chunk_size, final, converted, done;
  6529. if (code_page < 0) {
  6530. PyErr_SetString(PyExc_ValueError, "invalid code page number");
  6531. return NULL;
  6532. }
  6533. if (size < 0) {
  6534. PyErr_BadInternalCall();
  6535. return NULL;
  6536. }
  6537. if (consumed)
  6538. *consumed = 0;
  6539. do
  6540. {
  6541. #ifdef NEED_RETRY
  6542. if (size > DECODING_CHUNK_SIZE) {
  6543. chunk_size = DECODING_CHUNK_SIZE;
  6544. final = 0;
  6545. done = 0;
  6546. }
  6547. else
  6548. #endif
  6549. {
  6550. chunk_size = (int)size;
  6551. final = (consumed == NULL);
  6552. done = 1;
  6553. }
  6554. if (chunk_size == 0 && done) {
  6555. if (buf != NULL)
  6556. break;
  6557. _Py_RETURN_UNICODE_EMPTY();
  6558. }
  6559. converted = decode_code_page_strict(code_page, &buf, &bufsize,
  6560. s, chunk_size);
  6561. if (converted == -2)
  6562. converted = decode_code_page_errors(code_page, &buf, &bufsize,
  6563. s, chunk_size,
  6564. errors, final);
  6565. assert(converted != 0 || done);
  6566. if (converted < 0) {
  6567. PyMem_Free(buf);
  6568. return NULL;
  6569. }
  6570. if (consumed)
  6571. *consumed += converted;
  6572. s += converted;
  6573. size -= converted;
  6574. } while (!done);
  6575. PyObject *v = PyUnicode_FromWideChar(buf, bufsize);
  6576. PyMem_Free(buf);
  6577. return v;
  6578. }
  6579. PyObject *
  6580. PyUnicode_DecodeCodePageStateful(int code_page,
  6581. const char *s,
  6582. Py_ssize_t size,
  6583. const char *errors,
  6584. Py_ssize_t *consumed)
  6585. {
  6586. return decode_code_page_stateful(code_page, s, size, errors, consumed);
  6587. }
  6588. PyObject *
  6589. PyUnicode_DecodeMBCSStateful(const char *s,
  6590. Py_ssize_t size,
  6591. const char *errors,
  6592. Py_ssize_t *consumed)
  6593. {
  6594. return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
  6595. }
  6596. PyObject *
  6597. PyUnicode_DecodeMBCS(const char *s,
  6598. Py_ssize_t size,
  6599. const char *errors)
  6600. {
  6601. return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
  6602. }
  6603. static DWORD
  6604. encode_code_page_flags(UINT code_page, const char *errors)
  6605. {
  6606. if (code_page == CP_UTF8) {
  6607. return WC_ERR_INVALID_CHARS;
  6608. }
  6609. else if (code_page == CP_UTF7) {
  6610. /* CP_UTF7 only supports flags=0 */
  6611. return 0;
  6612. }
  6613. else {
  6614. if (errors != NULL && strcmp(errors, "replace") == 0)
  6615. return 0;
  6616. else
  6617. return WC_NO_BEST_FIT_CHARS;
  6618. }
  6619. }
  6620. /*
  6621. * Encode a Unicode string to a Windows code page into a byte string in strict
  6622. * mode.
  6623. *
  6624. * Returns consumed characters if succeed, returns -2 on encode error, or raise
  6625. * an OSError and returns -1 on other error.
  6626. */
  6627. static int
  6628. encode_code_page_strict(UINT code_page, PyObject **outbytes,
  6629. PyObject *unicode, Py_ssize_t offset, int len,
  6630. const char* errors)
  6631. {
  6632. BOOL usedDefaultChar = FALSE;
  6633. BOOL *pusedDefaultChar = &usedDefaultChar;
  6634. int outsize;
  6635. wchar_t *p;
  6636. Py_ssize_t size;
  6637. const DWORD flags = encode_code_page_flags(code_page, NULL);
  6638. char *out;
  6639. /* Create a substring so that we can get the UTF-16 representation
  6640. of just the slice under consideration. */
  6641. PyObject *substring;
  6642. int ret = -1;
  6643. assert(len > 0);
  6644. if (code_page != CP_UTF8 && code_page != CP_UTF7)
  6645. pusedDefaultChar = &usedDefaultChar;
  6646. else
  6647. pusedDefaultChar = NULL;
  6648. substring = PyUnicode_Substring(unicode, offset, offset+len);
  6649. if (substring == NULL)
  6650. return -1;
  6651. p = PyUnicode_AsWideCharString(substring, &size);
  6652. Py_CLEAR(substring);
  6653. if (p == NULL) {
  6654. return -1;
  6655. }
  6656. assert(size <= INT_MAX);
  6657. /* First get the size of the result */
  6658. outsize = WideCharToMultiByte(code_page, flags,
  6659. p, (int)size,
  6660. NULL, 0,
  6661. NULL, pusedDefaultChar);
  6662. if (outsize <= 0)
  6663. goto error;
  6664. /* If we used a default char, then we failed! */
  6665. if (pusedDefaultChar && *pusedDefaultChar) {
  6666. ret = -2;
  6667. goto done;
  6668. }
  6669. if (*outbytes == NULL) {
  6670. /* Create string object */
  6671. *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
  6672. if (*outbytes == NULL) {
  6673. goto done;
  6674. }
  6675. out = PyBytes_AS_STRING(*outbytes);
  6676. }
  6677. else {
  6678. /* Extend string object */
  6679. const Py_ssize_t n = PyBytes_Size(*outbytes);
  6680. if (outsize > PY_SSIZE_T_MAX - n) {
  6681. PyErr_NoMemory();
  6682. goto done;
  6683. }
  6684. if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
  6685. goto done;
  6686. }
  6687. out = PyBytes_AS_STRING(*outbytes) + n;
  6688. }
  6689. /* Do the conversion */
  6690. outsize = WideCharToMultiByte(code_page, flags,
  6691. p, (int)size,
  6692. out, outsize,
  6693. NULL, pusedDefaultChar);
  6694. if (outsize <= 0)
  6695. goto error;
  6696. if (pusedDefaultChar && *pusedDefaultChar) {
  6697. ret = -2;
  6698. goto done;
  6699. }
  6700. ret = 0;
  6701. done:
  6702. PyMem_Free(p);
  6703. return ret;
  6704. error:
  6705. if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
  6706. ret = -2;
  6707. goto done;
  6708. }
  6709. PyErr_SetFromWindowsErr(0);
  6710. goto done;
  6711. }
  6712. /*
  6713. * Encode a Unicode string to a Windows code page into a byte string using an
  6714. * error handler.
  6715. *
  6716. * Returns consumed characters if succeed, or raise an OSError and returns
  6717. * -1 on other error.
  6718. */
  6719. static int
  6720. encode_code_page_errors(UINT code_page, PyObject **outbytes,
  6721. PyObject *unicode, Py_ssize_t unicode_offset,
  6722. Py_ssize_t insize, const char* errors)
  6723. {
  6724. const DWORD flags = encode_code_page_flags(code_page, errors);
  6725. Py_ssize_t pos = unicode_offset;
  6726. Py_ssize_t endin = unicode_offset + insize;
  6727. /* Ideally, we should get reason from FormatMessage. This is the Windows
  6728. 2000 English version of the message. */
  6729. const char *reason = "invalid character";
  6730. /* 4=maximum length of a UTF-8 sequence */
  6731. char buffer[4];
  6732. BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
  6733. Py_ssize_t outsize;
  6734. char *out;
  6735. PyObject *errorHandler = NULL;
  6736. PyObject *exc = NULL;
  6737. PyObject *encoding_obj = NULL;
  6738. const char *encoding;
  6739. Py_ssize_t newpos, newoutsize;
  6740. PyObject *rep;
  6741. int ret = -1;
  6742. assert(insize > 0);
  6743. encoding = code_page_name(code_page, &encoding_obj);
  6744. if (encoding == NULL)
  6745. return -1;
  6746. if (errors == NULL || strcmp(errors, "strict") == 0) {
  6747. /* The last error was ERROR_NO_UNICODE_TRANSLATION,
  6748. then we raise a UnicodeEncodeError. */
  6749. make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
  6750. if (exc != NULL) {
  6751. PyCodec_StrictErrors(exc);
  6752. Py_DECREF(exc);
  6753. }
  6754. Py_XDECREF(encoding_obj);
  6755. return -1;
  6756. }
  6757. if (code_page != CP_UTF8 && code_page != CP_UTF7)
  6758. pusedDefaultChar = &usedDefaultChar;
  6759. else
  6760. pusedDefaultChar = NULL;
  6761. if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
  6762. PyErr_NoMemory();
  6763. goto error;
  6764. }
  6765. outsize = insize * Py_ARRAY_LENGTH(buffer);
  6766. if (*outbytes == NULL) {
  6767. /* Create string object */
  6768. *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
  6769. if (*outbytes == NULL)
  6770. goto error;
  6771. out = PyBytes_AS_STRING(*outbytes);
  6772. }
  6773. else {
  6774. /* Extend string object */
  6775. Py_ssize_t n = PyBytes_Size(*outbytes);
  6776. if (n > PY_SSIZE_T_MAX - outsize) {
  6777. PyErr_NoMemory();
  6778. goto error;
  6779. }
  6780. if (_PyBytes_Resize(outbytes, n + outsize) < 0)
  6781. goto error;
  6782. out = PyBytes_AS_STRING(*outbytes) + n;
  6783. }
  6784. /* Encode the string character per character */
  6785. while (pos < endin)
  6786. {
  6787. Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
  6788. wchar_t chars[2];
  6789. int charsize;
  6790. if (ch < 0x10000) {
  6791. chars[0] = (wchar_t)ch;
  6792. charsize = 1;
  6793. }
  6794. else {
  6795. chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
  6796. chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
  6797. charsize = 2;
  6798. }
  6799. outsize = WideCharToMultiByte(code_page, flags,
  6800. chars, charsize,
  6801. buffer, Py_ARRAY_LENGTH(buffer),
  6802. NULL, pusedDefaultChar);
  6803. if (outsize > 0) {
  6804. if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
  6805. {
  6806. pos++;
  6807. memcpy(out, buffer, outsize);
  6808. out += outsize;
  6809. continue;
  6810. }
  6811. }
  6812. else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
  6813. PyErr_SetFromWindowsErr(0);
  6814. goto error;
  6815. }
  6816. rep = unicode_encode_call_errorhandler(
  6817. errors, &errorHandler, encoding, reason,
  6818. unicode, &exc,
  6819. pos, pos + 1, &newpos);
  6820. if (rep == NULL)
  6821. goto error;
  6822. Py_ssize_t morebytes = pos - newpos;
  6823. if (PyBytes_Check(rep)) {
  6824. outsize = PyBytes_GET_SIZE(rep);
  6825. morebytes += outsize;
  6826. if (morebytes > 0) {
  6827. Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
  6828. newoutsize = PyBytes_GET_SIZE(*outbytes) + morebytes;
  6829. if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
  6830. Py_DECREF(rep);
  6831. goto error;
  6832. }
  6833. out = PyBytes_AS_STRING(*outbytes) + offset;
  6834. }
  6835. memcpy(out, PyBytes_AS_STRING(rep), outsize);
  6836. out += outsize;
  6837. }
  6838. else {
  6839. Py_ssize_t i;
  6840. int kind;
  6841. const void *data;
  6842. outsize = PyUnicode_GET_LENGTH(rep);
  6843. morebytes += outsize;
  6844. if (morebytes > 0) {
  6845. Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
  6846. newoutsize = PyBytes_GET_SIZE(*outbytes) + morebytes;
  6847. if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
  6848. Py_DECREF(rep);
  6849. goto error;
  6850. }
  6851. out = PyBytes_AS_STRING(*outbytes) + offset;
  6852. }
  6853. kind = PyUnicode_KIND(rep);
  6854. data = PyUnicode_DATA(rep);
  6855. for (i=0; i < outsize; i++) {
  6856. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  6857. if (ch > 127) {
  6858. raise_encode_exception(&exc,
  6859. encoding, unicode,
  6860. pos, pos + 1,
  6861. "unable to encode error handler result to ASCII");
  6862. Py_DECREF(rep);
  6863. goto error;
  6864. }
  6865. *out = (unsigned char)ch;
  6866. out++;
  6867. }
  6868. }
  6869. pos = newpos;
  6870. Py_DECREF(rep);
  6871. }
  6872. /* write a NUL byte */
  6873. *out = 0;
  6874. outsize = out - PyBytes_AS_STRING(*outbytes);
  6875. assert(outsize <= PyBytes_GET_SIZE(*outbytes));
  6876. if (_PyBytes_Resize(outbytes, outsize) < 0)
  6877. goto error;
  6878. ret = 0;
  6879. error:
  6880. Py_XDECREF(encoding_obj);
  6881. Py_XDECREF(errorHandler);
  6882. Py_XDECREF(exc);
  6883. return ret;
  6884. }
  6885. static PyObject *
  6886. encode_code_page(int code_page,
  6887. PyObject *unicode,
  6888. const char *errors)
  6889. {
  6890. Py_ssize_t len;
  6891. PyObject *outbytes = NULL;
  6892. Py_ssize_t offset;
  6893. int chunk_len, ret, done;
  6894. if (!PyUnicode_Check(unicode)) {
  6895. PyErr_BadArgument();
  6896. return NULL;
  6897. }
  6898. len = PyUnicode_GET_LENGTH(unicode);
  6899. if (code_page < 0) {
  6900. PyErr_SetString(PyExc_ValueError, "invalid code page number");
  6901. return NULL;
  6902. }
  6903. if (len == 0)
  6904. return PyBytes_FromStringAndSize(NULL, 0);
  6905. offset = 0;
  6906. do
  6907. {
  6908. #ifdef NEED_RETRY
  6909. if (len > DECODING_CHUNK_SIZE) {
  6910. chunk_len = DECODING_CHUNK_SIZE;
  6911. done = 0;
  6912. }
  6913. else
  6914. #endif
  6915. {
  6916. chunk_len = (int)len;
  6917. done = 1;
  6918. }
  6919. ret = encode_code_page_strict(code_page, &outbytes,
  6920. unicode, offset, chunk_len,
  6921. errors);
  6922. if (ret == -2)
  6923. ret = encode_code_page_errors(code_page, &outbytes,
  6924. unicode, offset,
  6925. chunk_len, errors);
  6926. if (ret < 0) {
  6927. Py_XDECREF(outbytes);
  6928. return NULL;
  6929. }
  6930. offset += chunk_len;
  6931. len -= chunk_len;
  6932. } while (!done);
  6933. return outbytes;
  6934. }
  6935. PyObject *
  6936. PyUnicode_EncodeCodePage(int code_page,
  6937. PyObject *unicode,
  6938. const char *errors)
  6939. {
  6940. return encode_code_page(code_page, unicode, errors);
  6941. }
  6942. PyObject *
  6943. PyUnicode_AsMBCSString(PyObject *unicode)
  6944. {
  6945. return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
  6946. }
  6947. #undef NEED_RETRY
  6948. #endif /* MS_WINDOWS */
  6949. /* --- Character Mapping Codec -------------------------------------------- */
  6950. static int
  6951. charmap_decode_string(const char *s,
  6952. Py_ssize_t size,
  6953. PyObject *mapping,
  6954. const char *errors,
  6955. _PyUnicodeWriter *writer)
  6956. {
  6957. const char *starts = s;
  6958. const char *e;
  6959. Py_ssize_t startinpos, endinpos;
  6960. PyObject *errorHandler = NULL, *exc = NULL;
  6961. Py_ssize_t maplen;
  6962. int mapkind;
  6963. const void *mapdata;
  6964. Py_UCS4 x;
  6965. unsigned char ch;
  6966. maplen = PyUnicode_GET_LENGTH(mapping);
  6967. mapdata = PyUnicode_DATA(mapping);
  6968. mapkind = PyUnicode_KIND(mapping);
  6969. e = s + size;
  6970. if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
  6971. /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
  6972. * is disabled in encoding aliases, latin1 is preferred because
  6973. * its implementation is faster. */
  6974. const Py_UCS1 *mapdata_ucs1 = (const Py_UCS1 *)mapdata;
  6975. Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
  6976. Py_UCS4 maxchar = writer->maxchar;
  6977. assert (writer->kind == PyUnicode_1BYTE_KIND);
  6978. while (s < e) {
  6979. ch = *s;
  6980. x = mapdata_ucs1[ch];
  6981. if (x > maxchar) {
  6982. if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
  6983. goto onError;
  6984. maxchar = writer->maxchar;
  6985. outdata = (Py_UCS1 *)writer->data;
  6986. }
  6987. outdata[writer->pos] = x;
  6988. writer->pos++;
  6989. ++s;
  6990. }
  6991. return 0;
  6992. }
  6993. while (s < e) {
  6994. if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
  6995. int outkind = writer->kind;
  6996. const Py_UCS2 *mapdata_ucs2 = (const Py_UCS2 *)mapdata;
  6997. if (outkind == PyUnicode_1BYTE_KIND) {
  6998. Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
  6999. Py_UCS4 maxchar = writer->maxchar;
  7000. while (s < e) {
  7001. ch = *s;
  7002. x = mapdata_ucs2[ch];
  7003. if (x > maxchar)
  7004. goto Error;
  7005. outdata[writer->pos] = x;
  7006. writer->pos++;
  7007. ++s;
  7008. }
  7009. break;
  7010. }
  7011. else if (outkind == PyUnicode_2BYTE_KIND) {
  7012. Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
  7013. while (s < e) {
  7014. ch = *s;
  7015. x = mapdata_ucs2[ch];
  7016. if (x == 0xFFFE)
  7017. goto Error;
  7018. outdata[writer->pos] = x;
  7019. writer->pos++;
  7020. ++s;
  7021. }
  7022. break;
  7023. }
  7024. }
  7025. ch = *s;
  7026. if (ch < maplen)
  7027. x = PyUnicode_READ(mapkind, mapdata, ch);
  7028. else
  7029. x = 0xfffe; /* invalid value */
  7030. Error:
  7031. if (x == 0xfffe)
  7032. {
  7033. /* undefined mapping */
  7034. startinpos = s-starts;
  7035. endinpos = startinpos+1;
  7036. if (unicode_decode_call_errorhandler_writer(
  7037. errors, &errorHandler,
  7038. "charmap", "character maps to <undefined>",
  7039. &starts, &e, &startinpos, &endinpos, &exc, &s,
  7040. writer)) {
  7041. goto onError;
  7042. }
  7043. continue;
  7044. }
  7045. if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
  7046. goto onError;
  7047. ++s;
  7048. }
  7049. Py_XDECREF(errorHandler);
  7050. Py_XDECREF(exc);
  7051. return 0;
  7052. onError:
  7053. Py_XDECREF(errorHandler);
  7054. Py_XDECREF(exc);
  7055. return -1;
  7056. }
  7057. static int
  7058. charmap_decode_mapping(const char *s,
  7059. Py_ssize_t size,
  7060. PyObject *mapping,
  7061. const char *errors,
  7062. _PyUnicodeWriter *writer)
  7063. {
  7064. const char *starts = s;
  7065. const char *e;
  7066. Py_ssize_t startinpos, endinpos;
  7067. PyObject *errorHandler = NULL, *exc = NULL;
  7068. unsigned char ch;
  7069. PyObject *key, *item = NULL;
  7070. e = s + size;
  7071. while (s < e) {
  7072. ch = *s;
  7073. /* Get mapping (char ordinal -> integer, Unicode char or None) */
  7074. key = PyLong_FromLong((long)ch);
  7075. if (key == NULL)
  7076. goto onError;
  7077. item = PyObject_GetItem(mapping, key);
  7078. Py_DECREF(key);
  7079. if (item == NULL) {
  7080. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  7081. /* No mapping found means: mapping is undefined. */
  7082. PyErr_Clear();
  7083. goto Undefined;
  7084. } else
  7085. goto onError;
  7086. }
  7087. /* Apply mapping */
  7088. if (item == Py_None)
  7089. goto Undefined;
  7090. if (PyLong_Check(item)) {
  7091. long value = PyLong_AS_LONG(item);
  7092. if (value == 0xFFFE)
  7093. goto Undefined;
  7094. if (value < 0 || value > MAX_UNICODE) {
  7095. PyErr_Format(PyExc_TypeError,
  7096. "character mapping must be in range(0x%x)",
  7097. (unsigned long)MAX_UNICODE + 1);
  7098. goto onError;
  7099. }
  7100. if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
  7101. goto onError;
  7102. }
  7103. else if (PyUnicode_Check(item)) {
  7104. if (PyUnicode_GET_LENGTH(item) == 1) {
  7105. Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
  7106. if (value == 0xFFFE)
  7107. goto Undefined;
  7108. if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
  7109. goto onError;
  7110. }
  7111. else {
  7112. writer->overallocate = 1;
  7113. if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
  7114. goto onError;
  7115. }
  7116. }
  7117. else {
  7118. /* wrong return value */
  7119. PyErr_SetString(PyExc_TypeError,
  7120. "character mapping must return integer, None or str");
  7121. goto onError;
  7122. }
  7123. Py_CLEAR(item);
  7124. ++s;
  7125. continue;
  7126. Undefined:
  7127. /* undefined mapping */
  7128. Py_CLEAR(item);
  7129. startinpos = s-starts;
  7130. endinpos = startinpos+1;
  7131. if (unicode_decode_call_errorhandler_writer(
  7132. errors, &errorHandler,
  7133. "charmap", "character maps to <undefined>",
  7134. &starts, &e, &startinpos, &endinpos, &exc, &s,
  7135. writer)) {
  7136. goto onError;
  7137. }
  7138. }
  7139. Py_XDECREF(errorHandler);
  7140. Py_XDECREF(exc);
  7141. return 0;
  7142. onError:
  7143. Py_XDECREF(item);
  7144. Py_XDECREF(errorHandler);
  7145. Py_XDECREF(exc);
  7146. return -1;
  7147. }
  7148. PyObject *
  7149. PyUnicode_DecodeCharmap(const char *s,
  7150. Py_ssize_t size,
  7151. PyObject *mapping,
  7152. const char *errors)
  7153. {
  7154. _PyUnicodeWriter writer;
  7155. /* Default to Latin-1 */
  7156. if (mapping == NULL)
  7157. return PyUnicode_DecodeLatin1(s, size, errors);
  7158. if (size == 0)
  7159. _Py_RETURN_UNICODE_EMPTY();
  7160. _PyUnicodeWriter_Init(&writer);
  7161. writer.min_length = size;
  7162. if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
  7163. goto onError;
  7164. if (PyUnicode_CheckExact(mapping)) {
  7165. if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
  7166. goto onError;
  7167. }
  7168. else {
  7169. if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
  7170. goto onError;
  7171. }
  7172. return _PyUnicodeWriter_Finish(&writer);
  7173. onError:
  7174. _PyUnicodeWriter_Dealloc(&writer);
  7175. return NULL;
  7176. }
  7177. /* Charmap encoding: the lookup table */
  7178. /*[clinic input]
  7179. class EncodingMap "struct encoding_map *" "&EncodingMapType"
  7180. [clinic start generated code]*/
  7181. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=14e46bbb6c522d22]*/
  7182. struct encoding_map {
  7183. PyObject_HEAD
  7184. unsigned char level1[32];
  7185. int count2, count3;
  7186. unsigned char level23[1];
  7187. };
  7188. /*[clinic input]
  7189. EncodingMap.size
  7190. Return the size (in bytes) of this object.
  7191. [clinic start generated code]*/
  7192. static PyObject *
  7193. EncodingMap_size_impl(struct encoding_map *self)
  7194. /*[clinic end generated code: output=c4c969e4c99342a4 input=004ff13f26bb5366]*/
  7195. {
  7196. return PyLong_FromLong((sizeof(*self) - 1) + 16*self->count2 +
  7197. 128*self->count3);
  7198. }
  7199. static PyMethodDef encoding_map_methods[] = {
  7200. ENCODINGMAP_SIZE_METHODDEF
  7201. {NULL, NULL}
  7202. };
  7203. static PyTypeObject EncodingMapType = {
  7204. PyVarObject_HEAD_INIT(NULL, 0)
  7205. .tp_name = "EncodingMap",
  7206. .tp_basicsize = sizeof(struct encoding_map),
  7207. /* methods */
  7208. .tp_flags = Py_TPFLAGS_DEFAULT,
  7209. .tp_methods = encoding_map_methods,
  7210. };
  7211. PyObject*
  7212. PyUnicode_BuildEncodingMap(PyObject* string)
  7213. {
  7214. PyObject *result;
  7215. struct encoding_map *mresult;
  7216. int i;
  7217. int need_dict = 0;
  7218. unsigned char level1[32];
  7219. unsigned char level2[512];
  7220. unsigned char *mlevel1, *mlevel2, *mlevel3;
  7221. int count2 = 0, count3 = 0;
  7222. int kind;
  7223. const void *data;
  7224. Py_ssize_t length;
  7225. Py_UCS4 ch;
  7226. if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
  7227. PyErr_BadArgument();
  7228. return NULL;
  7229. }
  7230. kind = PyUnicode_KIND(string);
  7231. data = PyUnicode_DATA(string);
  7232. length = PyUnicode_GET_LENGTH(string);
  7233. length = Py_MIN(length, 256);
  7234. memset(level1, 0xFF, sizeof level1);
  7235. memset(level2, 0xFF, sizeof level2);
  7236. /* If there isn't a one-to-one mapping of NULL to \0,
  7237. or if there are non-BMP characters, we need to use
  7238. a mapping dictionary. */
  7239. if (PyUnicode_READ(kind, data, 0) != 0)
  7240. need_dict = 1;
  7241. for (i = 1; i < length; i++) {
  7242. int l1, l2;
  7243. ch = PyUnicode_READ(kind, data, i);
  7244. if (ch == 0 || ch > 0xFFFF) {
  7245. need_dict = 1;
  7246. break;
  7247. }
  7248. if (ch == 0xFFFE)
  7249. /* unmapped character */
  7250. continue;
  7251. l1 = ch >> 11;
  7252. l2 = ch >> 7;
  7253. if (level1[l1] == 0xFF)
  7254. level1[l1] = count2++;
  7255. if (level2[l2] == 0xFF)
  7256. level2[l2] = count3++;
  7257. }
  7258. if (count2 >= 0xFF || count3 >= 0xFF)
  7259. need_dict = 1;
  7260. if (need_dict) {
  7261. PyObject *result = PyDict_New();
  7262. if (!result)
  7263. return NULL;
  7264. for (i = 0; i < length; i++) {
  7265. Py_UCS4 c = PyUnicode_READ(kind, data, i);
  7266. PyObject *key = PyLong_FromLong(c);
  7267. if (key == NULL) {
  7268. Py_DECREF(result);
  7269. return NULL;
  7270. }
  7271. PyObject *value = PyLong_FromLong(i);
  7272. if (value == NULL) {
  7273. Py_DECREF(key);
  7274. Py_DECREF(result);
  7275. return NULL;
  7276. }
  7277. int rc = PyDict_SetItem(result, key, value);
  7278. Py_DECREF(key);
  7279. Py_DECREF(value);
  7280. if (rc < 0) {
  7281. Py_DECREF(result);
  7282. return NULL;
  7283. }
  7284. }
  7285. return result;
  7286. }
  7287. /* Create a three-level trie */
  7288. result = PyObject_Malloc(sizeof(struct encoding_map) +
  7289. 16*count2 + 128*count3 - 1);
  7290. if (!result) {
  7291. return PyErr_NoMemory();
  7292. }
  7293. _PyObject_Init(result, &EncodingMapType);
  7294. mresult = (struct encoding_map*)result;
  7295. mresult->count2 = count2;
  7296. mresult->count3 = count3;
  7297. mlevel1 = mresult->level1;
  7298. mlevel2 = mresult->level23;
  7299. mlevel3 = mresult->level23 + 16*count2;
  7300. memcpy(mlevel1, level1, 32);
  7301. memset(mlevel2, 0xFF, 16*count2);
  7302. memset(mlevel3, 0, 128*count3);
  7303. count3 = 0;
  7304. for (i = 1; i < length; i++) {
  7305. int o1, o2, o3, i2, i3;
  7306. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  7307. if (ch == 0xFFFE)
  7308. /* unmapped character */
  7309. continue;
  7310. o1 = ch>>11;
  7311. o2 = (ch>>7) & 0xF;
  7312. i2 = 16*mlevel1[o1] + o2;
  7313. if (mlevel2[i2] == 0xFF)
  7314. mlevel2[i2] = count3++;
  7315. o3 = ch & 0x7F;
  7316. i3 = 128*mlevel2[i2] + o3;
  7317. mlevel3[i3] = i;
  7318. }
  7319. return result;
  7320. }
  7321. static int
  7322. encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
  7323. {
  7324. struct encoding_map *map = (struct encoding_map*)mapping;
  7325. int l1 = c>>11;
  7326. int l2 = (c>>7) & 0xF;
  7327. int l3 = c & 0x7F;
  7328. int i;
  7329. if (c > 0xFFFF)
  7330. return -1;
  7331. if (c == 0)
  7332. return 0;
  7333. /* level 1*/
  7334. i = map->level1[l1];
  7335. if (i == 0xFF) {
  7336. return -1;
  7337. }
  7338. /* level 2*/
  7339. i = map->level23[16*i+l2];
  7340. if (i == 0xFF) {
  7341. return -1;
  7342. }
  7343. /* level 3 */
  7344. i = map->level23[16*map->count2 + 128*i + l3];
  7345. if (i == 0) {
  7346. return -1;
  7347. }
  7348. return i;
  7349. }
  7350. /* Lookup the character ch in the mapping. If the character
  7351. can't be found, Py_None is returned (or NULL, if another
  7352. error occurred). */
  7353. static PyObject *
  7354. charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
  7355. {
  7356. PyObject *w = PyLong_FromLong((long)c);
  7357. PyObject *x;
  7358. if (w == NULL)
  7359. return NULL;
  7360. x = PyObject_GetItem(mapping, w);
  7361. Py_DECREF(w);
  7362. if (x == NULL) {
  7363. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  7364. /* No mapping found means: mapping is undefined. */
  7365. PyErr_Clear();
  7366. Py_RETURN_NONE;
  7367. } else
  7368. return NULL;
  7369. }
  7370. else if (x == Py_None)
  7371. return x;
  7372. else if (PyLong_Check(x)) {
  7373. long value = PyLong_AS_LONG(x);
  7374. if (value < 0 || value > 255) {
  7375. PyErr_SetString(PyExc_TypeError,
  7376. "character mapping must be in range(256)");
  7377. Py_DECREF(x);
  7378. return NULL;
  7379. }
  7380. return x;
  7381. }
  7382. else if (PyBytes_Check(x))
  7383. return x;
  7384. else {
  7385. /* wrong return value */
  7386. PyErr_Format(PyExc_TypeError,
  7387. "character mapping must return integer, bytes or None, not %.400s",
  7388. Py_TYPE(x)->tp_name);
  7389. Py_DECREF(x);
  7390. return NULL;
  7391. }
  7392. }
  7393. static int
  7394. charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
  7395. {
  7396. Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
  7397. /* exponentially overallocate to minimize reallocations */
  7398. if (requiredsize < 2*outsize)
  7399. requiredsize = 2*outsize;
  7400. if (_PyBytes_Resize(outobj, requiredsize))
  7401. return -1;
  7402. return 0;
  7403. }
  7404. typedef enum charmapencode_result {
  7405. enc_SUCCESS, enc_FAILED, enc_EXCEPTION
  7406. } charmapencode_result;
  7407. /* lookup the character, put the result in the output string and adjust
  7408. various state variables. Resize the output bytes object if not enough
  7409. space is available. Return a new reference to the object that
  7410. was put in the output buffer, or Py_None, if the mapping was undefined
  7411. (in which case no character was written) or NULL, if a
  7412. reallocation error occurred. The caller must decref the result */
  7413. static charmapencode_result
  7414. charmapencode_output(Py_UCS4 c, PyObject *mapping,
  7415. PyObject **outobj, Py_ssize_t *outpos)
  7416. {
  7417. PyObject *rep;
  7418. char *outstart;
  7419. Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
  7420. if (Py_IS_TYPE(mapping, &EncodingMapType)) {
  7421. int res = encoding_map_lookup(c, mapping);
  7422. Py_ssize_t requiredsize = *outpos+1;
  7423. if (res == -1)
  7424. return enc_FAILED;
  7425. if (outsize<requiredsize)
  7426. if (charmapencode_resize(outobj, outpos, requiredsize))
  7427. return enc_EXCEPTION;
  7428. outstart = PyBytes_AS_STRING(*outobj);
  7429. outstart[(*outpos)++] = (char)res;
  7430. return enc_SUCCESS;
  7431. }
  7432. rep = charmapencode_lookup(c, mapping);
  7433. if (rep==NULL)
  7434. return enc_EXCEPTION;
  7435. else if (rep==Py_None) {
  7436. Py_DECREF(rep);
  7437. return enc_FAILED;
  7438. } else {
  7439. if (PyLong_Check(rep)) {
  7440. Py_ssize_t requiredsize = *outpos+1;
  7441. if (outsize<requiredsize)
  7442. if (charmapencode_resize(outobj, outpos, requiredsize)) {
  7443. Py_DECREF(rep);
  7444. return enc_EXCEPTION;
  7445. }
  7446. outstart = PyBytes_AS_STRING(*outobj);
  7447. outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
  7448. }
  7449. else {
  7450. const char *repchars = PyBytes_AS_STRING(rep);
  7451. Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
  7452. Py_ssize_t requiredsize = *outpos+repsize;
  7453. if (outsize<requiredsize)
  7454. if (charmapencode_resize(outobj, outpos, requiredsize)) {
  7455. Py_DECREF(rep);
  7456. return enc_EXCEPTION;
  7457. }
  7458. outstart = PyBytes_AS_STRING(*outobj);
  7459. memcpy(outstart + *outpos, repchars, repsize);
  7460. *outpos += repsize;
  7461. }
  7462. }
  7463. Py_DECREF(rep);
  7464. return enc_SUCCESS;
  7465. }
  7466. /* handle an error in PyUnicode_EncodeCharmap
  7467. Return 0 on success, -1 on error */
  7468. static int
  7469. charmap_encoding_error(
  7470. PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
  7471. PyObject **exceptionObject,
  7472. _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
  7473. PyObject **res, Py_ssize_t *respos)
  7474. {
  7475. PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
  7476. Py_ssize_t size, repsize;
  7477. Py_ssize_t newpos;
  7478. int kind;
  7479. const void *data;
  7480. Py_ssize_t index;
  7481. /* startpos for collecting unencodable chars */
  7482. Py_ssize_t collstartpos = *inpos;
  7483. Py_ssize_t collendpos = *inpos+1;
  7484. Py_ssize_t collpos;
  7485. const char *encoding = "charmap";
  7486. const char *reason = "character maps to <undefined>";
  7487. charmapencode_result x;
  7488. Py_UCS4 ch;
  7489. int val;
  7490. size = PyUnicode_GET_LENGTH(unicode);
  7491. /* find all unencodable characters */
  7492. while (collendpos < size) {
  7493. PyObject *rep;
  7494. if (Py_IS_TYPE(mapping, &EncodingMapType)) {
  7495. ch = PyUnicode_READ_CHAR(unicode, collendpos);
  7496. val = encoding_map_lookup(ch, mapping);
  7497. if (val != -1)
  7498. break;
  7499. ++collendpos;
  7500. continue;
  7501. }
  7502. ch = PyUnicode_READ_CHAR(unicode, collendpos);
  7503. rep = charmapencode_lookup(ch, mapping);
  7504. if (rep==NULL)
  7505. return -1;
  7506. else if (rep!=Py_None) {
  7507. Py_DECREF(rep);
  7508. break;
  7509. }
  7510. Py_DECREF(rep);
  7511. ++collendpos;
  7512. }
  7513. /* cache callback name lookup
  7514. * (if not done yet, i.e. it's the first error) */
  7515. if (*error_handler == _Py_ERROR_UNKNOWN)
  7516. *error_handler = _Py_GetErrorHandler(errors);
  7517. switch (*error_handler) {
  7518. case _Py_ERROR_STRICT:
  7519. raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
  7520. return -1;
  7521. case _Py_ERROR_REPLACE:
  7522. for (collpos = collstartpos; collpos<collendpos; ++collpos) {
  7523. x = charmapencode_output('?', mapping, res, respos);
  7524. if (x==enc_EXCEPTION) {
  7525. return -1;
  7526. }
  7527. else if (x==enc_FAILED) {
  7528. raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
  7529. return -1;
  7530. }
  7531. }
  7532. /* fall through */
  7533. case _Py_ERROR_IGNORE:
  7534. *inpos = collendpos;
  7535. break;
  7536. case _Py_ERROR_XMLCHARREFREPLACE:
  7537. /* generate replacement (temporarily (mis)uses p) */
  7538. for (collpos = collstartpos; collpos < collendpos; ++collpos) {
  7539. char buffer[2+29+1+1];
  7540. char *cp;
  7541. sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
  7542. for (cp = buffer; *cp; ++cp) {
  7543. x = charmapencode_output(*cp, mapping, res, respos);
  7544. if (x==enc_EXCEPTION)
  7545. return -1;
  7546. else if (x==enc_FAILED) {
  7547. raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
  7548. return -1;
  7549. }
  7550. }
  7551. }
  7552. *inpos = collendpos;
  7553. break;
  7554. default:
  7555. repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
  7556. encoding, reason, unicode, exceptionObject,
  7557. collstartpos, collendpos, &newpos);
  7558. if (repunicode == NULL)
  7559. return -1;
  7560. if (PyBytes_Check(repunicode)) {
  7561. /* Directly copy bytes result to output. */
  7562. Py_ssize_t outsize = PyBytes_Size(*res);
  7563. Py_ssize_t requiredsize;
  7564. repsize = PyBytes_Size(repunicode);
  7565. requiredsize = *respos + repsize;
  7566. if (requiredsize > outsize)
  7567. /* Make room for all additional bytes. */
  7568. if (charmapencode_resize(res, respos, requiredsize)) {
  7569. Py_DECREF(repunicode);
  7570. return -1;
  7571. }
  7572. memcpy(PyBytes_AsString(*res) + *respos,
  7573. PyBytes_AsString(repunicode), repsize);
  7574. *respos += repsize;
  7575. *inpos = newpos;
  7576. Py_DECREF(repunicode);
  7577. break;
  7578. }
  7579. /* generate replacement */
  7580. repsize = PyUnicode_GET_LENGTH(repunicode);
  7581. data = PyUnicode_DATA(repunicode);
  7582. kind = PyUnicode_KIND(repunicode);
  7583. for (index = 0; index < repsize; index++) {
  7584. Py_UCS4 repch = PyUnicode_READ(kind, data, index);
  7585. x = charmapencode_output(repch, mapping, res, respos);
  7586. if (x==enc_EXCEPTION) {
  7587. Py_DECREF(repunicode);
  7588. return -1;
  7589. }
  7590. else if (x==enc_FAILED) {
  7591. Py_DECREF(repunicode);
  7592. raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
  7593. return -1;
  7594. }
  7595. }
  7596. *inpos = newpos;
  7597. Py_DECREF(repunicode);
  7598. }
  7599. return 0;
  7600. }
  7601. PyObject *
  7602. _PyUnicode_EncodeCharmap(PyObject *unicode,
  7603. PyObject *mapping,
  7604. const char *errors)
  7605. {
  7606. /* output object */
  7607. PyObject *res = NULL;
  7608. /* current input position */
  7609. Py_ssize_t inpos = 0;
  7610. Py_ssize_t size;
  7611. /* current output position */
  7612. Py_ssize_t respos = 0;
  7613. PyObject *error_handler_obj = NULL;
  7614. PyObject *exc = NULL;
  7615. _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
  7616. const void *data;
  7617. int kind;
  7618. size = PyUnicode_GET_LENGTH(unicode);
  7619. data = PyUnicode_DATA(unicode);
  7620. kind = PyUnicode_KIND(unicode);
  7621. /* Default to Latin-1 */
  7622. if (mapping == NULL)
  7623. return unicode_encode_ucs1(unicode, errors, 256);
  7624. /* allocate enough for a simple encoding without
  7625. replacements, if we need more, we'll resize */
  7626. res = PyBytes_FromStringAndSize(NULL, size);
  7627. if (res == NULL)
  7628. goto onError;
  7629. if (size == 0)
  7630. return res;
  7631. while (inpos<size) {
  7632. Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
  7633. /* try to encode it */
  7634. charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
  7635. if (x==enc_EXCEPTION) /* error */
  7636. goto onError;
  7637. if (x==enc_FAILED) { /* unencodable character */
  7638. if (charmap_encoding_error(unicode, &inpos, mapping,
  7639. &exc,
  7640. &error_handler, &error_handler_obj, errors,
  7641. &res, &respos)) {
  7642. goto onError;
  7643. }
  7644. }
  7645. else
  7646. /* done with this character => adjust input position */
  7647. ++inpos;
  7648. }
  7649. /* Resize if we allocated to much */
  7650. if (respos<PyBytes_GET_SIZE(res))
  7651. if (_PyBytes_Resize(&res, respos) < 0)
  7652. goto onError;
  7653. Py_XDECREF(exc);
  7654. Py_XDECREF(error_handler_obj);
  7655. return res;
  7656. onError:
  7657. Py_XDECREF(res);
  7658. Py_XDECREF(exc);
  7659. Py_XDECREF(error_handler_obj);
  7660. return NULL;
  7661. }
  7662. PyObject *
  7663. PyUnicode_AsCharmapString(PyObject *unicode,
  7664. PyObject *mapping)
  7665. {
  7666. if (!PyUnicode_Check(unicode) || mapping == NULL) {
  7667. PyErr_BadArgument();
  7668. return NULL;
  7669. }
  7670. return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
  7671. }
  7672. /* create or adjust a UnicodeTranslateError */
  7673. static void
  7674. make_translate_exception(PyObject **exceptionObject,
  7675. PyObject *unicode,
  7676. Py_ssize_t startpos, Py_ssize_t endpos,
  7677. const char *reason)
  7678. {
  7679. if (*exceptionObject == NULL) {
  7680. *exceptionObject = _PyUnicodeTranslateError_Create(
  7681. unicode, startpos, endpos, reason);
  7682. }
  7683. else {
  7684. if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
  7685. goto onError;
  7686. if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
  7687. goto onError;
  7688. if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
  7689. goto onError;
  7690. return;
  7691. onError:
  7692. Py_CLEAR(*exceptionObject);
  7693. }
  7694. }
  7695. /* error handling callback helper:
  7696. build arguments, call the callback and check the arguments,
  7697. put the result into newpos and return the replacement string, which
  7698. has to be freed by the caller */
  7699. static PyObject *
  7700. unicode_translate_call_errorhandler(const char *errors,
  7701. PyObject **errorHandler,
  7702. const char *reason,
  7703. PyObject *unicode, PyObject **exceptionObject,
  7704. Py_ssize_t startpos, Py_ssize_t endpos,
  7705. Py_ssize_t *newpos)
  7706. {
  7707. static const char *argparse = "Un;translating error handler must return (str, int) tuple";
  7708. Py_ssize_t i_newpos;
  7709. PyObject *restuple;
  7710. PyObject *resunicode;
  7711. if (*errorHandler == NULL) {
  7712. *errorHandler = PyCodec_LookupError(errors);
  7713. if (*errorHandler == NULL)
  7714. return NULL;
  7715. }
  7716. make_translate_exception(exceptionObject,
  7717. unicode, startpos, endpos, reason);
  7718. if (*exceptionObject == NULL)
  7719. return NULL;
  7720. restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
  7721. if (restuple == NULL)
  7722. return NULL;
  7723. if (!PyTuple_Check(restuple)) {
  7724. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  7725. Py_DECREF(restuple);
  7726. return NULL;
  7727. }
  7728. if (!PyArg_ParseTuple(restuple, argparse,
  7729. &resunicode, &i_newpos)) {
  7730. Py_DECREF(restuple);
  7731. return NULL;
  7732. }
  7733. if (i_newpos<0)
  7734. *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
  7735. else
  7736. *newpos = i_newpos;
  7737. if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
  7738. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
  7739. Py_DECREF(restuple);
  7740. return NULL;
  7741. }
  7742. Py_INCREF(resunicode);
  7743. Py_DECREF(restuple);
  7744. return resunicode;
  7745. }
  7746. /* Lookup the character ch in the mapping and put the result in result,
  7747. which must be decrefed by the caller.
  7748. Return 0 on success, -1 on error */
  7749. static int
  7750. charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
  7751. {
  7752. PyObject *w = PyLong_FromLong((long)c);
  7753. PyObject *x;
  7754. if (w == NULL)
  7755. return -1;
  7756. x = PyObject_GetItem(mapping, w);
  7757. Py_DECREF(w);
  7758. if (x == NULL) {
  7759. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  7760. /* No mapping found means: use 1:1 mapping. */
  7761. PyErr_Clear();
  7762. *result = NULL;
  7763. return 0;
  7764. } else
  7765. return -1;
  7766. }
  7767. else if (x == Py_None) {
  7768. *result = x;
  7769. return 0;
  7770. }
  7771. else if (PyLong_Check(x)) {
  7772. long value = PyLong_AS_LONG(x);
  7773. if (value < 0 || value > MAX_UNICODE) {
  7774. PyErr_Format(PyExc_ValueError,
  7775. "character mapping must be in range(0x%x)",
  7776. MAX_UNICODE+1);
  7777. Py_DECREF(x);
  7778. return -1;
  7779. }
  7780. *result = x;
  7781. return 0;
  7782. }
  7783. else if (PyUnicode_Check(x)) {
  7784. *result = x;
  7785. return 0;
  7786. }
  7787. else {
  7788. /* wrong return value */
  7789. PyErr_SetString(PyExc_TypeError,
  7790. "character mapping must return integer, None or str");
  7791. Py_DECREF(x);
  7792. return -1;
  7793. }
  7794. }
  7795. /* lookup the character, write the result into the writer.
  7796. Return 1 if the result was written into the writer, return 0 if the mapping
  7797. was undefined, raise an exception return -1 on error. */
  7798. static int
  7799. charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
  7800. _PyUnicodeWriter *writer)
  7801. {
  7802. PyObject *item;
  7803. if (charmaptranslate_lookup(ch, mapping, &item))
  7804. return -1;
  7805. if (item == NULL) {
  7806. /* not found => default to 1:1 mapping */
  7807. if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
  7808. return -1;
  7809. }
  7810. return 1;
  7811. }
  7812. if (item == Py_None) {
  7813. Py_DECREF(item);
  7814. return 0;
  7815. }
  7816. if (PyLong_Check(item)) {
  7817. long ch = (Py_UCS4)PyLong_AS_LONG(item);
  7818. /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
  7819. used it */
  7820. if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
  7821. Py_DECREF(item);
  7822. return -1;
  7823. }
  7824. Py_DECREF(item);
  7825. return 1;
  7826. }
  7827. if (!PyUnicode_Check(item)) {
  7828. Py_DECREF(item);
  7829. return -1;
  7830. }
  7831. if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
  7832. Py_DECREF(item);
  7833. return -1;
  7834. }
  7835. Py_DECREF(item);
  7836. return 1;
  7837. }
  7838. static int
  7839. unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
  7840. Py_UCS1 *translate)
  7841. {
  7842. PyObject *item = NULL;
  7843. int ret = 0;
  7844. if (charmaptranslate_lookup(ch, mapping, &item)) {
  7845. return -1;
  7846. }
  7847. if (item == Py_None) {
  7848. /* deletion */
  7849. translate[ch] = 0xfe;
  7850. }
  7851. else if (item == NULL) {
  7852. /* not found => default to 1:1 mapping */
  7853. translate[ch] = ch;
  7854. return 1;
  7855. }
  7856. else if (PyLong_Check(item)) {
  7857. long replace = PyLong_AS_LONG(item);
  7858. /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
  7859. used it */
  7860. if (127 < replace) {
  7861. /* invalid character or character outside ASCII:
  7862. skip the fast translate */
  7863. goto exit;
  7864. }
  7865. translate[ch] = (Py_UCS1)replace;
  7866. }
  7867. else if (PyUnicode_Check(item)) {
  7868. Py_UCS4 replace;
  7869. if (PyUnicode_GET_LENGTH(item) != 1)
  7870. goto exit;
  7871. replace = PyUnicode_READ_CHAR(item, 0);
  7872. if (replace > 127)
  7873. goto exit;
  7874. translate[ch] = (Py_UCS1)replace;
  7875. }
  7876. else {
  7877. /* not None, NULL, long or unicode */
  7878. goto exit;
  7879. }
  7880. ret = 1;
  7881. exit:
  7882. Py_DECREF(item);
  7883. return ret;
  7884. }
  7885. /* Fast path for ascii => ascii translation. Return 1 if the whole string
  7886. was translated into writer, return 0 if the input string was partially
  7887. translated into writer, raise an exception and return -1 on error. */
  7888. static int
  7889. unicode_fast_translate(PyObject *input, PyObject *mapping,
  7890. _PyUnicodeWriter *writer, int ignore,
  7891. Py_ssize_t *input_pos)
  7892. {
  7893. Py_UCS1 ascii_table[128], ch, ch2;
  7894. Py_ssize_t len;
  7895. const Py_UCS1 *in, *end;
  7896. Py_UCS1 *out;
  7897. int res = 0;
  7898. len = PyUnicode_GET_LENGTH(input);
  7899. memset(ascii_table, 0xff, 128);
  7900. in = PyUnicode_1BYTE_DATA(input);
  7901. end = in + len;
  7902. assert(PyUnicode_IS_ASCII(writer->buffer));
  7903. assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
  7904. out = PyUnicode_1BYTE_DATA(writer->buffer);
  7905. for (; in < end; in++) {
  7906. ch = *in;
  7907. ch2 = ascii_table[ch];
  7908. if (ch2 == 0xff) {
  7909. int translate = unicode_fast_translate_lookup(mapping, ch,
  7910. ascii_table);
  7911. if (translate < 0)
  7912. return -1;
  7913. if (translate == 0)
  7914. goto exit;
  7915. ch2 = ascii_table[ch];
  7916. }
  7917. if (ch2 == 0xfe) {
  7918. if (ignore)
  7919. continue;
  7920. goto exit;
  7921. }
  7922. assert(ch2 < 128);
  7923. *out = ch2;
  7924. out++;
  7925. }
  7926. res = 1;
  7927. exit:
  7928. writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
  7929. *input_pos = in - PyUnicode_1BYTE_DATA(input);
  7930. return res;
  7931. }
  7932. static PyObject *
  7933. _PyUnicode_TranslateCharmap(PyObject *input,
  7934. PyObject *mapping,
  7935. const char *errors)
  7936. {
  7937. /* input object */
  7938. const void *data;
  7939. Py_ssize_t size, i;
  7940. int kind;
  7941. /* output buffer */
  7942. _PyUnicodeWriter writer;
  7943. /* error handler */
  7944. const char *reason = "character maps to <undefined>";
  7945. PyObject *errorHandler = NULL;
  7946. PyObject *exc = NULL;
  7947. int ignore;
  7948. int res;
  7949. if (mapping == NULL) {
  7950. PyErr_BadArgument();
  7951. return NULL;
  7952. }
  7953. data = PyUnicode_DATA(input);
  7954. kind = PyUnicode_KIND(input);
  7955. size = PyUnicode_GET_LENGTH(input);
  7956. if (size == 0)
  7957. return PyUnicode_FromObject(input);
  7958. /* allocate enough for a simple 1:1 translation without
  7959. replacements, if we need more, we'll resize */
  7960. _PyUnicodeWriter_Init(&writer);
  7961. if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
  7962. goto onError;
  7963. ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
  7964. if (PyUnicode_IS_ASCII(input)) {
  7965. res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
  7966. if (res < 0) {
  7967. _PyUnicodeWriter_Dealloc(&writer);
  7968. return NULL;
  7969. }
  7970. if (res == 1)
  7971. return _PyUnicodeWriter_Finish(&writer);
  7972. }
  7973. else {
  7974. i = 0;
  7975. }
  7976. while (i<size) {
  7977. /* try to encode it */
  7978. int translate;
  7979. PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
  7980. Py_ssize_t newpos;
  7981. /* startpos for collecting untranslatable chars */
  7982. Py_ssize_t collstart;
  7983. Py_ssize_t collend;
  7984. Py_UCS4 ch;
  7985. ch = PyUnicode_READ(kind, data, i);
  7986. translate = charmaptranslate_output(ch, mapping, &writer);
  7987. if (translate < 0)
  7988. goto onError;
  7989. if (translate != 0) {
  7990. /* it worked => adjust input pointer */
  7991. ++i;
  7992. continue;
  7993. }
  7994. /* untranslatable character */
  7995. collstart = i;
  7996. collend = i+1;
  7997. /* find all untranslatable characters */
  7998. while (collend < size) {
  7999. PyObject *x;
  8000. ch = PyUnicode_READ(kind, data, collend);
  8001. if (charmaptranslate_lookup(ch, mapping, &x))
  8002. goto onError;
  8003. Py_XDECREF(x);
  8004. if (x != Py_None)
  8005. break;
  8006. ++collend;
  8007. }
  8008. if (ignore) {
  8009. i = collend;
  8010. }
  8011. else {
  8012. repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
  8013. reason, input, &exc,
  8014. collstart, collend, &newpos);
  8015. if (repunicode == NULL)
  8016. goto onError;
  8017. if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
  8018. Py_DECREF(repunicode);
  8019. goto onError;
  8020. }
  8021. Py_DECREF(repunicode);
  8022. i = newpos;
  8023. }
  8024. }
  8025. Py_XDECREF(exc);
  8026. Py_XDECREF(errorHandler);
  8027. return _PyUnicodeWriter_Finish(&writer);
  8028. onError:
  8029. _PyUnicodeWriter_Dealloc(&writer);
  8030. Py_XDECREF(exc);
  8031. Py_XDECREF(errorHandler);
  8032. return NULL;
  8033. }
  8034. PyObject *
  8035. PyUnicode_Translate(PyObject *str,
  8036. PyObject *mapping,
  8037. const char *errors)
  8038. {
  8039. if (ensure_unicode(str) < 0)
  8040. return NULL;
  8041. return _PyUnicode_TranslateCharmap(str, mapping, errors);
  8042. }
  8043. PyObject *
  8044. _PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
  8045. {
  8046. if (!PyUnicode_Check(unicode)) {
  8047. PyErr_BadInternalCall();
  8048. return NULL;
  8049. }
  8050. if (PyUnicode_IS_ASCII(unicode)) {
  8051. /* If the string is already ASCII, just return the same string */
  8052. return Py_NewRef(unicode);
  8053. }
  8054. Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
  8055. PyObject *result = PyUnicode_New(len, 127);
  8056. if (result == NULL) {
  8057. return NULL;
  8058. }
  8059. Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
  8060. int kind = PyUnicode_KIND(unicode);
  8061. const void *data = PyUnicode_DATA(unicode);
  8062. Py_ssize_t i;
  8063. for (i = 0; i < len; ++i) {
  8064. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  8065. if (ch < 127) {
  8066. out[i] = ch;
  8067. }
  8068. else if (Py_UNICODE_ISSPACE(ch)) {
  8069. out[i] = ' ';
  8070. }
  8071. else {
  8072. int decimal = Py_UNICODE_TODECIMAL(ch);
  8073. if (decimal < 0) {
  8074. out[i] = '?';
  8075. out[i+1] = '\0';
  8076. _PyUnicode_LENGTH(result) = i + 1;
  8077. break;
  8078. }
  8079. out[i] = '0' + decimal;
  8080. }
  8081. }
  8082. assert(_PyUnicode_CheckConsistency(result, 1));
  8083. return result;
  8084. }
  8085. /* --- Helpers ------------------------------------------------------------ */
  8086. /* helper macro to fixup start/end slice values */
  8087. #define ADJUST_INDICES(start, end, len) \
  8088. if (end > len) \
  8089. end = len; \
  8090. else if (end < 0) { \
  8091. end += len; \
  8092. if (end < 0) \
  8093. end = 0; \
  8094. } \
  8095. if (start < 0) { \
  8096. start += len; \
  8097. if (start < 0) \
  8098. start = 0; \
  8099. }
  8100. static Py_ssize_t
  8101. any_find_slice(PyObject* s1, PyObject* s2,
  8102. Py_ssize_t start,
  8103. Py_ssize_t end,
  8104. int direction)
  8105. {
  8106. int kind1, kind2;
  8107. const void *buf1, *buf2;
  8108. Py_ssize_t len1, len2, result;
  8109. kind1 = PyUnicode_KIND(s1);
  8110. kind2 = PyUnicode_KIND(s2);
  8111. if (kind1 < kind2)
  8112. return -1;
  8113. len1 = PyUnicode_GET_LENGTH(s1);
  8114. len2 = PyUnicode_GET_LENGTH(s2);
  8115. ADJUST_INDICES(start, end, len1);
  8116. if (end - start < len2)
  8117. return -1;
  8118. buf1 = PyUnicode_DATA(s1);
  8119. buf2 = PyUnicode_DATA(s2);
  8120. if (len2 == 1) {
  8121. Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
  8122. result = findchar((const char *)buf1 + kind1*start,
  8123. kind1, end - start, ch, direction);
  8124. if (result == -1)
  8125. return -1;
  8126. else
  8127. return start + result;
  8128. }
  8129. if (kind2 != kind1) {
  8130. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  8131. if (!buf2)
  8132. return -2;
  8133. }
  8134. if (direction > 0) {
  8135. switch (kind1) {
  8136. case PyUnicode_1BYTE_KIND:
  8137. if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
  8138. result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
  8139. else
  8140. result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
  8141. break;
  8142. case PyUnicode_2BYTE_KIND:
  8143. result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
  8144. break;
  8145. case PyUnicode_4BYTE_KIND:
  8146. result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
  8147. break;
  8148. default:
  8149. Py_UNREACHABLE();
  8150. }
  8151. }
  8152. else {
  8153. switch (kind1) {
  8154. case PyUnicode_1BYTE_KIND:
  8155. if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
  8156. result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
  8157. else
  8158. result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
  8159. break;
  8160. case PyUnicode_2BYTE_KIND:
  8161. result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
  8162. break;
  8163. case PyUnicode_4BYTE_KIND:
  8164. result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
  8165. break;
  8166. default:
  8167. Py_UNREACHABLE();
  8168. }
  8169. }
  8170. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(s2)));
  8171. if (kind2 != kind1)
  8172. PyMem_Free((void *)buf2);
  8173. return result;
  8174. }
  8175. /* _PyUnicode_InsertThousandsGrouping() helper functions */
  8176. #include "stringlib/localeutil.h"
  8177. /**
  8178. * InsertThousandsGrouping:
  8179. * @writer: Unicode writer.
  8180. * @n_buffer: Number of characters in @buffer.
  8181. * @digits: Digits we're reading from. If count is non-NULL, this is unused.
  8182. * @d_pos: Start of digits string.
  8183. * @n_digits: The number of digits in the string, in which we want
  8184. * to put the grouping chars.
  8185. * @min_width: The minimum width of the digits in the output string.
  8186. * Output will be zero-padded on the left to fill.
  8187. * @grouping: see definition in localeconv().
  8188. * @thousands_sep: see definition in localeconv().
  8189. *
  8190. * There are 2 modes: counting and filling. If @writer is NULL,
  8191. * we are in counting mode, else filling mode.
  8192. * If counting, the required buffer size is returned.
  8193. * If filling, we know the buffer will be large enough, so we don't
  8194. * need to pass in the buffer size.
  8195. * Inserts thousand grouping characters (as defined by grouping and
  8196. * thousands_sep) into @writer.
  8197. *
  8198. * Return value: -1 on error, number of characters otherwise.
  8199. **/
  8200. Py_ssize_t
  8201. _PyUnicode_InsertThousandsGrouping(
  8202. _PyUnicodeWriter *writer,
  8203. Py_ssize_t n_buffer,
  8204. PyObject *digits,
  8205. Py_ssize_t d_pos,
  8206. Py_ssize_t n_digits,
  8207. Py_ssize_t min_width,
  8208. const char *grouping,
  8209. PyObject *thousands_sep,
  8210. Py_UCS4 *maxchar)
  8211. {
  8212. min_width = Py_MAX(0, min_width);
  8213. if (writer) {
  8214. assert(digits != NULL);
  8215. assert(maxchar == NULL);
  8216. }
  8217. else {
  8218. assert(digits == NULL);
  8219. assert(maxchar != NULL);
  8220. }
  8221. assert(0 <= d_pos);
  8222. assert(0 <= n_digits);
  8223. assert(grouping != NULL);
  8224. Py_ssize_t count = 0;
  8225. Py_ssize_t n_zeros;
  8226. int loop_broken = 0;
  8227. int use_separator = 0; /* First time through, don't append the
  8228. separator. They only go between
  8229. groups. */
  8230. Py_ssize_t buffer_pos;
  8231. Py_ssize_t digits_pos;
  8232. Py_ssize_t len;
  8233. Py_ssize_t n_chars;
  8234. Py_ssize_t remaining = n_digits; /* Number of chars remaining to
  8235. be looked at */
  8236. /* A generator that returns all of the grouping widths, until it
  8237. returns 0. */
  8238. GroupGenerator groupgen;
  8239. GroupGenerator_init(&groupgen, grouping);
  8240. const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
  8241. /* if digits are not grouped, thousands separator
  8242. should be an empty string */
  8243. assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
  8244. digits_pos = d_pos + n_digits;
  8245. if (writer) {
  8246. buffer_pos = writer->pos + n_buffer;
  8247. assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
  8248. assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
  8249. }
  8250. else {
  8251. buffer_pos = n_buffer;
  8252. }
  8253. if (!writer) {
  8254. *maxchar = 127;
  8255. }
  8256. while ((len = GroupGenerator_next(&groupgen)) > 0) {
  8257. len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1));
  8258. n_zeros = Py_MAX(0, len - remaining);
  8259. n_chars = Py_MAX(0, Py_MIN(remaining, len));
  8260. /* Use n_zero zero's and n_chars chars */
  8261. /* Count only, don't do anything. */
  8262. count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
  8263. /* Copy into the writer. */
  8264. InsertThousandsGrouping_fill(writer, &buffer_pos,
  8265. digits, &digits_pos,
  8266. n_chars, n_zeros,
  8267. use_separator ? thousands_sep : NULL,
  8268. thousands_sep_len, maxchar);
  8269. /* Use a separator next time. */
  8270. use_separator = 1;
  8271. remaining -= n_chars;
  8272. min_width -= len;
  8273. if (remaining <= 0 && min_width <= 0) {
  8274. loop_broken = 1;
  8275. break;
  8276. }
  8277. min_width -= thousands_sep_len;
  8278. }
  8279. if (!loop_broken) {
  8280. /* We left the loop without using a break statement. */
  8281. len = Py_MAX(Py_MAX(remaining, min_width), 1);
  8282. n_zeros = Py_MAX(0, len - remaining);
  8283. n_chars = Py_MAX(0, Py_MIN(remaining, len));
  8284. /* Use n_zero zero's and n_chars chars */
  8285. count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
  8286. /* Copy into the writer. */
  8287. InsertThousandsGrouping_fill(writer, &buffer_pos,
  8288. digits, &digits_pos,
  8289. n_chars, n_zeros,
  8290. use_separator ? thousands_sep : NULL,
  8291. thousands_sep_len, maxchar);
  8292. }
  8293. return count;
  8294. }
  8295. static Py_ssize_t
  8296. unicode_count_impl(PyObject *str,
  8297. PyObject *substr,
  8298. Py_ssize_t start,
  8299. Py_ssize_t end)
  8300. {
  8301. assert(PyUnicode_Check(str));
  8302. assert(PyUnicode_Check(substr));
  8303. Py_ssize_t result;
  8304. int kind1, kind2;
  8305. const void *buf1 = NULL, *buf2 = NULL;
  8306. Py_ssize_t len1, len2;
  8307. kind1 = PyUnicode_KIND(str);
  8308. kind2 = PyUnicode_KIND(substr);
  8309. if (kind1 < kind2)
  8310. return 0;
  8311. len1 = PyUnicode_GET_LENGTH(str);
  8312. len2 = PyUnicode_GET_LENGTH(substr);
  8313. ADJUST_INDICES(start, end, len1);
  8314. if (end - start < len2)
  8315. return 0;
  8316. buf1 = PyUnicode_DATA(str);
  8317. buf2 = PyUnicode_DATA(substr);
  8318. if (kind2 != kind1) {
  8319. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  8320. if (!buf2)
  8321. goto onError;
  8322. }
  8323. // We don't reuse `anylib_count` here because of the explicit casts.
  8324. switch (kind1) {
  8325. case PyUnicode_1BYTE_KIND:
  8326. result = ucs1lib_count(
  8327. ((const Py_UCS1*)buf1) + start, end - start,
  8328. buf2, len2, PY_SSIZE_T_MAX
  8329. );
  8330. break;
  8331. case PyUnicode_2BYTE_KIND:
  8332. result = ucs2lib_count(
  8333. ((const Py_UCS2*)buf1) + start, end - start,
  8334. buf2, len2, PY_SSIZE_T_MAX
  8335. );
  8336. break;
  8337. case PyUnicode_4BYTE_KIND:
  8338. result = ucs4lib_count(
  8339. ((const Py_UCS4*)buf1) + start, end - start,
  8340. buf2, len2, PY_SSIZE_T_MAX
  8341. );
  8342. break;
  8343. default:
  8344. Py_UNREACHABLE();
  8345. }
  8346. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
  8347. if (kind2 != kind1)
  8348. PyMem_Free((void *)buf2);
  8349. return result;
  8350. onError:
  8351. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
  8352. if (kind2 != kind1)
  8353. PyMem_Free((void *)buf2);
  8354. return -1;
  8355. }
  8356. Py_ssize_t
  8357. PyUnicode_Count(PyObject *str,
  8358. PyObject *substr,
  8359. Py_ssize_t start,
  8360. Py_ssize_t end)
  8361. {
  8362. if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
  8363. return -1;
  8364. return unicode_count_impl(str, substr, start, end);
  8365. }
  8366. Py_ssize_t
  8367. PyUnicode_Find(PyObject *str,
  8368. PyObject *substr,
  8369. Py_ssize_t start,
  8370. Py_ssize_t end,
  8371. int direction)
  8372. {
  8373. if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
  8374. return -2;
  8375. return any_find_slice(str, substr, start, end, direction);
  8376. }
  8377. Py_ssize_t
  8378. PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
  8379. Py_ssize_t start, Py_ssize_t end,
  8380. int direction)
  8381. {
  8382. int kind;
  8383. Py_ssize_t len, result;
  8384. len = PyUnicode_GET_LENGTH(str);
  8385. ADJUST_INDICES(start, end, len);
  8386. if (end - start < 1)
  8387. return -1;
  8388. kind = PyUnicode_KIND(str);
  8389. result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
  8390. kind, end-start, ch, direction);
  8391. if (result == -1)
  8392. return -1;
  8393. else
  8394. return start + result;
  8395. }
  8396. static int
  8397. tailmatch(PyObject *self,
  8398. PyObject *substring,
  8399. Py_ssize_t start,
  8400. Py_ssize_t end,
  8401. int direction)
  8402. {
  8403. int kind_self;
  8404. int kind_sub;
  8405. const void *data_self;
  8406. const void *data_sub;
  8407. Py_ssize_t offset;
  8408. Py_ssize_t i;
  8409. Py_ssize_t end_sub;
  8410. ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
  8411. end -= PyUnicode_GET_LENGTH(substring);
  8412. if (end < start)
  8413. return 0;
  8414. if (PyUnicode_GET_LENGTH(substring) == 0)
  8415. return 1;
  8416. kind_self = PyUnicode_KIND(self);
  8417. data_self = PyUnicode_DATA(self);
  8418. kind_sub = PyUnicode_KIND(substring);
  8419. data_sub = PyUnicode_DATA(substring);
  8420. end_sub = PyUnicode_GET_LENGTH(substring) - 1;
  8421. if (direction > 0)
  8422. offset = end;
  8423. else
  8424. offset = start;
  8425. if (PyUnicode_READ(kind_self, data_self, offset) ==
  8426. PyUnicode_READ(kind_sub, data_sub, 0) &&
  8427. PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
  8428. PyUnicode_READ(kind_sub, data_sub, end_sub)) {
  8429. /* If both are of the same kind, memcmp is sufficient */
  8430. if (kind_self == kind_sub) {
  8431. return ! memcmp((char *)data_self +
  8432. (offset * PyUnicode_KIND(substring)),
  8433. data_sub,
  8434. PyUnicode_GET_LENGTH(substring) *
  8435. PyUnicode_KIND(substring));
  8436. }
  8437. /* otherwise we have to compare each character by first accessing it */
  8438. else {
  8439. /* We do not need to compare 0 and len(substring)-1 because
  8440. the if statement above ensured already that they are equal
  8441. when we end up here. */
  8442. for (i = 1; i < end_sub; ++i) {
  8443. if (PyUnicode_READ(kind_self, data_self, offset + i) !=
  8444. PyUnicode_READ(kind_sub, data_sub, i))
  8445. return 0;
  8446. }
  8447. return 1;
  8448. }
  8449. }
  8450. return 0;
  8451. }
  8452. Py_ssize_t
  8453. PyUnicode_Tailmatch(PyObject *str,
  8454. PyObject *substr,
  8455. Py_ssize_t start,
  8456. Py_ssize_t end,
  8457. int direction)
  8458. {
  8459. if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
  8460. return -1;
  8461. return tailmatch(str, substr, start, end, direction);
  8462. }
  8463. static PyObject *
  8464. ascii_upper_or_lower(PyObject *self, int lower)
  8465. {
  8466. Py_ssize_t len = PyUnicode_GET_LENGTH(self);
  8467. const char *data = PyUnicode_DATA(self);
  8468. char *resdata;
  8469. PyObject *res;
  8470. res = PyUnicode_New(len, 127);
  8471. if (res == NULL)
  8472. return NULL;
  8473. resdata = PyUnicode_DATA(res);
  8474. if (lower)
  8475. _Py_bytes_lower(resdata, data, len);
  8476. else
  8477. _Py_bytes_upper(resdata, data, len);
  8478. return res;
  8479. }
  8480. static Py_UCS4
  8481. handle_capital_sigma(int kind, const void *data, Py_ssize_t length, Py_ssize_t i)
  8482. {
  8483. Py_ssize_t j;
  8484. int final_sigma;
  8485. Py_UCS4 c = 0; /* initialize to prevent gcc warning */
  8486. /* U+03A3 is in the Final_Sigma context when, it is found like this:
  8487. \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
  8488. where ! is a negation and \p{xxx} is a character with property xxx.
  8489. */
  8490. for (j = i - 1; j >= 0; j--) {
  8491. c = PyUnicode_READ(kind, data, j);
  8492. if (!_PyUnicode_IsCaseIgnorable(c))
  8493. break;
  8494. }
  8495. final_sigma = j >= 0 && _PyUnicode_IsCased(c);
  8496. if (final_sigma) {
  8497. for (j = i + 1; j < length; j++) {
  8498. c = PyUnicode_READ(kind, data, j);
  8499. if (!_PyUnicode_IsCaseIgnorable(c))
  8500. break;
  8501. }
  8502. final_sigma = j == length || !_PyUnicode_IsCased(c);
  8503. }
  8504. return (final_sigma) ? 0x3C2 : 0x3C3;
  8505. }
  8506. static int
  8507. lower_ucs4(int kind, const void *data, Py_ssize_t length, Py_ssize_t i,
  8508. Py_UCS4 c, Py_UCS4 *mapped)
  8509. {
  8510. /* Obscure special case. */
  8511. if (c == 0x3A3) {
  8512. mapped[0] = handle_capital_sigma(kind, data, length, i);
  8513. return 1;
  8514. }
  8515. return _PyUnicode_ToLowerFull(c, mapped);
  8516. }
  8517. static Py_ssize_t
  8518. do_capitalize(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8519. {
  8520. Py_ssize_t i, k = 0;
  8521. int n_res, j;
  8522. Py_UCS4 c, mapped[3];
  8523. c = PyUnicode_READ(kind, data, 0);
  8524. n_res = _PyUnicode_ToTitleFull(c, mapped);
  8525. for (j = 0; j < n_res; j++) {
  8526. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8527. res[k++] = mapped[j];
  8528. }
  8529. for (i = 1; i < length; i++) {
  8530. c = PyUnicode_READ(kind, data, i);
  8531. n_res = lower_ucs4(kind, data, length, i, c, mapped);
  8532. for (j = 0; j < n_res; j++) {
  8533. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8534. res[k++] = mapped[j];
  8535. }
  8536. }
  8537. return k;
  8538. }
  8539. static Py_ssize_t
  8540. do_swapcase(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
  8541. Py_ssize_t i, k = 0;
  8542. for (i = 0; i < length; i++) {
  8543. Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
  8544. int n_res, j;
  8545. if (Py_UNICODE_ISUPPER(c)) {
  8546. n_res = lower_ucs4(kind, data, length, i, c, mapped);
  8547. }
  8548. else if (Py_UNICODE_ISLOWER(c)) {
  8549. n_res = _PyUnicode_ToUpperFull(c, mapped);
  8550. }
  8551. else {
  8552. n_res = 1;
  8553. mapped[0] = c;
  8554. }
  8555. for (j = 0; j < n_res; j++) {
  8556. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8557. res[k++] = mapped[j];
  8558. }
  8559. }
  8560. return k;
  8561. }
  8562. static Py_ssize_t
  8563. do_upper_or_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res,
  8564. Py_UCS4 *maxchar, int lower)
  8565. {
  8566. Py_ssize_t i, k = 0;
  8567. for (i = 0; i < length; i++) {
  8568. Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
  8569. int n_res, j;
  8570. if (lower)
  8571. n_res = lower_ucs4(kind, data, length, i, c, mapped);
  8572. else
  8573. n_res = _PyUnicode_ToUpperFull(c, mapped);
  8574. for (j = 0; j < n_res; j++) {
  8575. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8576. res[k++] = mapped[j];
  8577. }
  8578. }
  8579. return k;
  8580. }
  8581. static Py_ssize_t
  8582. do_upper(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8583. {
  8584. return do_upper_or_lower(kind, data, length, res, maxchar, 0);
  8585. }
  8586. static Py_ssize_t
  8587. do_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8588. {
  8589. return do_upper_or_lower(kind, data, length, res, maxchar, 1);
  8590. }
  8591. static Py_ssize_t
  8592. do_casefold(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8593. {
  8594. Py_ssize_t i, k = 0;
  8595. for (i = 0; i < length; i++) {
  8596. Py_UCS4 c = PyUnicode_READ(kind, data, i);
  8597. Py_UCS4 mapped[3];
  8598. int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
  8599. for (j = 0; j < n_res; j++) {
  8600. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8601. res[k++] = mapped[j];
  8602. }
  8603. }
  8604. return k;
  8605. }
  8606. static Py_ssize_t
  8607. do_title(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8608. {
  8609. Py_ssize_t i, k = 0;
  8610. int previous_is_cased;
  8611. previous_is_cased = 0;
  8612. for (i = 0; i < length; i++) {
  8613. const Py_UCS4 c = PyUnicode_READ(kind, data, i);
  8614. Py_UCS4 mapped[3];
  8615. int n_res, j;
  8616. if (previous_is_cased)
  8617. n_res = lower_ucs4(kind, data, length, i, c, mapped);
  8618. else
  8619. n_res = _PyUnicode_ToTitleFull(c, mapped);
  8620. for (j = 0; j < n_res; j++) {
  8621. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8622. res[k++] = mapped[j];
  8623. }
  8624. previous_is_cased = _PyUnicode_IsCased(c);
  8625. }
  8626. return k;
  8627. }
  8628. static PyObject *
  8629. case_operation(PyObject *self,
  8630. Py_ssize_t (*perform)(int, const void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
  8631. {
  8632. PyObject *res = NULL;
  8633. Py_ssize_t length, newlength = 0;
  8634. int kind, outkind;
  8635. const void *data;
  8636. void *outdata;
  8637. Py_UCS4 maxchar = 0, *tmp, *tmpend;
  8638. kind = PyUnicode_KIND(self);
  8639. data = PyUnicode_DATA(self);
  8640. length = PyUnicode_GET_LENGTH(self);
  8641. if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
  8642. PyErr_SetString(PyExc_OverflowError, "string is too long");
  8643. return NULL;
  8644. }
  8645. tmp = PyMem_Malloc(sizeof(Py_UCS4) * 3 * length);
  8646. if (tmp == NULL)
  8647. return PyErr_NoMemory();
  8648. newlength = perform(kind, data, length, tmp, &maxchar);
  8649. res = PyUnicode_New(newlength, maxchar);
  8650. if (res == NULL)
  8651. goto leave;
  8652. tmpend = tmp + newlength;
  8653. outdata = PyUnicode_DATA(res);
  8654. outkind = PyUnicode_KIND(res);
  8655. switch (outkind) {
  8656. case PyUnicode_1BYTE_KIND:
  8657. _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
  8658. break;
  8659. case PyUnicode_2BYTE_KIND:
  8660. _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
  8661. break;
  8662. case PyUnicode_4BYTE_KIND:
  8663. memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
  8664. break;
  8665. default:
  8666. Py_UNREACHABLE();
  8667. }
  8668. leave:
  8669. PyMem_Free(tmp);
  8670. return res;
  8671. }
  8672. PyObject *
  8673. PyUnicode_Join(PyObject *separator, PyObject *seq)
  8674. {
  8675. PyObject *res;
  8676. PyObject *fseq;
  8677. Py_ssize_t seqlen;
  8678. PyObject **items;
  8679. fseq = PySequence_Fast(seq, "can only join an iterable");
  8680. if (fseq == NULL) {
  8681. return NULL;
  8682. }
  8683. /* NOTE: the following code can't call back into Python code,
  8684. * so we are sure that fseq won't be mutated.
  8685. */
  8686. items = PySequence_Fast_ITEMS(fseq);
  8687. seqlen = PySequence_Fast_GET_SIZE(fseq);
  8688. res = _PyUnicode_JoinArray(separator, items, seqlen);
  8689. Py_DECREF(fseq);
  8690. return res;
  8691. }
  8692. PyObject *
  8693. _PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
  8694. {
  8695. PyObject *res = NULL; /* the result */
  8696. PyObject *sep = NULL;
  8697. Py_ssize_t seplen;
  8698. PyObject *item;
  8699. Py_ssize_t sz, i, res_offset;
  8700. Py_UCS4 maxchar;
  8701. Py_UCS4 item_maxchar;
  8702. int use_memcpy;
  8703. unsigned char *res_data = NULL, *sep_data = NULL;
  8704. PyObject *last_obj;
  8705. int kind = 0;
  8706. /* If empty sequence, return u"". */
  8707. if (seqlen == 0) {
  8708. _Py_RETURN_UNICODE_EMPTY();
  8709. }
  8710. /* If singleton sequence with an exact Unicode, return that. */
  8711. last_obj = NULL;
  8712. if (seqlen == 1) {
  8713. if (PyUnicode_CheckExact(items[0])) {
  8714. res = items[0];
  8715. return Py_NewRef(res);
  8716. }
  8717. seplen = 0;
  8718. maxchar = 0;
  8719. }
  8720. else {
  8721. /* Set up sep and seplen */
  8722. if (separator == NULL) {
  8723. /* fall back to a blank space separator */
  8724. sep = PyUnicode_FromOrdinal(' ');
  8725. if (!sep)
  8726. goto onError;
  8727. seplen = 1;
  8728. maxchar = 32;
  8729. }
  8730. else {
  8731. if (!PyUnicode_Check(separator)) {
  8732. PyErr_Format(PyExc_TypeError,
  8733. "separator: expected str instance,"
  8734. " %.80s found",
  8735. Py_TYPE(separator)->tp_name);
  8736. goto onError;
  8737. }
  8738. sep = separator;
  8739. seplen = PyUnicode_GET_LENGTH(separator);
  8740. maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
  8741. /* inc refcount to keep this code path symmetric with the
  8742. above case of a blank separator */
  8743. Py_INCREF(sep);
  8744. }
  8745. last_obj = sep;
  8746. }
  8747. /* There are at least two things to join, or else we have a subclass
  8748. * of str in the sequence.
  8749. * Do a pre-pass to figure out the total amount of space we'll
  8750. * need (sz), and see whether all argument are strings.
  8751. */
  8752. sz = 0;
  8753. #ifdef Py_DEBUG
  8754. use_memcpy = 0;
  8755. #else
  8756. use_memcpy = 1;
  8757. #endif
  8758. for (i = 0; i < seqlen; i++) {
  8759. size_t add_sz;
  8760. item = items[i];
  8761. if (!PyUnicode_Check(item)) {
  8762. PyErr_Format(PyExc_TypeError,
  8763. "sequence item %zd: expected str instance,"
  8764. " %.80s found",
  8765. i, Py_TYPE(item)->tp_name);
  8766. goto onError;
  8767. }
  8768. add_sz = PyUnicode_GET_LENGTH(item);
  8769. item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
  8770. maxchar = Py_MAX(maxchar, item_maxchar);
  8771. if (i != 0) {
  8772. add_sz += seplen;
  8773. }
  8774. if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
  8775. PyErr_SetString(PyExc_OverflowError,
  8776. "join() result is too long for a Python string");
  8777. goto onError;
  8778. }
  8779. sz += add_sz;
  8780. if (use_memcpy && last_obj != NULL) {
  8781. if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
  8782. use_memcpy = 0;
  8783. }
  8784. last_obj = item;
  8785. }
  8786. res = PyUnicode_New(sz, maxchar);
  8787. if (res == NULL)
  8788. goto onError;
  8789. /* Catenate everything. */
  8790. #ifdef Py_DEBUG
  8791. use_memcpy = 0;
  8792. #else
  8793. if (use_memcpy) {
  8794. res_data = PyUnicode_1BYTE_DATA(res);
  8795. kind = PyUnicode_KIND(res);
  8796. if (seplen != 0)
  8797. sep_data = PyUnicode_1BYTE_DATA(sep);
  8798. }
  8799. #endif
  8800. if (use_memcpy) {
  8801. for (i = 0; i < seqlen; ++i) {
  8802. Py_ssize_t itemlen;
  8803. item = items[i];
  8804. /* Copy item, and maybe the separator. */
  8805. if (i && seplen != 0) {
  8806. memcpy(res_data,
  8807. sep_data,
  8808. kind * seplen);
  8809. res_data += kind * seplen;
  8810. }
  8811. itemlen = PyUnicode_GET_LENGTH(item);
  8812. if (itemlen != 0) {
  8813. memcpy(res_data,
  8814. PyUnicode_DATA(item),
  8815. kind * itemlen);
  8816. res_data += kind * itemlen;
  8817. }
  8818. }
  8819. assert(res_data == PyUnicode_1BYTE_DATA(res)
  8820. + kind * PyUnicode_GET_LENGTH(res));
  8821. }
  8822. else {
  8823. for (i = 0, res_offset = 0; i < seqlen; ++i) {
  8824. Py_ssize_t itemlen;
  8825. item = items[i];
  8826. /* Copy item, and maybe the separator. */
  8827. if (i && seplen != 0) {
  8828. _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
  8829. res_offset += seplen;
  8830. }
  8831. itemlen = PyUnicode_GET_LENGTH(item);
  8832. if (itemlen != 0) {
  8833. _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
  8834. res_offset += itemlen;
  8835. }
  8836. }
  8837. assert(res_offset == PyUnicode_GET_LENGTH(res));
  8838. }
  8839. Py_XDECREF(sep);
  8840. assert(_PyUnicode_CheckConsistency(res, 1));
  8841. return res;
  8842. onError:
  8843. Py_XDECREF(sep);
  8844. Py_XDECREF(res);
  8845. return NULL;
  8846. }
  8847. void
  8848. _PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
  8849. Py_UCS4 fill_char)
  8850. {
  8851. const int kind = PyUnicode_KIND(unicode);
  8852. void *data = PyUnicode_DATA(unicode);
  8853. assert(unicode_modifiable(unicode));
  8854. assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
  8855. assert(start >= 0);
  8856. assert(start + length <= PyUnicode_GET_LENGTH(unicode));
  8857. unicode_fill(kind, data, fill_char, start, length);
  8858. }
  8859. Py_ssize_t
  8860. PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
  8861. Py_UCS4 fill_char)
  8862. {
  8863. Py_ssize_t maxlen;
  8864. if (!PyUnicode_Check(unicode)) {
  8865. PyErr_BadInternalCall();
  8866. return -1;
  8867. }
  8868. if (unicode_check_modifiable(unicode))
  8869. return -1;
  8870. if (start < 0) {
  8871. PyErr_SetString(PyExc_IndexError, "string index out of range");
  8872. return -1;
  8873. }
  8874. if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
  8875. PyErr_SetString(PyExc_ValueError,
  8876. "fill character is bigger than "
  8877. "the string maximum character");
  8878. return -1;
  8879. }
  8880. maxlen = PyUnicode_GET_LENGTH(unicode) - start;
  8881. length = Py_MIN(maxlen, length);
  8882. if (length <= 0)
  8883. return 0;
  8884. _PyUnicode_FastFill(unicode, start, length, fill_char);
  8885. return length;
  8886. }
  8887. static PyObject *
  8888. pad(PyObject *self,
  8889. Py_ssize_t left,
  8890. Py_ssize_t right,
  8891. Py_UCS4 fill)
  8892. {
  8893. PyObject *u;
  8894. Py_UCS4 maxchar;
  8895. int kind;
  8896. void *data;
  8897. if (left < 0)
  8898. left = 0;
  8899. if (right < 0)
  8900. right = 0;
  8901. if (left == 0 && right == 0)
  8902. return unicode_result_unchanged(self);
  8903. if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
  8904. right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
  8905. PyErr_SetString(PyExc_OverflowError, "padded string is too long");
  8906. return NULL;
  8907. }
  8908. maxchar = PyUnicode_MAX_CHAR_VALUE(self);
  8909. maxchar = Py_MAX(maxchar, fill);
  8910. u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
  8911. if (!u)
  8912. return NULL;
  8913. kind = PyUnicode_KIND(u);
  8914. data = PyUnicode_DATA(u);
  8915. if (left)
  8916. unicode_fill(kind, data, fill, 0, left);
  8917. if (right)
  8918. unicode_fill(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
  8919. _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
  8920. assert(_PyUnicode_CheckConsistency(u, 1));
  8921. return u;
  8922. }
  8923. PyObject *
  8924. PyUnicode_Splitlines(PyObject *string, int keepends)
  8925. {
  8926. PyObject *list;
  8927. if (ensure_unicode(string) < 0)
  8928. return NULL;
  8929. switch (PyUnicode_KIND(string)) {
  8930. case PyUnicode_1BYTE_KIND:
  8931. if (PyUnicode_IS_ASCII(string))
  8932. list = asciilib_splitlines(
  8933. string, PyUnicode_1BYTE_DATA(string),
  8934. PyUnicode_GET_LENGTH(string), keepends);
  8935. else
  8936. list = ucs1lib_splitlines(
  8937. string, PyUnicode_1BYTE_DATA(string),
  8938. PyUnicode_GET_LENGTH(string), keepends);
  8939. break;
  8940. case PyUnicode_2BYTE_KIND:
  8941. list = ucs2lib_splitlines(
  8942. string, PyUnicode_2BYTE_DATA(string),
  8943. PyUnicode_GET_LENGTH(string), keepends);
  8944. break;
  8945. case PyUnicode_4BYTE_KIND:
  8946. list = ucs4lib_splitlines(
  8947. string, PyUnicode_4BYTE_DATA(string),
  8948. PyUnicode_GET_LENGTH(string), keepends);
  8949. break;
  8950. default:
  8951. Py_UNREACHABLE();
  8952. }
  8953. return list;
  8954. }
  8955. static PyObject *
  8956. split(PyObject *self,
  8957. PyObject *substring,
  8958. Py_ssize_t maxcount)
  8959. {
  8960. int kind1, kind2;
  8961. const void *buf1, *buf2;
  8962. Py_ssize_t len1, len2;
  8963. PyObject* out;
  8964. len1 = PyUnicode_GET_LENGTH(self);
  8965. kind1 = PyUnicode_KIND(self);
  8966. if (substring == NULL) {
  8967. if (maxcount < 0) {
  8968. maxcount = (len1 - 1) / 2 + 1;
  8969. }
  8970. switch (kind1) {
  8971. case PyUnicode_1BYTE_KIND:
  8972. if (PyUnicode_IS_ASCII(self))
  8973. return asciilib_split_whitespace(
  8974. self, PyUnicode_1BYTE_DATA(self),
  8975. len1, maxcount
  8976. );
  8977. else
  8978. return ucs1lib_split_whitespace(
  8979. self, PyUnicode_1BYTE_DATA(self),
  8980. len1, maxcount
  8981. );
  8982. case PyUnicode_2BYTE_KIND:
  8983. return ucs2lib_split_whitespace(
  8984. self, PyUnicode_2BYTE_DATA(self),
  8985. len1, maxcount
  8986. );
  8987. case PyUnicode_4BYTE_KIND:
  8988. return ucs4lib_split_whitespace(
  8989. self, PyUnicode_4BYTE_DATA(self),
  8990. len1, maxcount
  8991. );
  8992. default:
  8993. Py_UNREACHABLE();
  8994. }
  8995. }
  8996. kind2 = PyUnicode_KIND(substring);
  8997. len2 = PyUnicode_GET_LENGTH(substring);
  8998. if (maxcount < 0) {
  8999. // if len2 == 0, it will raise ValueError.
  9000. maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
  9001. // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
  9002. maxcount = maxcount < 0 ? len1 : maxcount;
  9003. }
  9004. if (kind1 < kind2 || len1 < len2) {
  9005. out = PyList_New(1);
  9006. if (out == NULL)
  9007. return NULL;
  9008. PyList_SET_ITEM(out, 0, Py_NewRef(self));
  9009. return out;
  9010. }
  9011. buf1 = PyUnicode_DATA(self);
  9012. buf2 = PyUnicode_DATA(substring);
  9013. if (kind2 != kind1) {
  9014. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  9015. if (!buf2)
  9016. return NULL;
  9017. }
  9018. switch (kind1) {
  9019. case PyUnicode_1BYTE_KIND:
  9020. if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
  9021. out = asciilib_split(
  9022. self, buf1, len1, buf2, len2, maxcount);
  9023. else
  9024. out = ucs1lib_split(
  9025. self, buf1, len1, buf2, len2, maxcount);
  9026. break;
  9027. case PyUnicode_2BYTE_KIND:
  9028. out = ucs2lib_split(
  9029. self, buf1, len1, buf2, len2, maxcount);
  9030. break;
  9031. case PyUnicode_4BYTE_KIND:
  9032. out = ucs4lib_split(
  9033. self, buf1, len1, buf2, len2, maxcount);
  9034. break;
  9035. default:
  9036. out = NULL;
  9037. }
  9038. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
  9039. if (kind2 != kind1)
  9040. PyMem_Free((void *)buf2);
  9041. return out;
  9042. }
  9043. static PyObject *
  9044. rsplit(PyObject *self,
  9045. PyObject *substring,
  9046. Py_ssize_t maxcount)
  9047. {
  9048. int kind1, kind2;
  9049. const void *buf1, *buf2;
  9050. Py_ssize_t len1, len2;
  9051. PyObject* out;
  9052. len1 = PyUnicode_GET_LENGTH(self);
  9053. kind1 = PyUnicode_KIND(self);
  9054. if (substring == NULL) {
  9055. if (maxcount < 0) {
  9056. maxcount = (len1 - 1) / 2 + 1;
  9057. }
  9058. switch (kind1) {
  9059. case PyUnicode_1BYTE_KIND:
  9060. if (PyUnicode_IS_ASCII(self))
  9061. return asciilib_rsplit_whitespace(
  9062. self, PyUnicode_1BYTE_DATA(self),
  9063. len1, maxcount
  9064. );
  9065. else
  9066. return ucs1lib_rsplit_whitespace(
  9067. self, PyUnicode_1BYTE_DATA(self),
  9068. len1, maxcount
  9069. );
  9070. case PyUnicode_2BYTE_KIND:
  9071. return ucs2lib_rsplit_whitespace(
  9072. self, PyUnicode_2BYTE_DATA(self),
  9073. len1, maxcount
  9074. );
  9075. case PyUnicode_4BYTE_KIND:
  9076. return ucs4lib_rsplit_whitespace(
  9077. self, PyUnicode_4BYTE_DATA(self),
  9078. len1, maxcount
  9079. );
  9080. default:
  9081. Py_UNREACHABLE();
  9082. }
  9083. }
  9084. kind2 = PyUnicode_KIND(substring);
  9085. len2 = PyUnicode_GET_LENGTH(substring);
  9086. if (maxcount < 0) {
  9087. // if len2 == 0, it will raise ValueError.
  9088. maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
  9089. // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
  9090. maxcount = maxcount < 0 ? len1 : maxcount;
  9091. }
  9092. if (kind1 < kind2 || len1 < len2) {
  9093. out = PyList_New(1);
  9094. if (out == NULL)
  9095. return NULL;
  9096. PyList_SET_ITEM(out, 0, Py_NewRef(self));
  9097. return out;
  9098. }
  9099. buf1 = PyUnicode_DATA(self);
  9100. buf2 = PyUnicode_DATA(substring);
  9101. if (kind2 != kind1) {
  9102. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  9103. if (!buf2)
  9104. return NULL;
  9105. }
  9106. switch (kind1) {
  9107. case PyUnicode_1BYTE_KIND:
  9108. if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
  9109. out = asciilib_rsplit(
  9110. self, buf1, len1, buf2, len2, maxcount);
  9111. else
  9112. out = ucs1lib_rsplit(
  9113. self, buf1, len1, buf2, len2, maxcount);
  9114. break;
  9115. case PyUnicode_2BYTE_KIND:
  9116. out = ucs2lib_rsplit(
  9117. self, buf1, len1, buf2, len2, maxcount);
  9118. break;
  9119. case PyUnicode_4BYTE_KIND:
  9120. out = ucs4lib_rsplit(
  9121. self, buf1, len1, buf2, len2, maxcount);
  9122. break;
  9123. default:
  9124. out = NULL;
  9125. }
  9126. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
  9127. if (kind2 != kind1)
  9128. PyMem_Free((void *)buf2);
  9129. return out;
  9130. }
  9131. static Py_ssize_t
  9132. anylib_find(int kind, PyObject *str1, const void *buf1, Py_ssize_t len1,
  9133. PyObject *str2, const void *buf2, Py_ssize_t len2, Py_ssize_t offset)
  9134. {
  9135. switch (kind) {
  9136. case PyUnicode_1BYTE_KIND:
  9137. if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
  9138. return asciilib_find(buf1, len1, buf2, len2, offset);
  9139. else
  9140. return ucs1lib_find(buf1, len1, buf2, len2, offset);
  9141. case PyUnicode_2BYTE_KIND:
  9142. return ucs2lib_find(buf1, len1, buf2, len2, offset);
  9143. case PyUnicode_4BYTE_KIND:
  9144. return ucs4lib_find(buf1, len1, buf2, len2, offset);
  9145. }
  9146. Py_UNREACHABLE();
  9147. }
  9148. static Py_ssize_t
  9149. anylib_count(int kind, PyObject *sstr, const void* sbuf, Py_ssize_t slen,
  9150. PyObject *str1, const void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
  9151. {
  9152. switch (kind) {
  9153. case PyUnicode_1BYTE_KIND:
  9154. return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
  9155. case PyUnicode_2BYTE_KIND:
  9156. return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
  9157. case PyUnicode_4BYTE_KIND:
  9158. return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
  9159. }
  9160. Py_UNREACHABLE();
  9161. }
  9162. static void
  9163. replace_1char_inplace(PyObject *u, Py_ssize_t pos,
  9164. Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
  9165. {
  9166. int kind = PyUnicode_KIND(u);
  9167. void *data = PyUnicode_DATA(u);
  9168. Py_ssize_t len = PyUnicode_GET_LENGTH(u);
  9169. if (kind == PyUnicode_1BYTE_KIND) {
  9170. ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
  9171. (Py_UCS1 *)data + len,
  9172. u1, u2, maxcount);
  9173. }
  9174. else if (kind == PyUnicode_2BYTE_KIND) {
  9175. ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
  9176. (Py_UCS2 *)data + len,
  9177. u1, u2, maxcount);
  9178. }
  9179. else {
  9180. assert(kind == PyUnicode_4BYTE_KIND);
  9181. ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
  9182. (Py_UCS4 *)data + len,
  9183. u1, u2, maxcount);
  9184. }
  9185. }
  9186. static PyObject *
  9187. replace(PyObject *self, PyObject *str1,
  9188. PyObject *str2, Py_ssize_t maxcount)
  9189. {
  9190. PyObject *u;
  9191. const char *sbuf = PyUnicode_DATA(self);
  9192. const void *buf1 = PyUnicode_DATA(str1);
  9193. const void *buf2 = PyUnicode_DATA(str2);
  9194. int srelease = 0, release1 = 0, release2 = 0;
  9195. int skind = PyUnicode_KIND(self);
  9196. int kind1 = PyUnicode_KIND(str1);
  9197. int kind2 = PyUnicode_KIND(str2);
  9198. Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
  9199. Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
  9200. Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
  9201. int mayshrink;
  9202. Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
  9203. if (slen < len1)
  9204. goto nothing;
  9205. if (maxcount < 0)
  9206. maxcount = PY_SSIZE_T_MAX;
  9207. else if (maxcount == 0)
  9208. goto nothing;
  9209. if (str1 == str2)
  9210. goto nothing;
  9211. maxchar = PyUnicode_MAX_CHAR_VALUE(self);
  9212. maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
  9213. if (maxchar < maxchar_str1)
  9214. /* substring too wide to be present */
  9215. goto nothing;
  9216. maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
  9217. /* Replacing str1 with str2 may cause a maxchar reduction in the
  9218. result string. */
  9219. mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
  9220. maxchar = Py_MAX(maxchar, maxchar_str2);
  9221. if (len1 == len2) {
  9222. /* same length */
  9223. if (len1 == 0)
  9224. goto nothing;
  9225. if (len1 == 1) {
  9226. /* replace characters */
  9227. Py_UCS4 u1, u2;
  9228. Py_ssize_t pos;
  9229. u1 = PyUnicode_READ(kind1, buf1, 0);
  9230. pos = findchar(sbuf, skind, slen, u1, 1);
  9231. if (pos < 0)
  9232. goto nothing;
  9233. u2 = PyUnicode_READ(kind2, buf2, 0);
  9234. u = PyUnicode_New(slen, maxchar);
  9235. if (!u)
  9236. goto error;
  9237. _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
  9238. replace_1char_inplace(u, pos, u1, u2, maxcount);
  9239. }
  9240. else {
  9241. int rkind = skind;
  9242. char *res;
  9243. Py_ssize_t i;
  9244. if (kind1 < rkind) {
  9245. /* widen substring */
  9246. buf1 = unicode_askind(kind1, buf1, len1, rkind);
  9247. if (!buf1) goto error;
  9248. release1 = 1;
  9249. }
  9250. i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
  9251. if (i < 0)
  9252. goto nothing;
  9253. if (rkind > kind2) {
  9254. /* widen replacement */
  9255. buf2 = unicode_askind(kind2, buf2, len2, rkind);
  9256. if (!buf2) goto error;
  9257. release2 = 1;
  9258. }
  9259. else if (rkind < kind2) {
  9260. /* widen self and buf1 */
  9261. rkind = kind2;
  9262. if (release1) {
  9263. assert(buf1 != PyUnicode_DATA(str1));
  9264. PyMem_Free((void *)buf1);
  9265. buf1 = PyUnicode_DATA(str1);
  9266. release1 = 0;
  9267. }
  9268. sbuf = unicode_askind(skind, sbuf, slen, rkind);
  9269. if (!sbuf) goto error;
  9270. srelease = 1;
  9271. buf1 = unicode_askind(kind1, buf1, len1, rkind);
  9272. if (!buf1) goto error;
  9273. release1 = 1;
  9274. }
  9275. u = PyUnicode_New(slen, maxchar);
  9276. if (!u)
  9277. goto error;
  9278. assert(PyUnicode_KIND(u) == rkind);
  9279. res = PyUnicode_DATA(u);
  9280. memcpy(res, sbuf, rkind * slen);
  9281. /* change everything in-place, starting with this one */
  9282. memcpy(res + rkind * i,
  9283. buf2,
  9284. rkind * len2);
  9285. i += len1;
  9286. while ( --maxcount > 0) {
  9287. i = anylib_find(rkind, self,
  9288. sbuf+rkind*i, slen-i,
  9289. str1, buf1, len1, i);
  9290. if (i == -1)
  9291. break;
  9292. memcpy(res + rkind * i,
  9293. buf2,
  9294. rkind * len2);
  9295. i += len1;
  9296. }
  9297. }
  9298. }
  9299. else {
  9300. Py_ssize_t n, i, j, ires;
  9301. Py_ssize_t new_size;
  9302. int rkind = skind;
  9303. char *res;
  9304. if (kind1 < rkind) {
  9305. /* widen substring */
  9306. buf1 = unicode_askind(kind1, buf1, len1, rkind);
  9307. if (!buf1) goto error;
  9308. release1 = 1;
  9309. }
  9310. n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
  9311. if (n == 0)
  9312. goto nothing;
  9313. if (kind2 < rkind) {
  9314. /* widen replacement */
  9315. buf2 = unicode_askind(kind2, buf2, len2, rkind);
  9316. if (!buf2) goto error;
  9317. release2 = 1;
  9318. }
  9319. else if (kind2 > rkind) {
  9320. /* widen self and buf1 */
  9321. rkind = kind2;
  9322. sbuf = unicode_askind(skind, sbuf, slen, rkind);
  9323. if (!sbuf) goto error;
  9324. srelease = 1;
  9325. if (release1) {
  9326. assert(buf1 != PyUnicode_DATA(str1));
  9327. PyMem_Free((void *)buf1);
  9328. buf1 = PyUnicode_DATA(str1);
  9329. release1 = 0;
  9330. }
  9331. buf1 = unicode_askind(kind1, buf1, len1, rkind);
  9332. if (!buf1) goto error;
  9333. release1 = 1;
  9334. }
  9335. /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
  9336. PyUnicode_GET_LENGTH(str1)); */
  9337. if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
  9338. PyErr_SetString(PyExc_OverflowError,
  9339. "replace string is too long");
  9340. goto error;
  9341. }
  9342. new_size = slen + n * (len2 - len1);
  9343. if (new_size == 0) {
  9344. u = unicode_new_empty();
  9345. goto done;
  9346. }
  9347. if (new_size > (PY_SSIZE_T_MAX / rkind)) {
  9348. PyErr_SetString(PyExc_OverflowError,
  9349. "replace string is too long");
  9350. goto error;
  9351. }
  9352. u = PyUnicode_New(new_size, maxchar);
  9353. if (!u)
  9354. goto error;
  9355. assert(PyUnicode_KIND(u) == rkind);
  9356. res = PyUnicode_DATA(u);
  9357. ires = i = 0;
  9358. if (len1 > 0) {
  9359. while (n-- > 0) {
  9360. /* look for next match */
  9361. j = anylib_find(rkind, self,
  9362. sbuf + rkind * i, slen-i,
  9363. str1, buf1, len1, i);
  9364. if (j == -1)
  9365. break;
  9366. else if (j > i) {
  9367. /* copy unchanged part [i:j] */
  9368. memcpy(res + rkind * ires,
  9369. sbuf + rkind * i,
  9370. rkind * (j-i));
  9371. ires += j - i;
  9372. }
  9373. /* copy substitution string */
  9374. if (len2 > 0) {
  9375. memcpy(res + rkind * ires,
  9376. buf2,
  9377. rkind * len2);
  9378. ires += len2;
  9379. }
  9380. i = j + len1;
  9381. }
  9382. if (i < slen)
  9383. /* copy tail [i:] */
  9384. memcpy(res + rkind * ires,
  9385. sbuf + rkind * i,
  9386. rkind * (slen-i));
  9387. }
  9388. else {
  9389. /* interleave */
  9390. while (n > 0) {
  9391. memcpy(res + rkind * ires,
  9392. buf2,
  9393. rkind * len2);
  9394. ires += len2;
  9395. if (--n <= 0)
  9396. break;
  9397. memcpy(res + rkind * ires,
  9398. sbuf + rkind * i,
  9399. rkind);
  9400. ires++;
  9401. i++;
  9402. }
  9403. memcpy(res + rkind * ires,
  9404. sbuf + rkind * i,
  9405. rkind * (slen-i));
  9406. }
  9407. }
  9408. if (mayshrink) {
  9409. unicode_adjust_maxchar(&u);
  9410. if (u == NULL)
  9411. goto error;
  9412. }
  9413. done:
  9414. assert(srelease == (sbuf != PyUnicode_DATA(self)));
  9415. assert(release1 == (buf1 != PyUnicode_DATA(str1)));
  9416. assert(release2 == (buf2 != PyUnicode_DATA(str2)));
  9417. if (srelease)
  9418. PyMem_Free((void *)sbuf);
  9419. if (release1)
  9420. PyMem_Free((void *)buf1);
  9421. if (release2)
  9422. PyMem_Free((void *)buf2);
  9423. assert(_PyUnicode_CheckConsistency(u, 1));
  9424. return u;
  9425. nothing:
  9426. /* nothing to replace; return original string (when possible) */
  9427. assert(srelease == (sbuf != PyUnicode_DATA(self)));
  9428. assert(release1 == (buf1 != PyUnicode_DATA(str1)));
  9429. assert(release2 == (buf2 != PyUnicode_DATA(str2)));
  9430. if (srelease)
  9431. PyMem_Free((void *)sbuf);
  9432. if (release1)
  9433. PyMem_Free((void *)buf1);
  9434. if (release2)
  9435. PyMem_Free((void *)buf2);
  9436. return unicode_result_unchanged(self);
  9437. error:
  9438. assert(srelease == (sbuf != PyUnicode_DATA(self)));
  9439. assert(release1 == (buf1 != PyUnicode_DATA(str1)));
  9440. assert(release2 == (buf2 != PyUnicode_DATA(str2)));
  9441. if (srelease)
  9442. PyMem_Free((void *)sbuf);
  9443. if (release1)
  9444. PyMem_Free((void *)buf1);
  9445. if (release2)
  9446. PyMem_Free((void *)buf2);
  9447. return NULL;
  9448. }
  9449. /* --- Unicode Object Methods --------------------------------------------- */
  9450. /*[clinic input]
  9451. str.title as unicode_title
  9452. Return a version of the string where each word is titlecased.
  9453. More specifically, words start with uppercased characters and all remaining
  9454. cased characters have lower case.
  9455. [clinic start generated code]*/
  9456. static PyObject *
  9457. unicode_title_impl(PyObject *self)
  9458. /*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
  9459. {
  9460. return case_operation(self, do_title);
  9461. }
  9462. /*[clinic input]
  9463. str.capitalize as unicode_capitalize
  9464. Return a capitalized version of the string.
  9465. More specifically, make the first character have upper case and the rest lower
  9466. case.
  9467. [clinic start generated code]*/
  9468. static PyObject *
  9469. unicode_capitalize_impl(PyObject *self)
  9470. /*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
  9471. {
  9472. if (PyUnicode_GET_LENGTH(self) == 0)
  9473. return unicode_result_unchanged(self);
  9474. return case_operation(self, do_capitalize);
  9475. }
  9476. /*[clinic input]
  9477. str.casefold as unicode_casefold
  9478. Return a version of the string suitable for caseless comparisons.
  9479. [clinic start generated code]*/
  9480. static PyObject *
  9481. unicode_casefold_impl(PyObject *self)
  9482. /*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
  9483. {
  9484. if (PyUnicode_IS_ASCII(self))
  9485. return ascii_upper_or_lower(self, 1);
  9486. return case_operation(self, do_casefold);
  9487. }
  9488. /* Argument converter. Accepts a single Unicode character. */
  9489. static int
  9490. convert_uc(PyObject *obj, void *addr)
  9491. {
  9492. Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
  9493. if (!PyUnicode_Check(obj)) {
  9494. PyErr_Format(PyExc_TypeError,
  9495. "The fill character must be a unicode character, "
  9496. "not %.100s", Py_TYPE(obj)->tp_name);
  9497. return 0;
  9498. }
  9499. if (PyUnicode_GET_LENGTH(obj) != 1) {
  9500. PyErr_SetString(PyExc_TypeError,
  9501. "The fill character must be exactly one character long");
  9502. return 0;
  9503. }
  9504. *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
  9505. return 1;
  9506. }
  9507. /*[clinic input]
  9508. str.center as unicode_center
  9509. width: Py_ssize_t
  9510. fillchar: Py_UCS4 = ' '
  9511. /
  9512. Return a centered string of length width.
  9513. Padding is done using the specified fill character (default is a space).
  9514. [clinic start generated code]*/
  9515. static PyObject *
  9516. unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
  9517. /*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
  9518. {
  9519. Py_ssize_t marg, left;
  9520. if (PyUnicode_GET_LENGTH(self) >= width)
  9521. return unicode_result_unchanged(self);
  9522. marg = width - PyUnicode_GET_LENGTH(self);
  9523. left = marg / 2 + (marg & width & 1);
  9524. return pad(self, left, marg - left, fillchar);
  9525. }
  9526. /* This function assumes that str1 and str2 are readied by the caller. */
  9527. static int
  9528. unicode_compare(PyObject *str1, PyObject *str2)
  9529. {
  9530. #define COMPARE(TYPE1, TYPE2) \
  9531. do { \
  9532. TYPE1* p1 = (TYPE1 *)data1; \
  9533. TYPE2* p2 = (TYPE2 *)data2; \
  9534. TYPE1* end = p1 + len; \
  9535. Py_UCS4 c1, c2; \
  9536. for (; p1 != end; p1++, p2++) { \
  9537. c1 = *p1; \
  9538. c2 = *p2; \
  9539. if (c1 != c2) \
  9540. return (c1 < c2) ? -1 : 1; \
  9541. } \
  9542. } \
  9543. while (0)
  9544. int kind1, kind2;
  9545. const void *data1, *data2;
  9546. Py_ssize_t len1, len2, len;
  9547. kind1 = PyUnicode_KIND(str1);
  9548. kind2 = PyUnicode_KIND(str2);
  9549. data1 = PyUnicode_DATA(str1);
  9550. data2 = PyUnicode_DATA(str2);
  9551. len1 = PyUnicode_GET_LENGTH(str1);
  9552. len2 = PyUnicode_GET_LENGTH(str2);
  9553. len = Py_MIN(len1, len2);
  9554. switch(kind1) {
  9555. case PyUnicode_1BYTE_KIND:
  9556. {
  9557. switch(kind2) {
  9558. case PyUnicode_1BYTE_KIND:
  9559. {
  9560. int cmp = memcmp(data1, data2, len);
  9561. /* normalize result of memcmp() into the range [-1; 1] */
  9562. if (cmp < 0)
  9563. return -1;
  9564. if (cmp > 0)
  9565. return 1;
  9566. break;
  9567. }
  9568. case PyUnicode_2BYTE_KIND:
  9569. COMPARE(Py_UCS1, Py_UCS2);
  9570. break;
  9571. case PyUnicode_4BYTE_KIND:
  9572. COMPARE(Py_UCS1, Py_UCS4);
  9573. break;
  9574. default:
  9575. Py_UNREACHABLE();
  9576. }
  9577. break;
  9578. }
  9579. case PyUnicode_2BYTE_KIND:
  9580. {
  9581. switch(kind2) {
  9582. case PyUnicode_1BYTE_KIND:
  9583. COMPARE(Py_UCS2, Py_UCS1);
  9584. break;
  9585. case PyUnicode_2BYTE_KIND:
  9586. {
  9587. COMPARE(Py_UCS2, Py_UCS2);
  9588. break;
  9589. }
  9590. case PyUnicode_4BYTE_KIND:
  9591. COMPARE(Py_UCS2, Py_UCS4);
  9592. break;
  9593. default:
  9594. Py_UNREACHABLE();
  9595. }
  9596. break;
  9597. }
  9598. case PyUnicode_4BYTE_KIND:
  9599. {
  9600. switch(kind2) {
  9601. case PyUnicode_1BYTE_KIND:
  9602. COMPARE(Py_UCS4, Py_UCS1);
  9603. break;
  9604. case PyUnicode_2BYTE_KIND:
  9605. COMPARE(Py_UCS4, Py_UCS2);
  9606. break;
  9607. case PyUnicode_4BYTE_KIND:
  9608. {
  9609. #if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
  9610. int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
  9611. /* normalize result of wmemcmp() into the range [-1; 1] */
  9612. if (cmp < 0)
  9613. return -1;
  9614. if (cmp > 0)
  9615. return 1;
  9616. #else
  9617. COMPARE(Py_UCS4, Py_UCS4);
  9618. #endif
  9619. break;
  9620. }
  9621. default:
  9622. Py_UNREACHABLE();
  9623. }
  9624. break;
  9625. }
  9626. default:
  9627. Py_UNREACHABLE();
  9628. }
  9629. if (len1 == len2)
  9630. return 0;
  9631. if (len1 < len2)
  9632. return -1;
  9633. else
  9634. return 1;
  9635. #undef COMPARE
  9636. }
  9637. static int
  9638. unicode_compare_eq(PyObject *str1, PyObject *str2)
  9639. {
  9640. int kind;
  9641. const void *data1, *data2;
  9642. Py_ssize_t len;
  9643. int cmp;
  9644. len = PyUnicode_GET_LENGTH(str1);
  9645. if (PyUnicode_GET_LENGTH(str2) != len)
  9646. return 0;
  9647. kind = PyUnicode_KIND(str1);
  9648. if (PyUnicode_KIND(str2) != kind)
  9649. return 0;
  9650. data1 = PyUnicode_DATA(str1);
  9651. data2 = PyUnicode_DATA(str2);
  9652. cmp = memcmp(data1, data2, len * kind);
  9653. return (cmp == 0);
  9654. }
  9655. int
  9656. _PyUnicode_Equal(PyObject *str1, PyObject *str2)
  9657. {
  9658. assert(PyUnicode_Check(str1));
  9659. assert(PyUnicode_Check(str2));
  9660. if (str1 == str2) {
  9661. return 1;
  9662. }
  9663. return unicode_compare_eq(str1, str2);
  9664. }
  9665. int
  9666. PyUnicode_Compare(PyObject *left, PyObject *right)
  9667. {
  9668. if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
  9669. /* a string is equal to itself */
  9670. if (left == right)
  9671. return 0;
  9672. return unicode_compare(left, right);
  9673. }
  9674. PyErr_Format(PyExc_TypeError,
  9675. "Can't compare %.100s and %.100s",
  9676. Py_TYPE(left)->tp_name,
  9677. Py_TYPE(right)->tp_name);
  9678. return -1;
  9679. }
  9680. int
  9681. PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
  9682. {
  9683. Py_ssize_t i;
  9684. int kind;
  9685. Py_UCS4 chr;
  9686. assert(_PyUnicode_CHECK(uni));
  9687. kind = PyUnicode_KIND(uni);
  9688. if (kind == PyUnicode_1BYTE_KIND) {
  9689. const void *data = PyUnicode_1BYTE_DATA(uni);
  9690. size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
  9691. size_t len, len2 = strlen(str);
  9692. int cmp;
  9693. len = Py_MIN(len1, len2);
  9694. cmp = memcmp(data, str, len);
  9695. if (cmp != 0) {
  9696. if (cmp < 0)
  9697. return -1;
  9698. else
  9699. return 1;
  9700. }
  9701. if (len1 > len2)
  9702. return 1; /* uni is longer */
  9703. if (len1 < len2)
  9704. return -1; /* str is longer */
  9705. return 0;
  9706. }
  9707. else {
  9708. const void *data = PyUnicode_DATA(uni);
  9709. /* Compare Unicode string and source character set string */
  9710. for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
  9711. if (chr != (unsigned char)str[i])
  9712. return (chr < (unsigned char)(str[i])) ? -1 : 1;
  9713. /* This check keeps Python strings that end in '\0' from comparing equal
  9714. to C strings identical up to that point. */
  9715. if (PyUnicode_GET_LENGTH(uni) != i || chr)
  9716. return 1; /* uni is longer */
  9717. if (str[i])
  9718. return -1; /* str is longer */
  9719. return 0;
  9720. }
  9721. }
  9722. int
  9723. _PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
  9724. {
  9725. size_t len;
  9726. assert(_PyUnicode_CHECK(unicode));
  9727. assert(str);
  9728. #ifndef NDEBUG
  9729. for (const char *p = str; *p; p++) {
  9730. assert((unsigned char)*p < 128);
  9731. }
  9732. #endif
  9733. if (!PyUnicode_IS_ASCII(unicode))
  9734. return 0;
  9735. len = (size_t)PyUnicode_GET_LENGTH(unicode);
  9736. return strlen(str) == len &&
  9737. memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
  9738. }
  9739. int
  9740. _PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
  9741. {
  9742. PyObject *right_uni;
  9743. assert(_PyUnicode_CHECK(left));
  9744. assert(right->string);
  9745. #ifndef NDEBUG
  9746. for (const char *p = right->string; *p; p++) {
  9747. assert((unsigned char)*p < 128);
  9748. }
  9749. #endif
  9750. if (!PyUnicode_IS_ASCII(left))
  9751. return 0;
  9752. right_uni = _PyUnicode_FromId(right); /* borrowed */
  9753. if (right_uni == NULL) {
  9754. /* memory error or bad data */
  9755. PyErr_Clear();
  9756. return _PyUnicode_EqualToASCIIString(left, right->string);
  9757. }
  9758. if (left == right_uni)
  9759. return 1;
  9760. assert(PyUnicode_CHECK_INTERNED(right_uni));
  9761. if (PyUnicode_CHECK_INTERNED(left)) {
  9762. return 0;
  9763. }
  9764. assert(_PyUnicode_HASH(right_uni) != -1);
  9765. Py_hash_t hash = _PyUnicode_HASH(left);
  9766. if (hash != -1 && hash != _PyUnicode_HASH(right_uni)) {
  9767. return 0;
  9768. }
  9769. return unicode_compare_eq(left, right_uni);
  9770. }
  9771. PyObject *
  9772. PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
  9773. {
  9774. int result;
  9775. if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
  9776. Py_RETURN_NOTIMPLEMENTED;
  9777. if (left == right) {
  9778. switch (op) {
  9779. case Py_EQ:
  9780. case Py_LE:
  9781. case Py_GE:
  9782. /* a string is equal to itself */
  9783. Py_RETURN_TRUE;
  9784. case Py_NE:
  9785. case Py_LT:
  9786. case Py_GT:
  9787. Py_RETURN_FALSE;
  9788. default:
  9789. PyErr_BadArgument();
  9790. return NULL;
  9791. }
  9792. }
  9793. else if (op == Py_EQ || op == Py_NE) {
  9794. result = unicode_compare_eq(left, right);
  9795. result ^= (op == Py_NE);
  9796. return PyBool_FromLong(result);
  9797. }
  9798. else {
  9799. result = unicode_compare(left, right);
  9800. Py_RETURN_RICHCOMPARE(result, 0, op);
  9801. }
  9802. }
  9803. int
  9804. _PyUnicode_EQ(PyObject *aa, PyObject *bb)
  9805. {
  9806. return unicode_eq(aa, bb);
  9807. }
  9808. int
  9809. PyUnicode_Contains(PyObject *str, PyObject *substr)
  9810. {
  9811. int kind1, kind2;
  9812. const void *buf1, *buf2;
  9813. Py_ssize_t len1, len2;
  9814. int result;
  9815. if (!PyUnicode_Check(substr)) {
  9816. PyErr_Format(PyExc_TypeError,
  9817. "'in <string>' requires string as left operand, not %.100s",
  9818. Py_TYPE(substr)->tp_name);
  9819. return -1;
  9820. }
  9821. if (ensure_unicode(str) < 0)
  9822. return -1;
  9823. kind1 = PyUnicode_KIND(str);
  9824. kind2 = PyUnicode_KIND(substr);
  9825. if (kind1 < kind2)
  9826. return 0;
  9827. len1 = PyUnicode_GET_LENGTH(str);
  9828. len2 = PyUnicode_GET_LENGTH(substr);
  9829. if (len1 < len2)
  9830. return 0;
  9831. buf1 = PyUnicode_DATA(str);
  9832. buf2 = PyUnicode_DATA(substr);
  9833. if (len2 == 1) {
  9834. Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
  9835. result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
  9836. return result;
  9837. }
  9838. if (kind2 != kind1) {
  9839. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  9840. if (!buf2)
  9841. return -1;
  9842. }
  9843. switch (kind1) {
  9844. case PyUnicode_1BYTE_KIND:
  9845. result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
  9846. break;
  9847. case PyUnicode_2BYTE_KIND:
  9848. result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
  9849. break;
  9850. case PyUnicode_4BYTE_KIND:
  9851. result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
  9852. break;
  9853. default:
  9854. Py_UNREACHABLE();
  9855. }
  9856. assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(substr)));
  9857. if (kind2 != kind1)
  9858. PyMem_Free((void *)buf2);
  9859. return result;
  9860. }
  9861. /* Concat to string or Unicode object giving a new Unicode object. */
  9862. PyObject *
  9863. PyUnicode_Concat(PyObject *left, PyObject *right)
  9864. {
  9865. PyObject *result;
  9866. Py_UCS4 maxchar, maxchar2;
  9867. Py_ssize_t left_len, right_len, new_len;
  9868. if (ensure_unicode(left) < 0)
  9869. return NULL;
  9870. if (!PyUnicode_Check(right)) {
  9871. PyErr_Format(PyExc_TypeError,
  9872. "can only concatenate str (not \"%.200s\") to str",
  9873. Py_TYPE(right)->tp_name);
  9874. return NULL;
  9875. }
  9876. /* Shortcuts */
  9877. PyObject *empty = unicode_get_empty(); // Borrowed reference
  9878. if (left == empty) {
  9879. return PyUnicode_FromObject(right);
  9880. }
  9881. if (right == empty) {
  9882. return PyUnicode_FromObject(left);
  9883. }
  9884. left_len = PyUnicode_GET_LENGTH(left);
  9885. right_len = PyUnicode_GET_LENGTH(right);
  9886. if (left_len > PY_SSIZE_T_MAX - right_len) {
  9887. PyErr_SetString(PyExc_OverflowError,
  9888. "strings are too large to concat");
  9889. return NULL;
  9890. }
  9891. new_len = left_len + right_len;
  9892. maxchar = PyUnicode_MAX_CHAR_VALUE(left);
  9893. maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
  9894. maxchar = Py_MAX(maxchar, maxchar2);
  9895. /* Concat the two Unicode strings */
  9896. result = PyUnicode_New(new_len, maxchar);
  9897. if (result == NULL)
  9898. return NULL;
  9899. _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
  9900. _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
  9901. assert(_PyUnicode_CheckConsistency(result, 1));
  9902. return result;
  9903. }
  9904. void
  9905. PyUnicode_Append(PyObject **p_left, PyObject *right)
  9906. {
  9907. PyObject *left, *res;
  9908. Py_UCS4 maxchar, maxchar2;
  9909. Py_ssize_t left_len, right_len, new_len;
  9910. if (p_left == NULL) {
  9911. if (!PyErr_Occurred())
  9912. PyErr_BadInternalCall();
  9913. return;
  9914. }
  9915. left = *p_left;
  9916. if (right == NULL || left == NULL
  9917. || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
  9918. if (!PyErr_Occurred())
  9919. PyErr_BadInternalCall();
  9920. goto error;
  9921. }
  9922. /* Shortcuts */
  9923. PyObject *empty = unicode_get_empty(); // Borrowed reference
  9924. if (left == empty) {
  9925. Py_DECREF(left);
  9926. *p_left = Py_NewRef(right);
  9927. return;
  9928. }
  9929. if (right == empty) {
  9930. return;
  9931. }
  9932. left_len = PyUnicode_GET_LENGTH(left);
  9933. right_len = PyUnicode_GET_LENGTH(right);
  9934. if (left_len > PY_SSIZE_T_MAX - right_len) {
  9935. PyErr_SetString(PyExc_OverflowError,
  9936. "strings are too large to concat");
  9937. goto error;
  9938. }
  9939. new_len = left_len + right_len;
  9940. if (unicode_modifiable(left)
  9941. && PyUnicode_CheckExact(right)
  9942. && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
  9943. /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
  9944. to change the structure size, but characters are stored just after
  9945. the structure, and so it requires to move all characters which is
  9946. not so different than duplicating the string. */
  9947. && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
  9948. {
  9949. /* append inplace */
  9950. if (unicode_resize(p_left, new_len) != 0)
  9951. goto error;
  9952. /* copy 'right' into the newly allocated area of 'left' */
  9953. _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
  9954. }
  9955. else {
  9956. maxchar = PyUnicode_MAX_CHAR_VALUE(left);
  9957. maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
  9958. maxchar = Py_MAX(maxchar, maxchar2);
  9959. /* Concat the two Unicode strings */
  9960. res = PyUnicode_New(new_len, maxchar);
  9961. if (res == NULL)
  9962. goto error;
  9963. _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
  9964. _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
  9965. Py_DECREF(left);
  9966. *p_left = res;
  9967. }
  9968. assert(_PyUnicode_CheckConsistency(*p_left, 1));
  9969. return;
  9970. error:
  9971. Py_CLEAR(*p_left);
  9972. }
  9973. void
  9974. PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
  9975. {
  9976. PyUnicode_Append(pleft, right);
  9977. Py_XDECREF(right);
  9978. }
  9979. /*
  9980. Wraps asciilib_parse_args_finds() and additionally ensures that the
  9981. first argument is a unicode object.
  9982. */
  9983. static inline int
  9984. parse_args_finds_unicode(const char * function_name, PyObject *args,
  9985. PyObject **substring,
  9986. Py_ssize_t *start, Py_ssize_t *end)
  9987. {
  9988. if (asciilib_parse_args_finds(function_name, args, substring, start, end)) {
  9989. if (ensure_unicode(*substring) < 0)
  9990. return 0;
  9991. return 1;
  9992. }
  9993. return 0;
  9994. }
  9995. PyDoc_STRVAR(count__doc__,
  9996. "S.count(sub[, start[, end]]) -> int\n\
  9997. \n\
  9998. Return the number of non-overlapping occurrences of substring sub in\n\
  9999. string S[start:end]. Optional arguments start and end are\n\
  10000. interpreted as in slice notation.");
  10001. static PyObject *
  10002. unicode_count(PyObject *self, PyObject *args)
  10003. {
  10004. PyObject *substring = NULL; /* initialize to fix a compiler warning */
  10005. Py_ssize_t start = 0;
  10006. Py_ssize_t end = PY_SSIZE_T_MAX;
  10007. Py_ssize_t result;
  10008. if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
  10009. return NULL;
  10010. result = unicode_count_impl(self, substring, start, end);
  10011. if (result == -1)
  10012. return NULL;
  10013. return PyLong_FromSsize_t(result);
  10014. }
  10015. /*[clinic input]
  10016. str.encode as unicode_encode
  10017. encoding: str(c_default="NULL") = 'utf-8'
  10018. The encoding in which to encode the string.
  10019. errors: str(c_default="NULL") = 'strict'
  10020. The error handling scheme to use for encoding errors.
  10021. The default is 'strict' meaning that encoding errors raise a
  10022. UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
  10023. 'xmlcharrefreplace' as well as any other name registered with
  10024. codecs.register_error that can handle UnicodeEncodeErrors.
  10025. Encode the string using the codec registered for encoding.
  10026. [clinic start generated code]*/
  10027. static PyObject *
  10028. unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
  10029. /*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
  10030. {
  10031. return PyUnicode_AsEncodedString(self, encoding, errors);
  10032. }
  10033. /*[clinic input]
  10034. str.expandtabs as unicode_expandtabs
  10035. tabsize: int = 8
  10036. Return a copy where all tab characters are expanded using spaces.
  10037. If tabsize is not given, a tab size of 8 characters is assumed.
  10038. [clinic start generated code]*/
  10039. static PyObject *
  10040. unicode_expandtabs_impl(PyObject *self, int tabsize)
  10041. /*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
  10042. {
  10043. Py_ssize_t i, j, line_pos, src_len, incr;
  10044. Py_UCS4 ch;
  10045. PyObject *u;
  10046. const void *src_data;
  10047. void *dest_data;
  10048. int kind;
  10049. int found;
  10050. /* First pass: determine size of output string */
  10051. src_len = PyUnicode_GET_LENGTH(self);
  10052. i = j = line_pos = 0;
  10053. kind = PyUnicode_KIND(self);
  10054. src_data = PyUnicode_DATA(self);
  10055. found = 0;
  10056. for (; i < src_len; i++) {
  10057. ch = PyUnicode_READ(kind, src_data, i);
  10058. if (ch == '\t') {
  10059. found = 1;
  10060. if (tabsize > 0) {
  10061. incr = tabsize - (line_pos % tabsize); /* cannot overflow */
  10062. if (j > PY_SSIZE_T_MAX - incr)
  10063. goto overflow;
  10064. line_pos += incr;
  10065. j += incr;
  10066. }
  10067. }
  10068. else {
  10069. if (j > PY_SSIZE_T_MAX - 1)
  10070. goto overflow;
  10071. line_pos++;
  10072. j++;
  10073. if (ch == '\n' || ch == '\r')
  10074. line_pos = 0;
  10075. }
  10076. }
  10077. if (!found)
  10078. return unicode_result_unchanged(self);
  10079. /* Second pass: create output string and fill it */
  10080. u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
  10081. if (!u)
  10082. return NULL;
  10083. dest_data = PyUnicode_DATA(u);
  10084. i = j = line_pos = 0;
  10085. for (; i < src_len; i++) {
  10086. ch = PyUnicode_READ(kind, src_data, i);
  10087. if (ch == '\t') {
  10088. if (tabsize > 0) {
  10089. incr = tabsize - (line_pos % tabsize);
  10090. line_pos += incr;
  10091. unicode_fill(kind, dest_data, ' ', j, incr);
  10092. j += incr;
  10093. }
  10094. }
  10095. else {
  10096. line_pos++;
  10097. PyUnicode_WRITE(kind, dest_data, j, ch);
  10098. j++;
  10099. if (ch == '\n' || ch == '\r')
  10100. line_pos = 0;
  10101. }
  10102. }
  10103. assert (j == PyUnicode_GET_LENGTH(u));
  10104. return unicode_result(u);
  10105. overflow:
  10106. PyErr_SetString(PyExc_OverflowError, "new string is too long");
  10107. return NULL;
  10108. }
  10109. PyDoc_STRVAR(find__doc__,
  10110. "S.find(sub[, start[, end]]) -> int\n\
  10111. \n\
  10112. Return the lowest index in S where substring sub is found,\n\
  10113. such that sub is contained within S[start:end]. Optional\n\
  10114. arguments start and end are interpreted as in slice notation.\n\
  10115. \n\
  10116. Return -1 on failure.");
  10117. static PyObject *
  10118. unicode_find(PyObject *self, PyObject *args)
  10119. {
  10120. /* initialize variables to prevent gcc warning */
  10121. PyObject *substring = NULL;
  10122. Py_ssize_t start = 0;
  10123. Py_ssize_t end = 0;
  10124. Py_ssize_t result;
  10125. if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
  10126. return NULL;
  10127. result = any_find_slice(self, substring, start, end, 1);
  10128. if (result == -2)
  10129. return NULL;
  10130. return PyLong_FromSsize_t(result);
  10131. }
  10132. static PyObject *
  10133. unicode_getitem(PyObject *self, Py_ssize_t index)
  10134. {
  10135. const void *data;
  10136. int kind;
  10137. Py_UCS4 ch;
  10138. if (!PyUnicode_Check(self)) {
  10139. PyErr_BadArgument();
  10140. return NULL;
  10141. }
  10142. if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
  10143. PyErr_SetString(PyExc_IndexError, "string index out of range");
  10144. return NULL;
  10145. }
  10146. kind = PyUnicode_KIND(self);
  10147. data = PyUnicode_DATA(self);
  10148. ch = PyUnicode_READ(kind, data, index);
  10149. return unicode_char(ch);
  10150. }
  10151. /* Believe it or not, this produces the same value for ASCII strings
  10152. as bytes_hash(). */
  10153. static Py_hash_t
  10154. unicode_hash(PyObject *self)
  10155. {
  10156. Py_uhash_t x; /* Unsigned for defined overflow behavior. */
  10157. #ifdef Py_DEBUG
  10158. assert(_Py_HashSecret_Initialized);
  10159. #endif
  10160. if (_PyUnicode_HASH(self) != -1)
  10161. return _PyUnicode_HASH(self);
  10162. x = _Py_HashBytes(PyUnicode_DATA(self),
  10163. PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
  10164. _PyUnicode_HASH(self) = x;
  10165. return x;
  10166. }
  10167. PyDoc_STRVAR(index__doc__,
  10168. "S.index(sub[, start[, end]]) -> int\n\
  10169. \n\
  10170. Return the lowest index in S where substring sub is found,\n\
  10171. such that sub is contained within S[start:end]. Optional\n\
  10172. arguments start and end are interpreted as in slice notation.\n\
  10173. \n\
  10174. Raises ValueError when the substring is not found.");
  10175. static PyObject *
  10176. unicode_index(PyObject *self, PyObject *args)
  10177. {
  10178. /* initialize variables to prevent gcc warning */
  10179. Py_ssize_t result;
  10180. PyObject *substring = NULL;
  10181. Py_ssize_t start = 0;
  10182. Py_ssize_t end = 0;
  10183. if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
  10184. return NULL;
  10185. result = any_find_slice(self, substring, start, end, 1);
  10186. if (result == -2)
  10187. return NULL;
  10188. if (result < 0) {
  10189. PyErr_SetString(PyExc_ValueError, "substring not found");
  10190. return NULL;
  10191. }
  10192. return PyLong_FromSsize_t(result);
  10193. }
  10194. /*[clinic input]
  10195. str.isascii as unicode_isascii
  10196. Return True if all characters in the string are ASCII, False otherwise.
  10197. ASCII characters have code points in the range U+0000-U+007F.
  10198. Empty string is ASCII too.
  10199. [clinic start generated code]*/
  10200. static PyObject *
  10201. unicode_isascii_impl(PyObject *self)
  10202. /*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
  10203. {
  10204. return PyBool_FromLong(PyUnicode_IS_ASCII(self));
  10205. }
  10206. /*[clinic input]
  10207. str.islower as unicode_islower
  10208. Return True if the string is a lowercase string, False otherwise.
  10209. A string is lowercase if all cased characters in the string are lowercase and
  10210. there is at least one cased character in the string.
  10211. [clinic start generated code]*/
  10212. static PyObject *
  10213. unicode_islower_impl(PyObject *self)
  10214. /*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
  10215. {
  10216. Py_ssize_t i, length;
  10217. int kind;
  10218. const void *data;
  10219. int cased;
  10220. length = PyUnicode_GET_LENGTH(self);
  10221. kind = PyUnicode_KIND(self);
  10222. data = PyUnicode_DATA(self);
  10223. /* Shortcut for single character strings */
  10224. if (length == 1)
  10225. return PyBool_FromLong(
  10226. Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
  10227. /* Special case for empty strings */
  10228. if (length == 0)
  10229. Py_RETURN_FALSE;
  10230. cased = 0;
  10231. for (i = 0; i < length; i++) {
  10232. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10233. if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
  10234. Py_RETURN_FALSE;
  10235. else if (!cased && Py_UNICODE_ISLOWER(ch))
  10236. cased = 1;
  10237. }
  10238. return PyBool_FromLong(cased);
  10239. }
  10240. /*[clinic input]
  10241. str.isupper as unicode_isupper
  10242. Return True if the string is an uppercase string, False otherwise.
  10243. A string is uppercase if all cased characters in the string are uppercase and
  10244. there is at least one cased character in the string.
  10245. [clinic start generated code]*/
  10246. static PyObject *
  10247. unicode_isupper_impl(PyObject *self)
  10248. /*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
  10249. {
  10250. Py_ssize_t i, length;
  10251. int kind;
  10252. const void *data;
  10253. int cased;
  10254. length = PyUnicode_GET_LENGTH(self);
  10255. kind = PyUnicode_KIND(self);
  10256. data = PyUnicode_DATA(self);
  10257. /* Shortcut for single character strings */
  10258. if (length == 1)
  10259. return PyBool_FromLong(
  10260. Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
  10261. /* Special case for empty strings */
  10262. if (length == 0)
  10263. Py_RETURN_FALSE;
  10264. cased = 0;
  10265. for (i = 0; i < length; i++) {
  10266. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10267. if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
  10268. Py_RETURN_FALSE;
  10269. else if (!cased && Py_UNICODE_ISUPPER(ch))
  10270. cased = 1;
  10271. }
  10272. return PyBool_FromLong(cased);
  10273. }
  10274. /*[clinic input]
  10275. str.istitle as unicode_istitle
  10276. Return True if the string is a title-cased string, False otherwise.
  10277. In a title-cased string, upper- and title-case characters may only
  10278. follow uncased characters and lowercase characters only cased ones.
  10279. [clinic start generated code]*/
  10280. static PyObject *
  10281. unicode_istitle_impl(PyObject *self)
  10282. /*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
  10283. {
  10284. Py_ssize_t i, length;
  10285. int kind;
  10286. const void *data;
  10287. int cased, previous_is_cased;
  10288. length = PyUnicode_GET_LENGTH(self);
  10289. kind = PyUnicode_KIND(self);
  10290. data = PyUnicode_DATA(self);
  10291. /* Shortcut for single character strings */
  10292. if (length == 1) {
  10293. Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
  10294. return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
  10295. (Py_UNICODE_ISUPPER(ch) != 0));
  10296. }
  10297. /* Special case for empty strings */
  10298. if (length == 0)
  10299. Py_RETURN_FALSE;
  10300. cased = 0;
  10301. previous_is_cased = 0;
  10302. for (i = 0; i < length; i++) {
  10303. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10304. if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
  10305. if (previous_is_cased)
  10306. Py_RETURN_FALSE;
  10307. previous_is_cased = 1;
  10308. cased = 1;
  10309. }
  10310. else if (Py_UNICODE_ISLOWER(ch)) {
  10311. if (!previous_is_cased)
  10312. Py_RETURN_FALSE;
  10313. previous_is_cased = 1;
  10314. cased = 1;
  10315. }
  10316. else
  10317. previous_is_cased = 0;
  10318. }
  10319. return PyBool_FromLong(cased);
  10320. }
  10321. /*[clinic input]
  10322. str.isspace as unicode_isspace
  10323. Return True if the string is a whitespace string, False otherwise.
  10324. A string is whitespace if all characters in the string are whitespace and there
  10325. is at least one character in the string.
  10326. [clinic start generated code]*/
  10327. static PyObject *
  10328. unicode_isspace_impl(PyObject *self)
  10329. /*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
  10330. {
  10331. Py_ssize_t i, length;
  10332. int kind;
  10333. const void *data;
  10334. length = PyUnicode_GET_LENGTH(self);
  10335. kind = PyUnicode_KIND(self);
  10336. data = PyUnicode_DATA(self);
  10337. /* Shortcut for single character strings */
  10338. if (length == 1)
  10339. return PyBool_FromLong(
  10340. Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
  10341. /* Special case for empty strings */
  10342. if (length == 0)
  10343. Py_RETURN_FALSE;
  10344. for (i = 0; i < length; i++) {
  10345. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10346. if (!Py_UNICODE_ISSPACE(ch))
  10347. Py_RETURN_FALSE;
  10348. }
  10349. Py_RETURN_TRUE;
  10350. }
  10351. /*[clinic input]
  10352. str.isalpha as unicode_isalpha
  10353. Return True if the string is an alphabetic string, False otherwise.
  10354. A string is alphabetic if all characters in the string are alphabetic and there
  10355. is at least one character in the string.
  10356. [clinic start generated code]*/
  10357. static PyObject *
  10358. unicode_isalpha_impl(PyObject *self)
  10359. /*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
  10360. {
  10361. Py_ssize_t i, length;
  10362. int kind;
  10363. const void *data;
  10364. length = PyUnicode_GET_LENGTH(self);
  10365. kind = PyUnicode_KIND(self);
  10366. data = PyUnicode_DATA(self);
  10367. /* Shortcut for single character strings */
  10368. if (length == 1)
  10369. return PyBool_FromLong(
  10370. Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
  10371. /* Special case for empty strings */
  10372. if (length == 0)
  10373. Py_RETURN_FALSE;
  10374. for (i = 0; i < length; i++) {
  10375. if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
  10376. Py_RETURN_FALSE;
  10377. }
  10378. Py_RETURN_TRUE;
  10379. }
  10380. /*[clinic input]
  10381. str.isalnum as unicode_isalnum
  10382. Return True if the string is an alpha-numeric string, False otherwise.
  10383. A string is alpha-numeric if all characters in the string are alpha-numeric and
  10384. there is at least one character in the string.
  10385. [clinic start generated code]*/
  10386. static PyObject *
  10387. unicode_isalnum_impl(PyObject *self)
  10388. /*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
  10389. {
  10390. int kind;
  10391. const void *data;
  10392. Py_ssize_t len, i;
  10393. kind = PyUnicode_KIND(self);
  10394. data = PyUnicode_DATA(self);
  10395. len = PyUnicode_GET_LENGTH(self);
  10396. /* Shortcut for single character strings */
  10397. if (len == 1) {
  10398. const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
  10399. return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
  10400. }
  10401. /* Special case for empty strings */
  10402. if (len == 0)
  10403. Py_RETURN_FALSE;
  10404. for (i = 0; i < len; i++) {
  10405. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10406. if (!Py_UNICODE_ISALNUM(ch))
  10407. Py_RETURN_FALSE;
  10408. }
  10409. Py_RETURN_TRUE;
  10410. }
  10411. /*[clinic input]
  10412. str.isdecimal as unicode_isdecimal
  10413. Return True if the string is a decimal string, False otherwise.
  10414. A string is a decimal string if all characters in the string are decimal and
  10415. there is at least one character in the string.
  10416. [clinic start generated code]*/
  10417. static PyObject *
  10418. unicode_isdecimal_impl(PyObject *self)
  10419. /*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
  10420. {
  10421. Py_ssize_t i, length;
  10422. int kind;
  10423. const void *data;
  10424. length = PyUnicode_GET_LENGTH(self);
  10425. kind = PyUnicode_KIND(self);
  10426. data = PyUnicode_DATA(self);
  10427. /* Shortcut for single character strings */
  10428. if (length == 1)
  10429. return PyBool_FromLong(
  10430. Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
  10431. /* Special case for empty strings */
  10432. if (length == 0)
  10433. Py_RETURN_FALSE;
  10434. for (i = 0; i < length; i++) {
  10435. if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
  10436. Py_RETURN_FALSE;
  10437. }
  10438. Py_RETURN_TRUE;
  10439. }
  10440. /*[clinic input]
  10441. str.isdigit as unicode_isdigit
  10442. Return True if the string is a digit string, False otherwise.
  10443. A string is a digit string if all characters in the string are digits and there
  10444. is at least one character in the string.
  10445. [clinic start generated code]*/
  10446. static PyObject *
  10447. unicode_isdigit_impl(PyObject *self)
  10448. /*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
  10449. {
  10450. Py_ssize_t i, length;
  10451. int kind;
  10452. const void *data;
  10453. length = PyUnicode_GET_LENGTH(self);
  10454. kind = PyUnicode_KIND(self);
  10455. data = PyUnicode_DATA(self);
  10456. /* Shortcut for single character strings */
  10457. if (length == 1) {
  10458. const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
  10459. return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
  10460. }
  10461. /* Special case for empty strings */
  10462. if (length == 0)
  10463. Py_RETURN_FALSE;
  10464. for (i = 0; i < length; i++) {
  10465. if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
  10466. Py_RETURN_FALSE;
  10467. }
  10468. Py_RETURN_TRUE;
  10469. }
  10470. /*[clinic input]
  10471. str.isnumeric as unicode_isnumeric
  10472. Return True if the string is a numeric string, False otherwise.
  10473. A string is numeric if all characters in the string are numeric and there is at
  10474. least one character in the string.
  10475. [clinic start generated code]*/
  10476. static PyObject *
  10477. unicode_isnumeric_impl(PyObject *self)
  10478. /*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
  10479. {
  10480. Py_ssize_t i, length;
  10481. int kind;
  10482. const void *data;
  10483. length = PyUnicode_GET_LENGTH(self);
  10484. kind = PyUnicode_KIND(self);
  10485. data = PyUnicode_DATA(self);
  10486. /* Shortcut for single character strings */
  10487. if (length == 1)
  10488. return PyBool_FromLong(
  10489. Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
  10490. /* Special case for empty strings */
  10491. if (length == 0)
  10492. Py_RETURN_FALSE;
  10493. for (i = 0; i < length; i++) {
  10494. if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
  10495. Py_RETURN_FALSE;
  10496. }
  10497. Py_RETURN_TRUE;
  10498. }
  10499. Py_ssize_t
  10500. _PyUnicode_ScanIdentifier(PyObject *self)
  10501. {
  10502. Py_ssize_t i;
  10503. Py_ssize_t len = PyUnicode_GET_LENGTH(self);
  10504. if (len == 0) {
  10505. /* an empty string is not a valid identifier */
  10506. return 0;
  10507. }
  10508. int kind = PyUnicode_KIND(self);
  10509. const void *data = PyUnicode_DATA(self);
  10510. Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
  10511. /* PEP 3131 says that the first character must be in
  10512. XID_Start and subsequent characters in XID_Continue,
  10513. and for the ASCII range, the 2.x rules apply (i.e
  10514. start with letters and underscore, continue with
  10515. letters, digits, underscore). However, given the current
  10516. definition of XID_Start and XID_Continue, it is sufficient
  10517. to check just for these, except that _ must be allowed
  10518. as starting an identifier. */
  10519. if (!_PyUnicode_IsXidStart(ch) && ch != 0x5F /* LOW LINE */) {
  10520. return 0;
  10521. }
  10522. for (i = 1; i < len; i++) {
  10523. ch = PyUnicode_READ(kind, data, i);
  10524. if (!_PyUnicode_IsXidContinue(ch)) {
  10525. return i;
  10526. }
  10527. }
  10528. return i;
  10529. }
  10530. int
  10531. PyUnicode_IsIdentifier(PyObject *self)
  10532. {
  10533. Py_ssize_t i = _PyUnicode_ScanIdentifier(self);
  10534. Py_ssize_t len = PyUnicode_GET_LENGTH(self);
  10535. /* an empty string is not a valid identifier */
  10536. return len && i == len;
  10537. }
  10538. /*[clinic input]
  10539. str.isidentifier as unicode_isidentifier
  10540. Return True if the string is a valid Python identifier, False otherwise.
  10541. Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
  10542. such as "def" or "class".
  10543. [clinic start generated code]*/
  10544. static PyObject *
  10545. unicode_isidentifier_impl(PyObject *self)
  10546. /*[clinic end generated code: output=fe585a9666572905 input=2d807a104f21c0c5]*/
  10547. {
  10548. return PyBool_FromLong(PyUnicode_IsIdentifier(self));
  10549. }
  10550. /*[clinic input]
  10551. str.isprintable as unicode_isprintable
  10552. Return True if the string is printable, False otherwise.
  10553. A string is printable if all of its characters are considered printable in
  10554. repr() or if it is empty.
  10555. [clinic start generated code]*/
  10556. static PyObject *
  10557. unicode_isprintable_impl(PyObject *self)
  10558. /*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
  10559. {
  10560. Py_ssize_t i, length;
  10561. int kind;
  10562. const void *data;
  10563. length = PyUnicode_GET_LENGTH(self);
  10564. kind = PyUnicode_KIND(self);
  10565. data = PyUnicode_DATA(self);
  10566. /* Shortcut for single character strings */
  10567. if (length == 1)
  10568. return PyBool_FromLong(
  10569. Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
  10570. for (i = 0; i < length; i++) {
  10571. if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
  10572. Py_RETURN_FALSE;
  10573. }
  10574. }
  10575. Py_RETURN_TRUE;
  10576. }
  10577. /*[clinic input]
  10578. str.join as unicode_join
  10579. iterable: object
  10580. /
  10581. Concatenate any number of strings.
  10582. The string whose method is called is inserted in between each given string.
  10583. The result is returned as a new string.
  10584. Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
  10585. [clinic start generated code]*/
  10586. static PyObject *
  10587. unicode_join(PyObject *self, PyObject *iterable)
  10588. /*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
  10589. {
  10590. return PyUnicode_Join(self, iterable);
  10591. }
  10592. static Py_ssize_t
  10593. unicode_length(PyObject *self)
  10594. {
  10595. return PyUnicode_GET_LENGTH(self);
  10596. }
  10597. /*[clinic input]
  10598. str.ljust as unicode_ljust
  10599. width: Py_ssize_t
  10600. fillchar: Py_UCS4 = ' '
  10601. /
  10602. Return a left-justified string of length width.
  10603. Padding is done using the specified fill character (default is a space).
  10604. [clinic start generated code]*/
  10605. static PyObject *
  10606. unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
  10607. /*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
  10608. {
  10609. if (PyUnicode_GET_LENGTH(self) >= width)
  10610. return unicode_result_unchanged(self);
  10611. return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
  10612. }
  10613. /*[clinic input]
  10614. str.lower as unicode_lower
  10615. Return a copy of the string converted to lowercase.
  10616. [clinic start generated code]*/
  10617. static PyObject *
  10618. unicode_lower_impl(PyObject *self)
  10619. /*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
  10620. {
  10621. if (PyUnicode_IS_ASCII(self))
  10622. return ascii_upper_or_lower(self, 1);
  10623. return case_operation(self, do_lower);
  10624. }
  10625. #define LEFTSTRIP 0
  10626. #define RIGHTSTRIP 1
  10627. #define BOTHSTRIP 2
  10628. /* Arrays indexed by above */
  10629. static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
  10630. #define STRIPNAME(i) (stripfuncnames[i])
  10631. /* externally visible for str.strip(unicode) */
  10632. PyObject *
  10633. _PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
  10634. {
  10635. const void *data;
  10636. int kind;
  10637. Py_ssize_t i, j, len;
  10638. BLOOM_MASK sepmask;
  10639. Py_ssize_t seplen;
  10640. kind = PyUnicode_KIND(self);
  10641. data = PyUnicode_DATA(self);
  10642. len = PyUnicode_GET_LENGTH(self);
  10643. seplen = PyUnicode_GET_LENGTH(sepobj);
  10644. sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
  10645. PyUnicode_DATA(sepobj),
  10646. seplen);
  10647. i = 0;
  10648. if (striptype != RIGHTSTRIP) {
  10649. while (i < len) {
  10650. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10651. if (!BLOOM(sepmask, ch))
  10652. break;
  10653. if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
  10654. break;
  10655. i++;
  10656. }
  10657. }
  10658. j = len;
  10659. if (striptype != LEFTSTRIP) {
  10660. j--;
  10661. while (j >= i) {
  10662. Py_UCS4 ch = PyUnicode_READ(kind, data, j);
  10663. if (!BLOOM(sepmask, ch))
  10664. break;
  10665. if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
  10666. break;
  10667. j--;
  10668. }
  10669. j++;
  10670. }
  10671. return PyUnicode_Substring(self, i, j);
  10672. }
  10673. PyObject*
  10674. PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
  10675. {
  10676. const unsigned char *data;
  10677. int kind;
  10678. Py_ssize_t length;
  10679. length = PyUnicode_GET_LENGTH(self);
  10680. end = Py_MIN(end, length);
  10681. if (start == 0 && end == length)
  10682. return unicode_result_unchanged(self);
  10683. if (start < 0 || end < 0) {
  10684. PyErr_SetString(PyExc_IndexError, "string index out of range");
  10685. return NULL;
  10686. }
  10687. if (start >= length || end < start)
  10688. _Py_RETURN_UNICODE_EMPTY();
  10689. length = end - start;
  10690. if (PyUnicode_IS_ASCII(self)) {
  10691. data = PyUnicode_1BYTE_DATA(self);
  10692. return _PyUnicode_FromASCII((const char*)(data + start), length);
  10693. }
  10694. else {
  10695. kind = PyUnicode_KIND(self);
  10696. data = PyUnicode_1BYTE_DATA(self);
  10697. return PyUnicode_FromKindAndData(kind,
  10698. data + kind * start,
  10699. length);
  10700. }
  10701. }
  10702. static PyObject *
  10703. do_strip(PyObject *self, int striptype)
  10704. {
  10705. Py_ssize_t len, i, j;
  10706. len = PyUnicode_GET_LENGTH(self);
  10707. if (PyUnicode_IS_ASCII(self)) {
  10708. const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
  10709. i = 0;
  10710. if (striptype != RIGHTSTRIP) {
  10711. while (i < len) {
  10712. Py_UCS1 ch = data[i];
  10713. if (!_Py_ascii_whitespace[ch])
  10714. break;
  10715. i++;
  10716. }
  10717. }
  10718. j = len;
  10719. if (striptype != LEFTSTRIP) {
  10720. j--;
  10721. while (j >= i) {
  10722. Py_UCS1 ch = data[j];
  10723. if (!_Py_ascii_whitespace[ch])
  10724. break;
  10725. j--;
  10726. }
  10727. j++;
  10728. }
  10729. }
  10730. else {
  10731. int kind = PyUnicode_KIND(self);
  10732. const void *data = PyUnicode_DATA(self);
  10733. i = 0;
  10734. if (striptype != RIGHTSTRIP) {
  10735. while (i < len) {
  10736. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10737. if (!Py_UNICODE_ISSPACE(ch))
  10738. break;
  10739. i++;
  10740. }
  10741. }
  10742. j = len;
  10743. if (striptype != LEFTSTRIP) {
  10744. j--;
  10745. while (j >= i) {
  10746. Py_UCS4 ch = PyUnicode_READ(kind, data, j);
  10747. if (!Py_UNICODE_ISSPACE(ch))
  10748. break;
  10749. j--;
  10750. }
  10751. j++;
  10752. }
  10753. }
  10754. return PyUnicode_Substring(self, i, j);
  10755. }
  10756. static PyObject *
  10757. do_argstrip(PyObject *self, int striptype, PyObject *sep)
  10758. {
  10759. if (sep != Py_None) {
  10760. if (PyUnicode_Check(sep))
  10761. return _PyUnicode_XStrip(self, striptype, sep);
  10762. else {
  10763. PyErr_Format(PyExc_TypeError,
  10764. "%s arg must be None or str",
  10765. STRIPNAME(striptype));
  10766. return NULL;
  10767. }
  10768. }
  10769. return do_strip(self, striptype);
  10770. }
  10771. /*[clinic input]
  10772. str.strip as unicode_strip
  10773. chars: object = None
  10774. /
  10775. Return a copy of the string with leading and trailing whitespace removed.
  10776. If chars is given and not None, remove characters in chars instead.
  10777. [clinic start generated code]*/
  10778. static PyObject *
  10779. unicode_strip_impl(PyObject *self, PyObject *chars)
  10780. /*[clinic end generated code: output=ca19018454345d57 input=385289c6f423b954]*/
  10781. {
  10782. return do_argstrip(self, BOTHSTRIP, chars);
  10783. }
  10784. /*[clinic input]
  10785. str.lstrip as unicode_lstrip
  10786. chars: object = None
  10787. /
  10788. Return a copy of the string with leading whitespace removed.
  10789. If chars is given and not None, remove characters in chars instead.
  10790. [clinic start generated code]*/
  10791. static PyObject *
  10792. unicode_lstrip_impl(PyObject *self, PyObject *chars)
  10793. /*[clinic end generated code: output=3b43683251f79ca7 input=529f9f3834448671]*/
  10794. {
  10795. return do_argstrip(self, LEFTSTRIP, chars);
  10796. }
  10797. /*[clinic input]
  10798. str.rstrip as unicode_rstrip
  10799. chars: object = None
  10800. /
  10801. Return a copy of the string with trailing whitespace removed.
  10802. If chars is given and not None, remove characters in chars instead.
  10803. [clinic start generated code]*/
  10804. static PyObject *
  10805. unicode_rstrip_impl(PyObject *self, PyObject *chars)
  10806. /*[clinic end generated code: output=4a59230017cc3b7a input=62566c627916557f]*/
  10807. {
  10808. return do_argstrip(self, RIGHTSTRIP, chars);
  10809. }
  10810. static PyObject*
  10811. unicode_repeat(PyObject *str, Py_ssize_t len)
  10812. {
  10813. PyObject *u;
  10814. Py_ssize_t nchars, n;
  10815. if (len < 1)
  10816. _Py_RETURN_UNICODE_EMPTY();
  10817. /* no repeat, return original string */
  10818. if (len == 1)
  10819. return unicode_result_unchanged(str);
  10820. if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
  10821. PyErr_SetString(PyExc_OverflowError,
  10822. "repeated string is too long");
  10823. return NULL;
  10824. }
  10825. nchars = len * PyUnicode_GET_LENGTH(str);
  10826. u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
  10827. if (!u)
  10828. return NULL;
  10829. assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
  10830. if (PyUnicode_GET_LENGTH(str) == 1) {
  10831. int kind = PyUnicode_KIND(str);
  10832. Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
  10833. if (kind == PyUnicode_1BYTE_KIND) {
  10834. void *to = PyUnicode_DATA(u);
  10835. memset(to, (unsigned char)fill_char, len);
  10836. }
  10837. else if (kind == PyUnicode_2BYTE_KIND) {
  10838. Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
  10839. for (n = 0; n < len; ++n)
  10840. ucs2[n] = fill_char;
  10841. } else {
  10842. Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
  10843. assert(kind == PyUnicode_4BYTE_KIND);
  10844. for (n = 0; n < len; ++n)
  10845. ucs4[n] = fill_char;
  10846. }
  10847. }
  10848. else {
  10849. Py_ssize_t char_size = PyUnicode_KIND(str);
  10850. char *to = (char *) PyUnicode_DATA(u);
  10851. _PyBytes_Repeat(to, nchars * char_size, PyUnicode_DATA(str),
  10852. PyUnicode_GET_LENGTH(str) * char_size);
  10853. }
  10854. assert(_PyUnicode_CheckConsistency(u, 1));
  10855. return u;
  10856. }
  10857. PyObject *
  10858. PyUnicode_Replace(PyObject *str,
  10859. PyObject *substr,
  10860. PyObject *replstr,
  10861. Py_ssize_t maxcount)
  10862. {
  10863. if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
  10864. ensure_unicode(replstr) < 0)
  10865. return NULL;
  10866. return replace(str, substr, replstr, maxcount);
  10867. }
  10868. /*[clinic input]
  10869. str.replace as unicode_replace
  10870. old: unicode
  10871. new: unicode
  10872. count: Py_ssize_t = -1
  10873. Maximum number of occurrences to replace.
  10874. -1 (the default value) means replace all occurrences.
  10875. /
  10876. Return a copy with all occurrences of substring old replaced by new.
  10877. If the optional argument count is given, only the first count occurrences are
  10878. replaced.
  10879. [clinic start generated code]*/
  10880. static PyObject *
  10881. unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
  10882. Py_ssize_t count)
  10883. /*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
  10884. {
  10885. return replace(self, old, new, count);
  10886. }
  10887. /*[clinic input]
  10888. str.removeprefix as unicode_removeprefix
  10889. prefix: unicode
  10890. /
  10891. Return a str with the given prefix string removed if present.
  10892. If the string starts with the prefix string, return string[len(prefix):].
  10893. Otherwise, return a copy of the original string.
  10894. [clinic start generated code]*/
  10895. static PyObject *
  10896. unicode_removeprefix_impl(PyObject *self, PyObject *prefix)
  10897. /*[clinic end generated code: output=f1e5945e9763bcb9 input=27ec40b99a37eb88]*/
  10898. {
  10899. int match = tailmatch(self, prefix, 0, PY_SSIZE_T_MAX, -1);
  10900. if (match == -1) {
  10901. return NULL;
  10902. }
  10903. if (match) {
  10904. return PyUnicode_Substring(self, PyUnicode_GET_LENGTH(prefix),
  10905. PyUnicode_GET_LENGTH(self));
  10906. }
  10907. return unicode_result_unchanged(self);
  10908. }
  10909. /*[clinic input]
  10910. str.removesuffix as unicode_removesuffix
  10911. suffix: unicode
  10912. /
  10913. Return a str with the given suffix string removed if present.
  10914. If the string ends with the suffix string and that suffix is not empty,
  10915. return string[:-len(suffix)]. Otherwise, return a copy of the original
  10916. string.
  10917. [clinic start generated code]*/
  10918. static PyObject *
  10919. unicode_removesuffix_impl(PyObject *self, PyObject *suffix)
  10920. /*[clinic end generated code: output=d36629e227636822 input=12cc32561e769be4]*/
  10921. {
  10922. int match = tailmatch(self, suffix, 0, PY_SSIZE_T_MAX, +1);
  10923. if (match == -1) {
  10924. return NULL;
  10925. }
  10926. if (match) {
  10927. return PyUnicode_Substring(self, 0, PyUnicode_GET_LENGTH(self)
  10928. - PyUnicode_GET_LENGTH(suffix));
  10929. }
  10930. return unicode_result_unchanged(self);
  10931. }
  10932. static PyObject *
  10933. unicode_repr(PyObject *unicode)
  10934. {
  10935. PyObject *repr;
  10936. Py_ssize_t isize;
  10937. Py_ssize_t osize, squote, dquote, i, o;
  10938. Py_UCS4 max, quote;
  10939. int ikind, okind, unchanged;
  10940. const void *idata;
  10941. void *odata;
  10942. isize = PyUnicode_GET_LENGTH(unicode);
  10943. idata = PyUnicode_DATA(unicode);
  10944. /* Compute length of output, quote characters, and
  10945. maximum character */
  10946. osize = 0;
  10947. max = 127;
  10948. squote = dquote = 0;
  10949. ikind = PyUnicode_KIND(unicode);
  10950. for (i = 0; i < isize; i++) {
  10951. Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
  10952. Py_ssize_t incr = 1;
  10953. switch (ch) {
  10954. case '\'': squote++; break;
  10955. case '"': dquote++; break;
  10956. case '\\': case '\t': case '\r': case '\n':
  10957. incr = 2;
  10958. break;
  10959. default:
  10960. /* Fast-path ASCII */
  10961. if (ch < ' ' || ch == 0x7f)
  10962. incr = 4; /* \xHH */
  10963. else if (ch < 0x7f)
  10964. ;
  10965. else if (Py_UNICODE_ISPRINTABLE(ch))
  10966. max = ch > max ? ch : max;
  10967. else if (ch < 0x100)
  10968. incr = 4; /* \xHH */
  10969. else if (ch < 0x10000)
  10970. incr = 6; /* \uHHHH */
  10971. else
  10972. incr = 10; /* \uHHHHHHHH */
  10973. }
  10974. if (osize > PY_SSIZE_T_MAX - incr) {
  10975. PyErr_SetString(PyExc_OverflowError,
  10976. "string is too long to generate repr");
  10977. return NULL;
  10978. }
  10979. osize += incr;
  10980. }
  10981. quote = '\'';
  10982. unchanged = (osize == isize);
  10983. if (squote) {
  10984. unchanged = 0;
  10985. if (dquote)
  10986. /* Both squote and dquote present. Use squote,
  10987. and escape them */
  10988. osize += squote;
  10989. else
  10990. quote = '"';
  10991. }
  10992. osize += 2; /* quotes */
  10993. repr = PyUnicode_New(osize, max);
  10994. if (repr == NULL)
  10995. return NULL;
  10996. okind = PyUnicode_KIND(repr);
  10997. odata = PyUnicode_DATA(repr);
  10998. PyUnicode_WRITE(okind, odata, 0, quote);
  10999. PyUnicode_WRITE(okind, odata, osize-1, quote);
  11000. if (unchanged) {
  11001. _PyUnicode_FastCopyCharacters(repr, 1,
  11002. unicode, 0,
  11003. isize);
  11004. }
  11005. else {
  11006. for (i = 0, o = 1; i < isize; i++) {
  11007. Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
  11008. /* Escape quotes and backslashes */
  11009. if ((ch == quote) || (ch == '\\')) {
  11010. PyUnicode_WRITE(okind, odata, o++, '\\');
  11011. PyUnicode_WRITE(okind, odata, o++, ch);
  11012. continue;
  11013. }
  11014. /* Map special whitespace to '\t', \n', '\r' */
  11015. if (ch == '\t') {
  11016. PyUnicode_WRITE(okind, odata, o++, '\\');
  11017. PyUnicode_WRITE(okind, odata, o++, 't');
  11018. }
  11019. else if (ch == '\n') {
  11020. PyUnicode_WRITE(okind, odata, o++, '\\');
  11021. PyUnicode_WRITE(okind, odata, o++, 'n');
  11022. }
  11023. else if (ch == '\r') {
  11024. PyUnicode_WRITE(okind, odata, o++, '\\');
  11025. PyUnicode_WRITE(okind, odata, o++, 'r');
  11026. }
  11027. /* Map non-printable US ASCII to '\xhh' */
  11028. else if (ch < ' ' || ch == 0x7F) {
  11029. PyUnicode_WRITE(okind, odata, o++, '\\');
  11030. PyUnicode_WRITE(okind, odata, o++, 'x');
  11031. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
  11032. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
  11033. }
  11034. /* Copy ASCII characters as-is */
  11035. else if (ch < 0x7F) {
  11036. PyUnicode_WRITE(okind, odata, o++, ch);
  11037. }
  11038. /* Non-ASCII characters */
  11039. else {
  11040. /* Map Unicode whitespace and control characters
  11041. (categories Z* and C* except ASCII space)
  11042. */
  11043. if (!Py_UNICODE_ISPRINTABLE(ch)) {
  11044. PyUnicode_WRITE(okind, odata, o++, '\\');
  11045. /* Map 8-bit characters to '\xhh' */
  11046. if (ch <= 0xff) {
  11047. PyUnicode_WRITE(okind, odata, o++, 'x');
  11048. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
  11049. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
  11050. }
  11051. /* Map 16-bit characters to '\uxxxx' */
  11052. else if (ch <= 0xffff) {
  11053. PyUnicode_WRITE(okind, odata, o++, 'u');
  11054. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
  11055. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
  11056. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
  11057. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
  11058. }
  11059. /* Map 21-bit characters to '\U00xxxxxx' */
  11060. else {
  11061. PyUnicode_WRITE(okind, odata, o++, 'U');
  11062. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
  11063. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
  11064. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
  11065. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
  11066. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
  11067. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
  11068. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
  11069. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
  11070. }
  11071. }
  11072. /* Copy characters as-is */
  11073. else {
  11074. PyUnicode_WRITE(okind, odata, o++, ch);
  11075. }
  11076. }
  11077. }
  11078. }
  11079. /* Closing quote already added at the beginning */
  11080. assert(_PyUnicode_CheckConsistency(repr, 1));
  11081. return repr;
  11082. }
  11083. PyDoc_STRVAR(rfind__doc__,
  11084. "S.rfind(sub[, start[, end]]) -> int\n\
  11085. \n\
  11086. Return the highest index in S where substring sub is found,\n\
  11087. such that sub is contained within S[start:end]. Optional\n\
  11088. arguments start and end are interpreted as in slice notation.\n\
  11089. \n\
  11090. Return -1 on failure.");
  11091. static PyObject *
  11092. unicode_rfind(PyObject *self, PyObject *args)
  11093. {
  11094. /* initialize variables to prevent gcc warning */
  11095. PyObject *substring = NULL;
  11096. Py_ssize_t start = 0;
  11097. Py_ssize_t end = 0;
  11098. Py_ssize_t result;
  11099. if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
  11100. return NULL;
  11101. result = any_find_slice(self, substring, start, end, -1);
  11102. if (result == -2)
  11103. return NULL;
  11104. return PyLong_FromSsize_t(result);
  11105. }
  11106. PyDoc_STRVAR(rindex__doc__,
  11107. "S.rindex(sub[, start[, end]]) -> int\n\
  11108. \n\
  11109. Return the highest index in S where substring sub is found,\n\
  11110. such that sub is contained within S[start:end]. Optional\n\
  11111. arguments start and end are interpreted as in slice notation.\n\
  11112. \n\
  11113. Raises ValueError when the substring is not found.");
  11114. static PyObject *
  11115. unicode_rindex(PyObject *self, PyObject *args)
  11116. {
  11117. /* initialize variables to prevent gcc warning */
  11118. PyObject *substring = NULL;
  11119. Py_ssize_t start = 0;
  11120. Py_ssize_t end = 0;
  11121. Py_ssize_t result;
  11122. if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
  11123. return NULL;
  11124. result = any_find_slice(self, substring, start, end, -1);
  11125. if (result == -2)
  11126. return NULL;
  11127. if (result < 0) {
  11128. PyErr_SetString(PyExc_ValueError, "substring not found");
  11129. return NULL;
  11130. }
  11131. return PyLong_FromSsize_t(result);
  11132. }
  11133. /*[clinic input]
  11134. str.rjust as unicode_rjust
  11135. width: Py_ssize_t
  11136. fillchar: Py_UCS4 = ' '
  11137. /
  11138. Return a right-justified string of length width.
  11139. Padding is done using the specified fill character (default is a space).
  11140. [clinic start generated code]*/
  11141. static PyObject *
  11142. unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
  11143. /*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
  11144. {
  11145. if (PyUnicode_GET_LENGTH(self) >= width)
  11146. return unicode_result_unchanged(self);
  11147. return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
  11148. }
  11149. PyObject *
  11150. PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
  11151. {
  11152. if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
  11153. return NULL;
  11154. return split(s, sep, maxsplit);
  11155. }
  11156. /*[clinic input]
  11157. str.split as unicode_split
  11158. sep: object = None
  11159. The separator used to split the string.
  11160. When set to None (the default value), will split on any whitespace
  11161. character (including \n \r \t \f and spaces) and will discard
  11162. empty strings from the result.
  11163. maxsplit: Py_ssize_t = -1
  11164. Maximum number of splits.
  11165. -1 (the default value) means no limit.
  11166. Return a list of the substrings in the string, using sep as the separator string.
  11167. Splitting starts at the front of the string and works to the end.
  11168. Note, str.split() is mainly useful for data that has been intentionally
  11169. delimited. With natural text that includes punctuation, consider using
  11170. the regular expression module.
  11171. [clinic start generated code]*/
  11172. static PyObject *
  11173. unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
  11174. /*[clinic end generated code: output=3a65b1db356948dc input=a29bcc0c7a5af0eb]*/
  11175. {
  11176. if (sep == Py_None)
  11177. return split(self, NULL, maxsplit);
  11178. if (PyUnicode_Check(sep))
  11179. return split(self, sep, maxsplit);
  11180. PyErr_Format(PyExc_TypeError,
  11181. "must be str or None, not %.100s",
  11182. Py_TYPE(sep)->tp_name);
  11183. return NULL;
  11184. }
  11185. PyObject *
  11186. PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
  11187. {
  11188. PyObject* out;
  11189. int kind1, kind2;
  11190. const void *buf1, *buf2;
  11191. Py_ssize_t len1, len2;
  11192. if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
  11193. return NULL;
  11194. kind1 = PyUnicode_KIND(str_obj);
  11195. kind2 = PyUnicode_KIND(sep_obj);
  11196. len1 = PyUnicode_GET_LENGTH(str_obj);
  11197. len2 = PyUnicode_GET_LENGTH(sep_obj);
  11198. if (kind1 < kind2 || len1 < len2) {
  11199. PyObject *empty = unicode_get_empty(); // Borrowed reference
  11200. return PyTuple_Pack(3, str_obj, empty, empty);
  11201. }
  11202. buf1 = PyUnicode_DATA(str_obj);
  11203. buf2 = PyUnicode_DATA(sep_obj);
  11204. if (kind2 != kind1) {
  11205. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  11206. if (!buf2)
  11207. return NULL;
  11208. }
  11209. switch (kind1) {
  11210. case PyUnicode_1BYTE_KIND:
  11211. if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
  11212. out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11213. else
  11214. out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11215. break;
  11216. case PyUnicode_2BYTE_KIND:
  11217. out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11218. break;
  11219. case PyUnicode_4BYTE_KIND:
  11220. out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11221. break;
  11222. default:
  11223. Py_UNREACHABLE();
  11224. }
  11225. assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
  11226. if (kind2 != kind1)
  11227. PyMem_Free((void *)buf2);
  11228. return out;
  11229. }
  11230. PyObject *
  11231. PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
  11232. {
  11233. PyObject* out;
  11234. int kind1, kind2;
  11235. const void *buf1, *buf2;
  11236. Py_ssize_t len1, len2;
  11237. if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
  11238. return NULL;
  11239. kind1 = PyUnicode_KIND(str_obj);
  11240. kind2 = PyUnicode_KIND(sep_obj);
  11241. len1 = PyUnicode_GET_LENGTH(str_obj);
  11242. len2 = PyUnicode_GET_LENGTH(sep_obj);
  11243. if (kind1 < kind2 || len1 < len2) {
  11244. PyObject *empty = unicode_get_empty(); // Borrowed reference
  11245. return PyTuple_Pack(3, empty, empty, str_obj);
  11246. }
  11247. buf1 = PyUnicode_DATA(str_obj);
  11248. buf2 = PyUnicode_DATA(sep_obj);
  11249. if (kind2 != kind1) {
  11250. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  11251. if (!buf2)
  11252. return NULL;
  11253. }
  11254. switch (kind1) {
  11255. case PyUnicode_1BYTE_KIND:
  11256. if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
  11257. out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11258. else
  11259. out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11260. break;
  11261. case PyUnicode_2BYTE_KIND:
  11262. out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11263. break;
  11264. case PyUnicode_4BYTE_KIND:
  11265. out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11266. break;
  11267. default:
  11268. Py_UNREACHABLE();
  11269. }
  11270. assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
  11271. if (kind2 != kind1)
  11272. PyMem_Free((void *)buf2);
  11273. return out;
  11274. }
  11275. /*[clinic input]
  11276. str.partition as unicode_partition
  11277. sep: object
  11278. /
  11279. Partition the string into three parts using the given separator.
  11280. This will search for the separator in the string. If the separator is found,
  11281. returns a 3-tuple containing the part before the separator, the separator
  11282. itself, and the part after it.
  11283. If the separator is not found, returns a 3-tuple containing the original string
  11284. and two empty strings.
  11285. [clinic start generated code]*/
  11286. static PyObject *
  11287. unicode_partition(PyObject *self, PyObject *sep)
  11288. /*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
  11289. {
  11290. return PyUnicode_Partition(self, sep);
  11291. }
  11292. /*[clinic input]
  11293. str.rpartition as unicode_rpartition = str.partition
  11294. Partition the string into three parts using the given separator.
  11295. This will search for the separator in the string, starting at the end. If
  11296. the separator is found, returns a 3-tuple containing the part before the
  11297. separator, the separator itself, and the part after it.
  11298. If the separator is not found, returns a 3-tuple containing two empty strings
  11299. and the original string.
  11300. [clinic start generated code]*/
  11301. static PyObject *
  11302. unicode_rpartition(PyObject *self, PyObject *sep)
  11303. /*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
  11304. {
  11305. return PyUnicode_RPartition(self, sep);
  11306. }
  11307. PyObject *
  11308. PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
  11309. {
  11310. if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
  11311. return NULL;
  11312. return rsplit(s, sep, maxsplit);
  11313. }
  11314. /*[clinic input]
  11315. str.rsplit as unicode_rsplit = str.split
  11316. Return a list of the substrings in the string, using sep as the separator string.
  11317. Splitting starts at the end of the string and works to the front.
  11318. [clinic start generated code]*/
  11319. static PyObject *
  11320. unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
  11321. /*[clinic end generated code: output=c2b815c63bcabffc input=ea78406060fce33c]*/
  11322. {
  11323. if (sep == Py_None)
  11324. return rsplit(self, NULL, maxsplit);
  11325. if (PyUnicode_Check(sep))
  11326. return rsplit(self, sep, maxsplit);
  11327. PyErr_Format(PyExc_TypeError,
  11328. "must be str or None, not %.100s",
  11329. Py_TYPE(sep)->tp_name);
  11330. return NULL;
  11331. }
  11332. /*[clinic input]
  11333. str.splitlines as unicode_splitlines
  11334. keepends: bool = False
  11335. Return a list of the lines in the string, breaking at line boundaries.
  11336. Line breaks are not included in the resulting list unless keepends is given and
  11337. true.
  11338. [clinic start generated code]*/
  11339. static PyObject *
  11340. unicode_splitlines_impl(PyObject *self, int keepends)
  11341. /*[clinic end generated code: output=f664dcdad153ec40 input=ba6ad05ee85d2b55]*/
  11342. {
  11343. return PyUnicode_Splitlines(self, keepends);
  11344. }
  11345. static
  11346. PyObject *unicode_str(PyObject *self)
  11347. {
  11348. return unicode_result_unchanged(self);
  11349. }
  11350. /*[clinic input]
  11351. str.swapcase as unicode_swapcase
  11352. Convert uppercase characters to lowercase and lowercase characters to uppercase.
  11353. [clinic start generated code]*/
  11354. static PyObject *
  11355. unicode_swapcase_impl(PyObject *self)
  11356. /*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
  11357. {
  11358. return case_operation(self, do_swapcase);
  11359. }
  11360. /*[clinic input]
  11361. @staticmethod
  11362. str.maketrans as unicode_maketrans
  11363. x: object
  11364. y: unicode=NULL
  11365. z: unicode=NULL
  11366. /
  11367. Return a translation table usable for str.translate().
  11368. If there is only one argument, it must be a dictionary mapping Unicode
  11369. ordinals (integers) or characters to Unicode ordinals, strings or None.
  11370. Character keys will be then converted to ordinals.
  11371. If there are two arguments, they must be strings of equal length, and
  11372. in the resulting dictionary, each character in x will be mapped to the
  11373. character at the same position in y. If there is a third argument, it
  11374. must be a string, whose characters will be mapped to None in the result.
  11375. [clinic start generated code]*/
  11376. static PyObject *
  11377. unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
  11378. /*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
  11379. {
  11380. PyObject *new = NULL, *key, *value;
  11381. Py_ssize_t i = 0;
  11382. int res;
  11383. new = PyDict_New();
  11384. if (!new)
  11385. return NULL;
  11386. if (y != NULL) {
  11387. int x_kind, y_kind, z_kind;
  11388. const void *x_data, *y_data, *z_data;
  11389. /* x must be a string too, of equal length */
  11390. if (!PyUnicode_Check(x)) {
  11391. PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
  11392. "be a string if there is a second argument");
  11393. goto err;
  11394. }
  11395. if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
  11396. PyErr_SetString(PyExc_ValueError, "the first two maketrans "
  11397. "arguments must have equal length");
  11398. goto err;
  11399. }
  11400. /* create entries for translating chars in x to those in y */
  11401. x_kind = PyUnicode_KIND(x);
  11402. y_kind = PyUnicode_KIND(y);
  11403. x_data = PyUnicode_DATA(x);
  11404. y_data = PyUnicode_DATA(y);
  11405. for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
  11406. key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
  11407. if (!key)
  11408. goto err;
  11409. value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
  11410. if (!value) {
  11411. Py_DECREF(key);
  11412. goto err;
  11413. }
  11414. res = PyDict_SetItem(new, key, value);
  11415. Py_DECREF(key);
  11416. Py_DECREF(value);
  11417. if (res < 0)
  11418. goto err;
  11419. }
  11420. /* create entries for deleting chars in z */
  11421. if (z != NULL) {
  11422. z_kind = PyUnicode_KIND(z);
  11423. z_data = PyUnicode_DATA(z);
  11424. for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
  11425. key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
  11426. if (!key)
  11427. goto err;
  11428. res = PyDict_SetItem(new, key, Py_None);
  11429. Py_DECREF(key);
  11430. if (res < 0)
  11431. goto err;
  11432. }
  11433. }
  11434. } else {
  11435. int kind;
  11436. const void *data;
  11437. /* x must be a dict */
  11438. if (!PyDict_CheckExact(x)) {
  11439. PyErr_SetString(PyExc_TypeError, "if you give only one argument "
  11440. "to maketrans it must be a dict");
  11441. goto err;
  11442. }
  11443. /* copy entries into the new dict, converting string keys to int keys */
  11444. while (PyDict_Next(x, &i, &key, &value)) {
  11445. if (PyUnicode_Check(key)) {
  11446. /* convert string keys to integer keys */
  11447. PyObject *newkey;
  11448. if (PyUnicode_GET_LENGTH(key) != 1) {
  11449. PyErr_SetString(PyExc_ValueError, "string keys in translate "
  11450. "table must be of length 1");
  11451. goto err;
  11452. }
  11453. kind = PyUnicode_KIND(key);
  11454. data = PyUnicode_DATA(key);
  11455. newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
  11456. if (!newkey)
  11457. goto err;
  11458. res = PyDict_SetItem(new, newkey, value);
  11459. Py_DECREF(newkey);
  11460. if (res < 0)
  11461. goto err;
  11462. } else if (PyLong_Check(key)) {
  11463. /* just keep integer keys */
  11464. if (PyDict_SetItem(new, key, value) < 0)
  11465. goto err;
  11466. } else {
  11467. PyErr_SetString(PyExc_TypeError, "keys in translate table must "
  11468. "be strings or integers");
  11469. goto err;
  11470. }
  11471. }
  11472. }
  11473. return new;
  11474. err:
  11475. Py_DECREF(new);
  11476. return NULL;
  11477. }
  11478. /*[clinic input]
  11479. str.translate as unicode_translate
  11480. table: object
  11481. Translation table, which must be a mapping of Unicode ordinals to
  11482. Unicode ordinals, strings, or None.
  11483. /
  11484. Replace each character in the string using the given translation table.
  11485. The table must implement lookup/indexing via __getitem__, for instance a
  11486. dictionary or list. If this operation raises LookupError, the character is
  11487. left untouched. Characters mapped to None are deleted.
  11488. [clinic start generated code]*/
  11489. static PyObject *
  11490. unicode_translate(PyObject *self, PyObject *table)
  11491. /*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
  11492. {
  11493. return _PyUnicode_TranslateCharmap(self, table, "ignore");
  11494. }
  11495. /*[clinic input]
  11496. str.upper as unicode_upper
  11497. Return a copy of the string converted to uppercase.
  11498. [clinic start generated code]*/
  11499. static PyObject *
  11500. unicode_upper_impl(PyObject *self)
  11501. /*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
  11502. {
  11503. if (PyUnicode_IS_ASCII(self))
  11504. return ascii_upper_or_lower(self, 0);
  11505. return case_operation(self, do_upper);
  11506. }
  11507. /*[clinic input]
  11508. str.zfill as unicode_zfill
  11509. width: Py_ssize_t
  11510. /
  11511. Pad a numeric string with zeros on the left, to fill a field of the given width.
  11512. The string is never truncated.
  11513. [clinic start generated code]*/
  11514. static PyObject *
  11515. unicode_zfill_impl(PyObject *self, Py_ssize_t width)
  11516. /*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
  11517. {
  11518. Py_ssize_t fill;
  11519. PyObject *u;
  11520. int kind;
  11521. const void *data;
  11522. Py_UCS4 chr;
  11523. if (PyUnicode_GET_LENGTH(self) >= width)
  11524. return unicode_result_unchanged(self);
  11525. fill = width - PyUnicode_GET_LENGTH(self);
  11526. u = pad(self, fill, 0, '0');
  11527. if (u == NULL)
  11528. return NULL;
  11529. kind = PyUnicode_KIND(u);
  11530. data = PyUnicode_DATA(u);
  11531. chr = PyUnicode_READ(kind, data, fill);
  11532. if (chr == '+' || chr == '-') {
  11533. /* move sign to beginning of string */
  11534. PyUnicode_WRITE(kind, data, 0, chr);
  11535. PyUnicode_WRITE(kind, data, fill, '0');
  11536. }
  11537. assert(_PyUnicode_CheckConsistency(u, 1));
  11538. return u;
  11539. }
  11540. PyDoc_STRVAR(startswith__doc__,
  11541. "S.startswith(prefix[, start[, end]]) -> bool\n\
  11542. \n\
  11543. Return True if S starts with the specified prefix, False otherwise.\n\
  11544. With optional start, test S beginning at that position.\n\
  11545. With optional end, stop comparing S at that position.\n\
  11546. prefix can also be a tuple of strings to try.");
  11547. static PyObject *
  11548. unicode_startswith(PyObject *self,
  11549. PyObject *args)
  11550. {
  11551. PyObject *subobj;
  11552. PyObject *substring;
  11553. Py_ssize_t start = 0;
  11554. Py_ssize_t end = PY_SSIZE_T_MAX;
  11555. int result;
  11556. if (!asciilib_parse_args_finds("startswith", args, &subobj, &start, &end))
  11557. return NULL;
  11558. if (PyTuple_Check(subobj)) {
  11559. Py_ssize_t i;
  11560. for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
  11561. substring = PyTuple_GET_ITEM(subobj, i);
  11562. if (!PyUnicode_Check(substring)) {
  11563. PyErr_Format(PyExc_TypeError,
  11564. "tuple for startswith must only contain str, "
  11565. "not %.100s",
  11566. Py_TYPE(substring)->tp_name);
  11567. return NULL;
  11568. }
  11569. result = tailmatch(self, substring, start, end, -1);
  11570. if (result == -1)
  11571. return NULL;
  11572. if (result) {
  11573. Py_RETURN_TRUE;
  11574. }
  11575. }
  11576. /* nothing matched */
  11577. Py_RETURN_FALSE;
  11578. }
  11579. if (!PyUnicode_Check(subobj)) {
  11580. PyErr_Format(PyExc_TypeError,
  11581. "startswith first arg must be str or "
  11582. "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
  11583. return NULL;
  11584. }
  11585. result = tailmatch(self, subobj, start, end, -1);
  11586. if (result == -1)
  11587. return NULL;
  11588. return PyBool_FromLong(result);
  11589. }
  11590. PyDoc_STRVAR(endswith__doc__,
  11591. "S.endswith(suffix[, start[, end]]) -> bool\n\
  11592. \n\
  11593. Return True if S ends with the specified suffix, False otherwise.\n\
  11594. With optional start, test S beginning at that position.\n\
  11595. With optional end, stop comparing S at that position.\n\
  11596. suffix can also be a tuple of strings to try.");
  11597. static PyObject *
  11598. unicode_endswith(PyObject *self,
  11599. PyObject *args)
  11600. {
  11601. PyObject *subobj;
  11602. PyObject *substring;
  11603. Py_ssize_t start = 0;
  11604. Py_ssize_t end = PY_SSIZE_T_MAX;
  11605. int result;
  11606. if (!asciilib_parse_args_finds("endswith", args, &subobj, &start, &end))
  11607. return NULL;
  11608. if (PyTuple_Check(subobj)) {
  11609. Py_ssize_t i;
  11610. for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
  11611. substring = PyTuple_GET_ITEM(subobj, i);
  11612. if (!PyUnicode_Check(substring)) {
  11613. PyErr_Format(PyExc_TypeError,
  11614. "tuple for endswith must only contain str, "
  11615. "not %.100s",
  11616. Py_TYPE(substring)->tp_name);
  11617. return NULL;
  11618. }
  11619. result = tailmatch(self, substring, start, end, +1);
  11620. if (result == -1)
  11621. return NULL;
  11622. if (result) {
  11623. Py_RETURN_TRUE;
  11624. }
  11625. }
  11626. Py_RETURN_FALSE;
  11627. }
  11628. if (!PyUnicode_Check(subobj)) {
  11629. PyErr_Format(PyExc_TypeError,
  11630. "endswith first arg must be str or "
  11631. "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
  11632. return NULL;
  11633. }
  11634. result = tailmatch(self, subobj, start, end, +1);
  11635. if (result == -1)
  11636. return NULL;
  11637. return PyBool_FromLong(result);
  11638. }
  11639. static inline void
  11640. _PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
  11641. {
  11642. writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
  11643. writer->data = PyUnicode_DATA(writer->buffer);
  11644. if (!writer->readonly) {
  11645. writer->kind = PyUnicode_KIND(writer->buffer);
  11646. writer->size = PyUnicode_GET_LENGTH(writer->buffer);
  11647. }
  11648. else {
  11649. /* use a value smaller than PyUnicode_1BYTE_KIND() so
  11650. _PyUnicodeWriter_PrepareKind() will copy the buffer. */
  11651. writer->kind = 0;
  11652. assert(writer->kind <= PyUnicode_1BYTE_KIND);
  11653. /* Copy-on-write mode: set buffer size to 0 so
  11654. * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
  11655. * next write. */
  11656. writer->size = 0;
  11657. }
  11658. }
  11659. void
  11660. _PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
  11661. {
  11662. memset(writer, 0, sizeof(*writer));
  11663. /* ASCII is the bare minimum */
  11664. writer->min_char = 127;
  11665. /* use a value smaller than PyUnicode_1BYTE_KIND() so
  11666. _PyUnicodeWriter_PrepareKind() will copy the buffer. */
  11667. writer->kind = 0;
  11668. assert(writer->kind <= PyUnicode_1BYTE_KIND);
  11669. }
  11670. // Initialize _PyUnicodeWriter with initial buffer
  11671. static inline void
  11672. _PyUnicodeWriter_InitWithBuffer(_PyUnicodeWriter *writer, PyObject *buffer)
  11673. {
  11674. memset(writer, 0, sizeof(*writer));
  11675. writer->buffer = buffer;
  11676. _PyUnicodeWriter_Update(writer);
  11677. writer->min_length = writer->size;
  11678. }
  11679. int
  11680. _PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
  11681. Py_ssize_t length, Py_UCS4 maxchar)
  11682. {
  11683. Py_ssize_t newlen;
  11684. PyObject *newbuffer;
  11685. assert(maxchar <= MAX_UNICODE);
  11686. /* ensure that the _PyUnicodeWriter_Prepare macro was used */
  11687. assert((maxchar > writer->maxchar && length >= 0)
  11688. || length > 0);
  11689. if (length > PY_SSIZE_T_MAX - writer->pos) {
  11690. PyErr_NoMemory();
  11691. return -1;
  11692. }
  11693. newlen = writer->pos + length;
  11694. maxchar = Py_MAX(maxchar, writer->min_char);
  11695. if (writer->buffer == NULL) {
  11696. assert(!writer->readonly);
  11697. if (writer->overallocate
  11698. && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
  11699. /* overallocate to limit the number of realloc() */
  11700. newlen += newlen / OVERALLOCATE_FACTOR;
  11701. }
  11702. if (newlen < writer->min_length)
  11703. newlen = writer->min_length;
  11704. writer->buffer = PyUnicode_New(newlen, maxchar);
  11705. if (writer->buffer == NULL)
  11706. return -1;
  11707. }
  11708. else if (newlen > writer->size) {
  11709. if (writer->overallocate
  11710. && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
  11711. /* overallocate to limit the number of realloc() */
  11712. newlen += newlen / OVERALLOCATE_FACTOR;
  11713. }
  11714. if (newlen < writer->min_length)
  11715. newlen = writer->min_length;
  11716. if (maxchar > writer->maxchar || writer->readonly) {
  11717. /* resize + widen */
  11718. maxchar = Py_MAX(maxchar, writer->maxchar);
  11719. newbuffer = PyUnicode_New(newlen, maxchar);
  11720. if (newbuffer == NULL)
  11721. return -1;
  11722. _PyUnicode_FastCopyCharacters(newbuffer, 0,
  11723. writer->buffer, 0, writer->pos);
  11724. Py_DECREF(writer->buffer);
  11725. writer->readonly = 0;
  11726. }
  11727. else {
  11728. newbuffer = resize_compact(writer->buffer, newlen);
  11729. if (newbuffer == NULL)
  11730. return -1;
  11731. }
  11732. writer->buffer = newbuffer;
  11733. }
  11734. else if (maxchar > writer->maxchar) {
  11735. assert(!writer->readonly);
  11736. newbuffer = PyUnicode_New(writer->size, maxchar);
  11737. if (newbuffer == NULL)
  11738. return -1;
  11739. _PyUnicode_FastCopyCharacters(newbuffer, 0,
  11740. writer->buffer, 0, writer->pos);
  11741. Py_SETREF(writer->buffer, newbuffer);
  11742. }
  11743. _PyUnicodeWriter_Update(writer);
  11744. return 0;
  11745. #undef OVERALLOCATE_FACTOR
  11746. }
  11747. int
  11748. _PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
  11749. int kind)
  11750. {
  11751. Py_UCS4 maxchar;
  11752. /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
  11753. assert(writer->kind < kind);
  11754. switch (kind)
  11755. {
  11756. case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
  11757. case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
  11758. case PyUnicode_4BYTE_KIND: maxchar = MAX_UNICODE; break;
  11759. default:
  11760. Py_UNREACHABLE();
  11761. }
  11762. return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
  11763. }
  11764. static inline int
  11765. _PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
  11766. {
  11767. assert(ch <= MAX_UNICODE);
  11768. if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
  11769. return -1;
  11770. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
  11771. writer->pos++;
  11772. return 0;
  11773. }
  11774. int
  11775. _PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
  11776. {
  11777. return _PyUnicodeWriter_WriteCharInline(writer, ch);
  11778. }
  11779. int
  11780. _PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
  11781. {
  11782. Py_UCS4 maxchar;
  11783. Py_ssize_t len;
  11784. len = PyUnicode_GET_LENGTH(str);
  11785. if (len == 0)
  11786. return 0;
  11787. maxchar = PyUnicode_MAX_CHAR_VALUE(str);
  11788. if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
  11789. if (writer->buffer == NULL && !writer->overallocate) {
  11790. assert(_PyUnicode_CheckConsistency(str, 1));
  11791. writer->readonly = 1;
  11792. writer->buffer = Py_NewRef(str);
  11793. _PyUnicodeWriter_Update(writer);
  11794. writer->pos += len;
  11795. return 0;
  11796. }
  11797. if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
  11798. return -1;
  11799. }
  11800. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  11801. str, 0, len);
  11802. writer->pos += len;
  11803. return 0;
  11804. }
  11805. int
  11806. _PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
  11807. Py_ssize_t start, Py_ssize_t end)
  11808. {
  11809. Py_UCS4 maxchar;
  11810. Py_ssize_t len;
  11811. assert(0 <= start);
  11812. assert(end <= PyUnicode_GET_LENGTH(str));
  11813. assert(start <= end);
  11814. if (end == 0)
  11815. return 0;
  11816. if (start == 0 && end == PyUnicode_GET_LENGTH(str))
  11817. return _PyUnicodeWriter_WriteStr(writer, str);
  11818. if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
  11819. maxchar = _PyUnicode_FindMaxChar(str, start, end);
  11820. else
  11821. maxchar = writer->maxchar;
  11822. len = end - start;
  11823. if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
  11824. return -1;
  11825. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  11826. str, start, len);
  11827. writer->pos += len;
  11828. return 0;
  11829. }
  11830. int
  11831. _PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
  11832. const char *ascii, Py_ssize_t len)
  11833. {
  11834. if (len == -1)
  11835. len = strlen(ascii);
  11836. assert(ucs1lib_find_max_char((const Py_UCS1*)ascii, (const Py_UCS1*)ascii + len) < 128);
  11837. if (writer->buffer == NULL && !writer->overallocate) {
  11838. PyObject *str;
  11839. str = _PyUnicode_FromASCII(ascii, len);
  11840. if (str == NULL)
  11841. return -1;
  11842. writer->readonly = 1;
  11843. writer->buffer = str;
  11844. _PyUnicodeWriter_Update(writer);
  11845. writer->pos += len;
  11846. return 0;
  11847. }
  11848. if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
  11849. return -1;
  11850. switch (writer->kind)
  11851. {
  11852. case PyUnicode_1BYTE_KIND:
  11853. {
  11854. const Py_UCS1 *str = (const Py_UCS1 *)ascii;
  11855. Py_UCS1 *data = writer->data;
  11856. memcpy(data + writer->pos, str, len);
  11857. break;
  11858. }
  11859. case PyUnicode_2BYTE_KIND:
  11860. {
  11861. _PyUnicode_CONVERT_BYTES(
  11862. Py_UCS1, Py_UCS2,
  11863. ascii, ascii + len,
  11864. (Py_UCS2 *)writer->data + writer->pos);
  11865. break;
  11866. }
  11867. case PyUnicode_4BYTE_KIND:
  11868. {
  11869. _PyUnicode_CONVERT_BYTES(
  11870. Py_UCS1, Py_UCS4,
  11871. ascii, ascii + len,
  11872. (Py_UCS4 *)writer->data + writer->pos);
  11873. break;
  11874. }
  11875. default:
  11876. Py_UNREACHABLE();
  11877. }
  11878. writer->pos += len;
  11879. return 0;
  11880. }
  11881. int
  11882. _PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
  11883. const char *str, Py_ssize_t len)
  11884. {
  11885. Py_UCS4 maxchar;
  11886. maxchar = ucs1lib_find_max_char((const Py_UCS1*)str, (const Py_UCS1*)str + len);
  11887. if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
  11888. return -1;
  11889. unicode_write_cstr(writer->buffer, writer->pos, str, len);
  11890. writer->pos += len;
  11891. return 0;
  11892. }
  11893. PyObject *
  11894. _PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
  11895. {
  11896. PyObject *str;
  11897. if (writer->pos == 0) {
  11898. Py_CLEAR(writer->buffer);
  11899. _Py_RETURN_UNICODE_EMPTY();
  11900. }
  11901. str = writer->buffer;
  11902. writer->buffer = NULL;
  11903. if (writer->readonly) {
  11904. assert(PyUnicode_GET_LENGTH(str) == writer->pos);
  11905. return str;
  11906. }
  11907. if (PyUnicode_GET_LENGTH(str) != writer->pos) {
  11908. PyObject *str2;
  11909. str2 = resize_compact(str, writer->pos);
  11910. if (str2 == NULL) {
  11911. Py_DECREF(str);
  11912. return NULL;
  11913. }
  11914. str = str2;
  11915. }
  11916. assert(_PyUnicode_CheckConsistency(str, 1));
  11917. return unicode_result(str);
  11918. }
  11919. void
  11920. _PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
  11921. {
  11922. Py_CLEAR(writer->buffer);
  11923. }
  11924. #include "stringlib/unicode_format.h"
  11925. PyDoc_STRVAR(format__doc__,
  11926. "S.format(*args, **kwargs) -> str\n\
  11927. \n\
  11928. Return a formatted version of S, using substitutions from args and kwargs.\n\
  11929. The substitutions are identified by braces ('{' and '}').");
  11930. PyDoc_STRVAR(format_map__doc__,
  11931. "S.format_map(mapping) -> str\n\
  11932. \n\
  11933. Return a formatted version of S, using substitutions from mapping.\n\
  11934. The substitutions are identified by braces ('{' and '}').");
  11935. /*[clinic input]
  11936. str.__format__ as unicode___format__
  11937. format_spec: unicode
  11938. /
  11939. Return a formatted version of the string as described by format_spec.
  11940. [clinic start generated code]*/
  11941. static PyObject *
  11942. unicode___format___impl(PyObject *self, PyObject *format_spec)
  11943. /*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
  11944. {
  11945. _PyUnicodeWriter writer;
  11946. int ret;
  11947. _PyUnicodeWriter_Init(&writer);
  11948. ret = _PyUnicode_FormatAdvancedWriter(&writer,
  11949. self, format_spec, 0,
  11950. PyUnicode_GET_LENGTH(format_spec));
  11951. if (ret == -1) {
  11952. _PyUnicodeWriter_Dealloc(&writer);
  11953. return NULL;
  11954. }
  11955. return _PyUnicodeWriter_Finish(&writer);
  11956. }
  11957. /*[clinic input]
  11958. str.__sizeof__ as unicode_sizeof
  11959. Return the size of the string in memory, in bytes.
  11960. [clinic start generated code]*/
  11961. static PyObject *
  11962. unicode_sizeof_impl(PyObject *self)
  11963. /*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
  11964. {
  11965. Py_ssize_t size;
  11966. /* If it's a compact object, account for base structure +
  11967. character data. */
  11968. if (PyUnicode_IS_COMPACT_ASCII(self)) {
  11969. size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
  11970. }
  11971. else if (PyUnicode_IS_COMPACT(self)) {
  11972. size = sizeof(PyCompactUnicodeObject) +
  11973. (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
  11974. }
  11975. else {
  11976. /* If it is a two-block object, account for base object, and
  11977. for character block if present. */
  11978. size = sizeof(PyUnicodeObject);
  11979. if (_PyUnicode_DATA_ANY(self))
  11980. size += (PyUnicode_GET_LENGTH(self) + 1) *
  11981. PyUnicode_KIND(self);
  11982. }
  11983. if (_PyUnicode_HAS_UTF8_MEMORY(self))
  11984. size += PyUnicode_UTF8_LENGTH(self) + 1;
  11985. return PyLong_FromSsize_t(size);
  11986. }
  11987. static PyObject *
  11988. unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
  11989. {
  11990. PyObject *copy = _PyUnicode_Copy(v);
  11991. if (!copy)
  11992. return NULL;
  11993. return Py_BuildValue("(N)", copy);
  11994. }
  11995. static PyMethodDef unicode_methods[] = {
  11996. UNICODE_ENCODE_METHODDEF
  11997. UNICODE_REPLACE_METHODDEF
  11998. UNICODE_SPLIT_METHODDEF
  11999. UNICODE_RSPLIT_METHODDEF
  12000. UNICODE_JOIN_METHODDEF
  12001. UNICODE_CAPITALIZE_METHODDEF
  12002. UNICODE_CASEFOLD_METHODDEF
  12003. UNICODE_TITLE_METHODDEF
  12004. UNICODE_CENTER_METHODDEF
  12005. {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
  12006. UNICODE_EXPANDTABS_METHODDEF
  12007. {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
  12008. UNICODE_PARTITION_METHODDEF
  12009. {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
  12010. UNICODE_LJUST_METHODDEF
  12011. UNICODE_LOWER_METHODDEF
  12012. UNICODE_LSTRIP_METHODDEF
  12013. {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
  12014. {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
  12015. UNICODE_RJUST_METHODDEF
  12016. UNICODE_RSTRIP_METHODDEF
  12017. UNICODE_RPARTITION_METHODDEF
  12018. UNICODE_SPLITLINES_METHODDEF
  12019. UNICODE_STRIP_METHODDEF
  12020. UNICODE_SWAPCASE_METHODDEF
  12021. UNICODE_TRANSLATE_METHODDEF
  12022. UNICODE_UPPER_METHODDEF
  12023. {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
  12024. {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
  12025. UNICODE_REMOVEPREFIX_METHODDEF
  12026. UNICODE_REMOVESUFFIX_METHODDEF
  12027. UNICODE_ISASCII_METHODDEF
  12028. UNICODE_ISLOWER_METHODDEF
  12029. UNICODE_ISUPPER_METHODDEF
  12030. UNICODE_ISTITLE_METHODDEF
  12031. UNICODE_ISSPACE_METHODDEF
  12032. UNICODE_ISDECIMAL_METHODDEF
  12033. UNICODE_ISDIGIT_METHODDEF
  12034. UNICODE_ISNUMERIC_METHODDEF
  12035. UNICODE_ISALPHA_METHODDEF
  12036. UNICODE_ISALNUM_METHODDEF
  12037. UNICODE_ISIDENTIFIER_METHODDEF
  12038. UNICODE_ISPRINTABLE_METHODDEF
  12039. UNICODE_ZFILL_METHODDEF
  12040. {"format", _PyCFunction_CAST(do_string_format), METH_VARARGS | METH_KEYWORDS, format__doc__},
  12041. {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
  12042. UNICODE___FORMAT___METHODDEF
  12043. UNICODE_MAKETRANS_METHODDEF
  12044. UNICODE_SIZEOF_METHODDEF
  12045. {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
  12046. {NULL, NULL}
  12047. };
  12048. static PyObject *
  12049. unicode_mod(PyObject *v, PyObject *w)
  12050. {
  12051. if (!PyUnicode_Check(v))
  12052. Py_RETURN_NOTIMPLEMENTED;
  12053. return PyUnicode_Format(v, w);
  12054. }
  12055. static PyNumberMethods unicode_as_number = {
  12056. 0, /*nb_add*/
  12057. 0, /*nb_subtract*/
  12058. 0, /*nb_multiply*/
  12059. unicode_mod, /*nb_remainder*/
  12060. };
  12061. static PySequenceMethods unicode_as_sequence = {
  12062. (lenfunc) unicode_length, /* sq_length */
  12063. PyUnicode_Concat, /* sq_concat */
  12064. (ssizeargfunc) unicode_repeat, /* sq_repeat */
  12065. (ssizeargfunc) unicode_getitem, /* sq_item */
  12066. 0, /* sq_slice */
  12067. 0, /* sq_ass_item */
  12068. 0, /* sq_ass_slice */
  12069. PyUnicode_Contains, /* sq_contains */
  12070. };
  12071. static PyObject*
  12072. unicode_subscript(PyObject* self, PyObject* item)
  12073. {
  12074. if (_PyIndex_Check(item)) {
  12075. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  12076. if (i == -1 && PyErr_Occurred())
  12077. return NULL;
  12078. if (i < 0)
  12079. i += PyUnicode_GET_LENGTH(self);
  12080. return unicode_getitem(self, i);
  12081. } else if (PySlice_Check(item)) {
  12082. Py_ssize_t start, stop, step, slicelength, i;
  12083. size_t cur;
  12084. PyObject *result;
  12085. const void *src_data;
  12086. void *dest_data;
  12087. int src_kind, dest_kind;
  12088. Py_UCS4 ch, max_char, kind_limit;
  12089. if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
  12090. return NULL;
  12091. }
  12092. slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
  12093. &start, &stop, step);
  12094. if (slicelength <= 0) {
  12095. _Py_RETURN_UNICODE_EMPTY();
  12096. } else if (start == 0 && step == 1 &&
  12097. slicelength == PyUnicode_GET_LENGTH(self)) {
  12098. return unicode_result_unchanged(self);
  12099. } else if (step == 1) {
  12100. return PyUnicode_Substring(self,
  12101. start, start + slicelength);
  12102. }
  12103. /* General case */
  12104. src_kind = PyUnicode_KIND(self);
  12105. src_data = PyUnicode_DATA(self);
  12106. if (!PyUnicode_IS_ASCII(self)) {
  12107. kind_limit = kind_maxchar_limit(src_kind);
  12108. max_char = 0;
  12109. for (cur = start, i = 0; i < slicelength; cur += step, i++) {
  12110. ch = PyUnicode_READ(src_kind, src_data, cur);
  12111. if (ch > max_char) {
  12112. max_char = ch;
  12113. if (max_char >= kind_limit)
  12114. break;
  12115. }
  12116. }
  12117. }
  12118. else
  12119. max_char = 127;
  12120. result = PyUnicode_New(slicelength, max_char);
  12121. if (result == NULL)
  12122. return NULL;
  12123. dest_kind = PyUnicode_KIND(result);
  12124. dest_data = PyUnicode_DATA(result);
  12125. for (cur = start, i = 0; i < slicelength; cur += step, i++) {
  12126. Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
  12127. PyUnicode_WRITE(dest_kind, dest_data, i, ch);
  12128. }
  12129. assert(_PyUnicode_CheckConsistency(result, 1));
  12130. return result;
  12131. } else {
  12132. PyErr_Format(PyExc_TypeError, "string indices must be integers, not '%.200s'",
  12133. Py_TYPE(item)->tp_name);
  12134. return NULL;
  12135. }
  12136. }
  12137. static PyMappingMethods unicode_as_mapping = {
  12138. (lenfunc)unicode_length, /* mp_length */
  12139. (binaryfunc)unicode_subscript, /* mp_subscript */
  12140. (objobjargproc)0, /* mp_ass_subscript */
  12141. };
  12142. /* Helpers for PyUnicode_Format() */
  12143. struct unicode_formatter_t {
  12144. PyObject *args;
  12145. int args_owned;
  12146. Py_ssize_t arglen, argidx;
  12147. PyObject *dict;
  12148. int fmtkind;
  12149. Py_ssize_t fmtcnt, fmtpos;
  12150. const void *fmtdata;
  12151. PyObject *fmtstr;
  12152. _PyUnicodeWriter writer;
  12153. };
  12154. struct unicode_format_arg_t {
  12155. Py_UCS4 ch;
  12156. int flags;
  12157. Py_ssize_t width;
  12158. int prec;
  12159. int sign;
  12160. };
  12161. static PyObject *
  12162. unicode_format_getnextarg(struct unicode_formatter_t *ctx)
  12163. {
  12164. Py_ssize_t argidx = ctx->argidx;
  12165. if (argidx < ctx->arglen) {
  12166. ctx->argidx++;
  12167. if (ctx->arglen < 0)
  12168. return ctx->args;
  12169. else
  12170. return PyTuple_GetItem(ctx->args, argidx);
  12171. }
  12172. PyErr_SetString(PyExc_TypeError,
  12173. "not enough arguments for format string");
  12174. return NULL;
  12175. }
  12176. /* Returns a new reference to a PyUnicode object, or NULL on failure. */
  12177. /* Format a float into the writer if the writer is not NULL, or into *p_output
  12178. otherwise.
  12179. Return 0 on success, raise an exception and return -1 on error. */
  12180. static int
  12181. formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
  12182. PyObject **p_output,
  12183. _PyUnicodeWriter *writer)
  12184. {
  12185. char *p;
  12186. double x;
  12187. Py_ssize_t len;
  12188. int prec;
  12189. int dtoa_flags = 0;
  12190. x = PyFloat_AsDouble(v);
  12191. if (x == -1.0 && PyErr_Occurred())
  12192. return -1;
  12193. prec = arg->prec;
  12194. if (prec < 0)
  12195. prec = 6;
  12196. if (arg->flags & F_ALT)
  12197. dtoa_flags |= Py_DTSF_ALT;
  12198. p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
  12199. if (p == NULL)
  12200. return -1;
  12201. len = strlen(p);
  12202. if (writer) {
  12203. if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
  12204. PyMem_Free(p);
  12205. return -1;
  12206. }
  12207. }
  12208. else
  12209. *p_output = _PyUnicode_FromASCII(p, len);
  12210. PyMem_Free(p);
  12211. return 0;
  12212. }
  12213. /* formatlong() emulates the format codes d, u, o, x and X, and
  12214. * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
  12215. * Python's regular ints.
  12216. * Return value: a new PyUnicodeObject*, or NULL if error.
  12217. * The output string is of the form
  12218. * "-"? ("0x" | "0X")? digit+
  12219. * "0x"/"0X" are present only for x and X conversions, with F_ALT
  12220. * set in flags. The case of hex digits will be correct,
  12221. * There will be at least prec digits, zero-filled on the left if
  12222. * necessary to get that many.
  12223. * val object to be converted
  12224. * flags bitmask of format flags; only F_ALT is looked at
  12225. * prec minimum number of digits; 0-fill on left if needed
  12226. * type a character in [duoxX]; u acts the same as d
  12227. *
  12228. * CAUTION: o, x and X conversions on regular ints can never
  12229. * produce a '-' sign, but can for Python's unbounded ints.
  12230. */
  12231. PyObject *
  12232. _PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
  12233. {
  12234. PyObject *result = NULL;
  12235. char *buf;
  12236. Py_ssize_t i;
  12237. int sign; /* 1 if '-', else 0 */
  12238. int len; /* number of characters */
  12239. Py_ssize_t llen;
  12240. int numdigits; /* len == numnondigits + numdigits */
  12241. int numnondigits = 0;
  12242. /* Avoid exceeding SSIZE_T_MAX */
  12243. if (prec > INT_MAX-3) {
  12244. PyErr_SetString(PyExc_OverflowError,
  12245. "precision too large");
  12246. return NULL;
  12247. }
  12248. assert(PyLong_Check(val));
  12249. switch (type) {
  12250. default:
  12251. Py_UNREACHABLE();
  12252. case 'd':
  12253. case 'i':
  12254. case 'u':
  12255. /* int and int subclasses should print numerically when a numeric */
  12256. /* format code is used (see issue18780) */
  12257. result = PyNumber_ToBase(val, 10);
  12258. break;
  12259. case 'o':
  12260. numnondigits = 2;
  12261. result = PyNumber_ToBase(val, 8);
  12262. break;
  12263. case 'x':
  12264. case 'X':
  12265. numnondigits = 2;
  12266. result = PyNumber_ToBase(val, 16);
  12267. break;
  12268. }
  12269. if (!result)
  12270. return NULL;
  12271. assert(unicode_modifiable(result));
  12272. assert(PyUnicode_IS_ASCII(result));
  12273. /* To modify the string in-place, there can only be one reference. */
  12274. if (Py_REFCNT(result) != 1) {
  12275. Py_DECREF(result);
  12276. PyErr_BadInternalCall();
  12277. return NULL;
  12278. }
  12279. buf = PyUnicode_DATA(result);
  12280. llen = PyUnicode_GET_LENGTH(result);
  12281. if (llen > INT_MAX) {
  12282. Py_DECREF(result);
  12283. PyErr_SetString(PyExc_ValueError,
  12284. "string too large in _PyUnicode_FormatLong");
  12285. return NULL;
  12286. }
  12287. len = (int)llen;
  12288. sign = buf[0] == '-';
  12289. numnondigits += sign;
  12290. numdigits = len - numnondigits;
  12291. assert(numdigits > 0);
  12292. /* Get rid of base marker unless F_ALT */
  12293. if (((alt) == 0 &&
  12294. (type == 'o' || type == 'x' || type == 'X'))) {
  12295. assert(buf[sign] == '0');
  12296. assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
  12297. buf[sign+1] == 'o');
  12298. numnondigits -= 2;
  12299. buf += 2;
  12300. len -= 2;
  12301. if (sign)
  12302. buf[0] = '-';
  12303. assert(len == numnondigits + numdigits);
  12304. assert(numdigits > 0);
  12305. }
  12306. /* Fill with leading zeroes to meet minimum width. */
  12307. if (prec > numdigits) {
  12308. PyObject *r1 = PyBytes_FromStringAndSize(NULL,
  12309. numnondigits + prec);
  12310. char *b1;
  12311. if (!r1) {
  12312. Py_DECREF(result);
  12313. return NULL;
  12314. }
  12315. b1 = PyBytes_AS_STRING(r1);
  12316. for (i = 0; i < numnondigits; ++i)
  12317. *b1++ = *buf++;
  12318. for (i = 0; i < prec - numdigits; i++)
  12319. *b1++ = '0';
  12320. for (i = 0; i < numdigits; i++)
  12321. *b1++ = *buf++;
  12322. *b1 = '\0';
  12323. Py_SETREF(result, r1);
  12324. buf = PyBytes_AS_STRING(result);
  12325. len = numnondigits + prec;
  12326. }
  12327. /* Fix up case for hex conversions. */
  12328. if (type == 'X') {
  12329. /* Need to convert all lower case letters to upper case.
  12330. and need to convert 0x to 0X (and -0x to -0X). */
  12331. for (i = 0; i < len; i++)
  12332. if (buf[i] >= 'a' && buf[i] <= 'x')
  12333. buf[i] -= 'a'-'A';
  12334. }
  12335. if (!PyUnicode_Check(result)
  12336. || buf != PyUnicode_DATA(result)) {
  12337. PyObject *unicode;
  12338. unicode = _PyUnicode_FromASCII(buf, len);
  12339. Py_SETREF(result, unicode);
  12340. }
  12341. else if (len != PyUnicode_GET_LENGTH(result)) {
  12342. if (PyUnicode_Resize(&result, len) < 0)
  12343. Py_CLEAR(result);
  12344. }
  12345. return result;
  12346. }
  12347. /* Format an integer or a float as an integer.
  12348. * Return 1 if the number has been formatted into the writer,
  12349. * 0 if the number has been formatted into *p_output
  12350. * -1 and raise an exception on error */
  12351. static int
  12352. mainformatlong(PyObject *v,
  12353. struct unicode_format_arg_t *arg,
  12354. PyObject **p_output,
  12355. _PyUnicodeWriter *writer)
  12356. {
  12357. PyObject *iobj, *res;
  12358. char type = (char)arg->ch;
  12359. if (!PyNumber_Check(v))
  12360. goto wrongtype;
  12361. /* make sure number is a type of integer for o, x, and X */
  12362. if (!PyLong_Check(v)) {
  12363. if (type == 'o' || type == 'x' || type == 'X') {
  12364. iobj = _PyNumber_Index(v);
  12365. }
  12366. else {
  12367. iobj = PyNumber_Long(v);
  12368. }
  12369. if (iobj == NULL ) {
  12370. if (PyErr_ExceptionMatches(PyExc_TypeError))
  12371. goto wrongtype;
  12372. return -1;
  12373. }
  12374. assert(PyLong_Check(iobj));
  12375. }
  12376. else {
  12377. iobj = Py_NewRef(v);
  12378. }
  12379. if (PyLong_CheckExact(v)
  12380. && arg->width == -1 && arg->prec == -1
  12381. && !(arg->flags & (F_SIGN | F_BLANK))
  12382. && type != 'X')
  12383. {
  12384. /* Fast path */
  12385. int alternate = arg->flags & F_ALT;
  12386. int base;
  12387. switch(type)
  12388. {
  12389. default:
  12390. Py_UNREACHABLE();
  12391. case 'd':
  12392. case 'i':
  12393. case 'u':
  12394. base = 10;
  12395. break;
  12396. case 'o':
  12397. base = 8;
  12398. break;
  12399. case 'x':
  12400. case 'X':
  12401. base = 16;
  12402. break;
  12403. }
  12404. if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
  12405. Py_DECREF(iobj);
  12406. return -1;
  12407. }
  12408. Py_DECREF(iobj);
  12409. return 1;
  12410. }
  12411. res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
  12412. Py_DECREF(iobj);
  12413. if (res == NULL)
  12414. return -1;
  12415. *p_output = res;
  12416. return 0;
  12417. wrongtype:
  12418. switch(type)
  12419. {
  12420. case 'o':
  12421. case 'x':
  12422. case 'X':
  12423. PyErr_Format(PyExc_TypeError,
  12424. "%%%c format: an integer is required, "
  12425. "not %.200s",
  12426. type, Py_TYPE(v)->tp_name);
  12427. break;
  12428. default:
  12429. PyErr_Format(PyExc_TypeError,
  12430. "%%%c format: a real number is required, "
  12431. "not %.200s",
  12432. type, Py_TYPE(v)->tp_name);
  12433. break;
  12434. }
  12435. return -1;
  12436. }
  12437. static Py_UCS4
  12438. formatchar(PyObject *v)
  12439. {
  12440. /* presume that the buffer is at least 3 characters long */
  12441. if (PyUnicode_Check(v)) {
  12442. if (PyUnicode_GET_LENGTH(v) == 1) {
  12443. return PyUnicode_READ_CHAR(v, 0);
  12444. }
  12445. goto onError;
  12446. }
  12447. else {
  12448. int overflow;
  12449. long x = PyLong_AsLongAndOverflow(v, &overflow);
  12450. if (x == -1 && PyErr_Occurred()) {
  12451. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  12452. goto onError;
  12453. }
  12454. return (Py_UCS4) -1;
  12455. }
  12456. if (x < 0 || x > MAX_UNICODE) {
  12457. /* this includes an overflow in converting to C long */
  12458. PyErr_SetString(PyExc_OverflowError,
  12459. "%c arg not in range(0x110000)");
  12460. return (Py_UCS4) -1;
  12461. }
  12462. return (Py_UCS4) x;
  12463. }
  12464. onError:
  12465. PyErr_SetString(PyExc_TypeError,
  12466. "%c requires int or char");
  12467. return (Py_UCS4) -1;
  12468. }
  12469. /* Parse options of an argument: flags, width, precision.
  12470. Handle also "%(name)" syntax.
  12471. Return 0 if the argument has been formatted into arg->str.
  12472. Return 1 if the argument has been written into ctx->writer,
  12473. Raise an exception and return -1 on error. */
  12474. static int
  12475. unicode_format_arg_parse(struct unicode_formatter_t *ctx,
  12476. struct unicode_format_arg_t *arg)
  12477. {
  12478. #define FORMAT_READ(ctx) \
  12479. PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
  12480. PyObject *v;
  12481. if (arg->ch == '(') {
  12482. /* Get argument value from a dictionary. Example: "%(name)s". */
  12483. Py_ssize_t keystart;
  12484. Py_ssize_t keylen;
  12485. PyObject *key;
  12486. int pcount = 1;
  12487. if (ctx->dict == NULL) {
  12488. PyErr_SetString(PyExc_TypeError,
  12489. "format requires a mapping");
  12490. return -1;
  12491. }
  12492. ++ctx->fmtpos;
  12493. --ctx->fmtcnt;
  12494. keystart = ctx->fmtpos;
  12495. /* Skip over balanced parentheses */
  12496. while (pcount > 0 && --ctx->fmtcnt >= 0) {
  12497. arg->ch = FORMAT_READ(ctx);
  12498. if (arg->ch == ')')
  12499. --pcount;
  12500. else if (arg->ch == '(')
  12501. ++pcount;
  12502. ctx->fmtpos++;
  12503. }
  12504. keylen = ctx->fmtpos - keystart - 1;
  12505. if (ctx->fmtcnt < 0 || pcount > 0) {
  12506. PyErr_SetString(PyExc_ValueError,
  12507. "incomplete format key");
  12508. return -1;
  12509. }
  12510. key = PyUnicode_Substring(ctx->fmtstr,
  12511. keystart, keystart + keylen);
  12512. if (key == NULL)
  12513. return -1;
  12514. if (ctx->args_owned) {
  12515. ctx->args_owned = 0;
  12516. Py_DECREF(ctx->args);
  12517. }
  12518. ctx->args = PyObject_GetItem(ctx->dict, key);
  12519. Py_DECREF(key);
  12520. if (ctx->args == NULL)
  12521. return -1;
  12522. ctx->args_owned = 1;
  12523. ctx->arglen = -1;
  12524. ctx->argidx = -2;
  12525. }
  12526. /* Parse flags. Example: "%+i" => flags=F_SIGN. */
  12527. while (--ctx->fmtcnt >= 0) {
  12528. arg->ch = FORMAT_READ(ctx);
  12529. ctx->fmtpos++;
  12530. switch (arg->ch) {
  12531. case '-': arg->flags |= F_LJUST; continue;
  12532. case '+': arg->flags |= F_SIGN; continue;
  12533. case ' ': arg->flags |= F_BLANK; continue;
  12534. case '#': arg->flags |= F_ALT; continue;
  12535. case '0': arg->flags |= F_ZERO; continue;
  12536. }
  12537. break;
  12538. }
  12539. /* Parse width. Example: "%10s" => width=10 */
  12540. if (arg->ch == '*') {
  12541. v = unicode_format_getnextarg(ctx);
  12542. if (v == NULL)
  12543. return -1;
  12544. if (!PyLong_Check(v)) {
  12545. PyErr_SetString(PyExc_TypeError,
  12546. "* wants int");
  12547. return -1;
  12548. }
  12549. arg->width = PyLong_AsSsize_t(v);
  12550. if (arg->width == -1 && PyErr_Occurred())
  12551. return -1;
  12552. if (arg->width < 0) {
  12553. arg->flags |= F_LJUST;
  12554. arg->width = -arg->width;
  12555. }
  12556. if (--ctx->fmtcnt >= 0) {
  12557. arg->ch = FORMAT_READ(ctx);
  12558. ctx->fmtpos++;
  12559. }
  12560. }
  12561. else if (arg->ch >= '0' && arg->ch <= '9') {
  12562. arg->width = arg->ch - '0';
  12563. while (--ctx->fmtcnt >= 0) {
  12564. arg->ch = FORMAT_READ(ctx);
  12565. ctx->fmtpos++;
  12566. if (arg->ch < '0' || arg->ch > '9')
  12567. break;
  12568. /* Since arg->ch is unsigned, the RHS would end up as unsigned,
  12569. mixing signed and unsigned comparison. Since arg->ch is between
  12570. '0' and '9', casting to int is safe. */
  12571. if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
  12572. PyErr_SetString(PyExc_ValueError,
  12573. "width too big");
  12574. return -1;
  12575. }
  12576. arg->width = arg->width*10 + (arg->ch - '0');
  12577. }
  12578. }
  12579. /* Parse precision. Example: "%.3f" => prec=3 */
  12580. if (arg->ch == '.') {
  12581. arg->prec = 0;
  12582. if (--ctx->fmtcnt >= 0) {
  12583. arg->ch = FORMAT_READ(ctx);
  12584. ctx->fmtpos++;
  12585. }
  12586. if (arg->ch == '*') {
  12587. v = unicode_format_getnextarg(ctx);
  12588. if (v == NULL)
  12589. return -1;
  12590. if (!PyLong_Check(v)) {
  12591. PyErr_SetString(PyExc_TypeError,
  12592. "* wants int");
  12593. return -1;
  12594. }
  12595. arg->prec = _PyLong_AsInt(v);
  12596. if (arg->prec == -1 && PyErr_Occurred())
  12597. return -1;
  12598. if (arg->prec < 0)
  12599. arg->prec = 0;
  12600. if (--ctx->fmtcnt >= 0) {
  12601. arg->ch = FORMAT_READ(ctx);
  12602. ctx->fmtpos++;
  12603. }
  12604. }
  12605. else if (arg->ch >= '0' && arg->ch <= '9') {
  12606. arg->prec = arg->ch - '0';
  12607. while (--ctx->fmtcnt >= 0) {
  12608. arg->ch = FORMAT_READ(ctx);
  12609. ctx->fmtpos++;
  12610. if (arg->ch < '0' || arg->ch > '9')
  12611. break;
  12612. if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
  12613. PyErr_SetString(PyExc_ValueError,
  12614. "precision too big");
  12615. return -1;
  12616. }
  12617. arg->prec = arg->prec*10 + (arg->ch - '0');
  12618. }
  12619. }
  12620. }
  12621. /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
  12622. if (ctx->fmtcnt >= 0) {
  12623. if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
  12624. if (--ctx->fmtcnt >= 0) {
  12625. arg->ch = FORMAT_READ(ctx);
  12626. ctx->fmtpos++;
  12627. }
  12628. }
  12629. }
  12630. if (ctx->fmtcnt < 0) {
  12631. PyErr_SetString(PyExc_ValueError,
  12632. "incomplete format");
  12633. return -1;
  12634. }
  12635. return 0;
  12636. #undef FORMAT_READ
  12637. }
  12638. /* Format one argument. Supported conversion specifiers:
  12639. - "s", "r", "a": any type
  12640. - "i", "d", "u": int or float
  12641. - "o", "x", "X": int
  12642. - "e", "E", "f", "F", "g", "G": float
  12643. - "c": int or str (1 character)
  12644. When possible, the output is written directly into the Unicode writer
  12645. (ctx->writer). A string is created when padding is required.
  12646. Return 0 if the argument has been formatted into *p_str,
  12647. 1 if the argument has been written into ctx->writer,
  12648. -1 on error. */
  12649. static int
  12650. unicode_format_arg_format(struct unicode_formatter_t *ctx,
  12651. struct unicode_format_arg_t *arg,
  12652. PyObject **p_str)
  12653. {
  12654. PyObject *v;
  12655. _PyUnicodeWriter *writer = &ctx->writer;
  12656. if (ctx->fmtcnt == 0)
  12657. ctx->writer.overallocate = 0;
  12658. v = unicode_format_getnextarg(ctx);
  12659. if (v == NULL)
  12660. return -1;
  12661. switch (arg->ch) {
  12662. case 's':
  12663. case 'r':
  12664. case 'a':
  12665. if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
  12666. /* Fast path */
  12667. if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
  12668. return -1;
  12669. return 1;
  12670. }
  12671. if (PyUnicode_CheckExact(v) && arg->ch == 's') {
  12672. *p_str = Py_NewRef(v);
  12673. }
  12674. else {
  12675. if (arg->ch == 's')
  12676. *p_str = PyObject_Str(v);
  12677. else if (arg->ch == 'r')
  12678. *p_str = PyObject_Repr(v);
  12679. else
  12680. *p_str = PyObject_ASCII(v);
  12681. }
  12682. break;
  12683. case 'i':
  12684. case 'd':
  12685. case 'u':
  12686. case 'o':
  12687. case 'x':
  12688. case 'X':
  12689. {
  12690. int ret = mainformatlong(v, arg, p_str, writer);
  12691. if (ret != 0)
  12692. return ret;
  12693. arg->sign = 1;
  12694. break;
  12695. }
  12696. case 'e':
  12697. case 'E':
  12698. case 'f':
  12699. case 'F':
  12700. case 'g':
  12701. case 'G':
  12702. if (arg->width == -1 && arg->prec == -1
  12703. && !(arg->flags & (F_SIGN | F_BLANK)))
  12704. {
  12705. /* Fast path */
  12706. if (formatfloat(v, arg, NULL, writer) == -1)
  12707. return -1;
  12708. return 1;
  12709. }
  12710. arg->sign = 1;
  12711. if (formatfloat(v, arg, p_str, NULL) == -1)
  12712. return -1;
  12713. break;
  12714. case 'c':
  12715. {
  12716. Py_UCS4 ch = formatchar(v);
  12717. if (ch == (Py_UCS4) -1)
  12718. return -1;
  12719. if (arg->width == -1 && arg->prec == -1) {
  12720. /* Fast path */
  12721. if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
  12722. return -1;
  12723. return 1;
  12724. }
  12725. *p_str = PyUnicode_FromOrdinal(ch);
  12726. break;
  12727. }
  12728. default:
  12729. PyErr_Format(PyExc_ValueError,
  12730. "unsupported format character '%c' (0x%x) "
  12731. "at index %zd",
  12732. (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
  12733. (int)arg->ch,
  12734. ctx->fmtpos - 1);
  12735. return -1;
  12736. }
  12737. if (*p_str == NULL)
  12738. return -1;
  12739. assert (PyUnicode_Check(*p_str));
  12740. return 0;
  12741. }
  12742. static int
  12743. unicode_format_arg_output(struct unicode_formatter_t *ctx,
  12744. struct unicode_format_arg_t *arg,
  12745. PyObject *str)
  12746. {
  12747. Py_ssize_t len;
  12748. int kind;
  12749. const void *pbuf;
  12750. Py_ssize_t pindex;
  12751. Py_UCS4 signchar;
  12752. Py_ssize_t buflen;
  12753. Py_UCS4 maxchar;
  12754. Py_ssize_t sublen;
  12755. _PyUnicodeWriter *writer = &ctx->writer;
  12756. Py_UCS4 fill;
  12757. fill = ' ';
  12758. if (arg->sign && arg->flags & F_ZERO)
  12759. fill = '0';
  12760. len = PyUnicode_GET_LENGTH(str);
  12761. if ((arg->width == -1 || arg->width <= len)
  12762. && (arg->prec == -1 || arg->prec >= len)
  12763. && !(arg->flags & (F_SIGN | F_BLANK)))
  12764. {
  12765. /* Fast path */
  12766. if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
  12767. return -1;
  12768. return 0;
  12769. }
  12770. /* Truncate the string for "s", "r" and "a" formats
  12771. if the precision is set */
  12772. if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
  12773. if (arg->prec >= 0 && len > arg->prec)
  12774. len = arg->prec;
  12775. }
  12776. /* Adjust sign and width */
  12777. kind = PyUnicode_KIND(str);
  12778. pbuf = PyUnicode_DATA(str);
  12779. pindex = 0;
  12780. signchar = '\0';
  12781. if (arg->sign) {
  12782. Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
  12783. if (ch == '-' || ch == '+') {
  12784. signchar = ch;
  12785. len--;
  12786. pindex++;
  12787. }
  12788. else if (arg->flags & F_SIGN)
  12789. signchar = '+';
  12790. else if (arg->flags & F_BLANK)
  12791. signchar = ' ';
  12792. else
  12793. arg->sign = 0;
  12794. }
  12795. if (arg->width < len)
  12796. arg->width = len;
  12797. /* Prepare the writer */
  12798. maxchar = writer->maxchar;
  12799. if (!(arg->flags & F_LJUST)) {
  12800. if (arg->sign) {
  12801. if ((arg->width-1) > len)
  12802. maxchar = Py_MAX(maxchar, fill);
  12803. }
  12804. else {
  12805. if (arg->width > len)
  12806. maxchar = Py_MAX(maxchar, fill);
  12807. }
  12808. }
  12809. if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
  12810. Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
  12811. maxchar = Py_MAX(maxchar, strmaxchar);
  12812. }
  12813. buflen = arg->width;
  12814. if (arg->sign && len == arg->width)
  12815. buflen++;
  12816. if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
  12817. return -1;
  12818. /* Write the sign if needed */
  12819. if (arg->sign) {
  12820. if (fill != ' ') {
  12821. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
  12822. writer->pos += 1;
  12823. }
  12824. if (arg->width > len)
  12825. arg->width--;
  12826. }
  12827. /* Write the numeric prefix for "x", "X" and "o" formats
  12828. if the alternate form is used.
  12829. For example, write "0x" for the "%#x" format. */
  12830. if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
  12831. assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
  12832. assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
  12833. if (fill != ' ') {
  12834. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
  12835. PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
  12836. writer->pos += 2;
  12837. pindex += 2;
  12838. }
  12839. arg->width -= 2;
  12840. if (arg->width < 0)
  12841. arg->width = 0;
  12842. len -= 2;
  12843. }
  12844. /* Pad left with the fill character if needed */
  12845. if (arg->width > len && !(arg->flags & F_LJUST)) {
  12846. sublen = arg->width - len;
  12847. unicode_fill(writer->kind, writer->data, fill, writer->pos, sublen);
  12848. writer->pos += sublen;
  12849. arg->width = len;
  12850. }
  12851. /* If padding with spaces: write sign if needed and/or numeric prefix if
  12852. the alternate form is used */
  12853. if (fill == ' ') {
  12854. if (arg->sign) {
  12855. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
  12856. writer->pos += 1;
  12857. }
  12858. if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
  12859. assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
  12860. assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
  12861. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
  12862. PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
  12863. writer->pos += 2;
  12864. pindex += 2;
  12865. }
  12866. }
  12867. /* Write characters */
  12868. if (len) {
  12869. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  12870. str, pindex, len);
  12871. writer->pos += len;
  12872. }
  12873. /* Pad right with the fill character if needed */
  12874. if (arg->width > len) {
  12875. sublen = arg->width - len;
  12876. unicode_fill(writer->kind, writer->data, ' ', writer->pos, sublen);
  12877. writer->pos += sublen;
  12878. }
  12879. return 0;
  12880. }
  12881. /* Helper of PyUnicode_Format(): format one arg.
  12882. Return 0 on success, raise an exception and return -1 on error. */
  12883. static int
  12884. unicode_format_arg(struct unicode_formatter_t *ctx)
  12885. {
  12886. struct unicode_format_arg_t arg;
  12887. PyObject *str;
  12888. int ret;
  12889. arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
  12890. if (arg.ch == '%') {
  12891. ctx->fmtpos++;
  12892. ctx->fmtcnt--;
  12893. if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
  12894. return -1;
  12895. return 0;
  12896. }
  12897. arg.flags = 0;
  12898. arg.width = -1;
  12899. arg.prec = -1;
  12900. arg.sign = 0;
  12901. str = NULL;
  12902. ret = unicode_format_arg_parse(ctx, &arg);
  12903. if (ret == -1)
  12904. return -1;
  12905. ret = unicode_format_arg_format(ctx, &arg, &str);
  12906. if (ret == -1)
  12907. return -1;
  12908. if (ret != 1) {
  12909. ret = unicode_format_arg_output(ctx, &arg, str);
  12910. Py_DECREF(str);
  12911. if (ret == -1)
  12912. return -1;
  12913. }
  12914. if (ctx->dict && (ctx->argidx < ctx->arglen)) {
  12915. PyErr_SetString(PyExc_TypeError,
  12916. "not all arguments converted during string formatting");
  12917. return -1;
  12918. }
  12919. return 0;
  12920. }
  12921. PyObject *
  12922. PyUnicode_Format(PyObject *format, PyObject *args)
  12923. {
  12924. struct unicode_formatter_t ctx;
  12925. if (format == NULL || args == NULL) {
  12926. PyErr_BadInternalCall();
  12927. return NULL;
  12928. }
  12929. if (ensure_unicode(format) < 0)
  12930. return NULL;
  12931. ctx.fmtstr = format;
  12932. ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
  12933. ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
  12934. ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
  12935. ctx.fmtpos = 0;
  12936. _PyUnicodeWriter_Init(&ctx.writer);
  12937. ctx.writer.min_length = ctx.fmtcnt + 100;
  12938. ctx.writer.overallocate = 1;
  12939. if (PyTuple_Check(args)) {
  12940. ctx.arglen = PyTuple_Size(args);
  12941. ctx.argidx = 0;
  12942. }
  12943. else {
  12944. ctx.arglen = -1;
  12945. ctx.argidx = -2;
  12946. }
  12947. ctx.args_owned = 0;
  12948. if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
  12949. ctx.dict = args;
  12950. else
  12951. ctx.dict = NULL;
  12952. ctx.args = args;
  12953. while (--ctx.fmtcnt >= 0) {
  12954. if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
  12955. Py_ssize_t nonfmtpos;
  12956. nonfmtpos = ctx.fmtpos++;
  12957. while (ctx.fmtcnt >= 0 &&
  12958. PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
  12959. ctx.fmtpos++;
  12960. ctx.fmtcnt--;
  12961. }
  12962. if (ctx.fmtcnt < 0) {
  12963. ctx.fmtpos--;
  12964. ctx.writer.overallocate = 0;
  12965. }
  12966. if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
  12967. nonfmtpos, ctx.fmtpos) < 0)
  12968. goto onError;
  12969. }
  12970. else {
  12971. ctx.fmtpos++;
  12972. if (unicode_format_arg(&ctx) == -1)
  12973. goto onError;
  12974. }
  12975. }
  12976. if (ctx.argidx < ctx.arglen && !ctx.dict) {
  12977. PyErr_SetString(PyExc_TypeError,
  12978. "not all arguments converted during string formatting");
  12979. goto onError;
  12980. }
  12981. if (ctx.args_owned) {
  12982. Py_DECREF(ctx.args);
  12983. }
  12984. return _PyUnicodeWriter_Finish(&ctx.writer);
  12985. onError:
  12986. _PyUnicodeWriter_Dealloc(&ctx.writer);
  12987. if (ctx.args_owned) {
  12988. Py_DECREF(ctx.args);
  12989. }
  12990. return NULL;
  12991. }
  12992. static PyObject *
  12993. unicode_subtype_new(PyTypeObject *type, PyObject *unicode);
  12994. /*[clinic input]
  12995. @classmethod
  12996. str.__new__ as unicode_new
  12997. object as x: object = NULL
  12998. encoding: str = NULL
  12999. errors: str = NULL
  13000. [clinic start generated code]*/
  13001. static PyObject *
  13002. unicode_new_impl(PyTypeObject *type, PyObject *x, const char *encoding,
  13003. const char *errors)
  13004. /*[clinic end generated code: output=fc72d4878b0b57e9 input=e81255e5676d174e]*/
  13005. {
  13006. PyObject *unicode;
  13007. if (x == NULL) {
  13008. unicode = unicode_new_empty();
  13009. }
  13010. else if (encoding == NULL && errors == NULL) {
  13011. unicode = PyObject_Str(x);
  13012. }
  13013. else {
  13014. unicode = PyUnicode_FromEncodedObject(x, encoding, errors);
  13015. }
  13016. if (unicode != NULL && type != &PyUnicode_Type) {
  13017. Py_SETREF(unicode, unicode_subtype_new(type, unicode));
  13018. }
  13019. return unicode;
  13020. }
  13021. static PyObject *
  13022. unicode_subtype_new(PyTypeObject *type, PyObject *unicode)
  13023. {
  13024. PyObject *self;
  13025. Py_ssize_t length, char_size;
  13026. int share_utf8;
  13027. int kind;
  13028. void *data;
  13029. assert(PyType_IsSubtype(type, &PyUnicode_Type));
  13030. assert(_PyUnicode_CHECK(unicode));
  13031. self = type->tp_alloc(type, 0);
  13032. if (self == NULL) {
  13033. return NULL;
  13034. }
  13035. kind = PyUnicode_KIND(unicode);
  13036. length = PyUnicode_GET_LENGTH(unicode);
  13037. _PyUnicode_LENGTH(self) = length;
  13038. #ifdef Py_DEBUG
  13039. _PyUnicode_HASH(self) = -1;
  13040. #else
  13041. _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
  13042. #endif
  13043. _PyUnicode_STATE(self).interned = 0;
  13044. _PyUnicode_STATE(self).kind = kind;
  13045. _PyUnicode_STATE(self).compact = 0;
  13046. _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
  13047. _PyUnicode_STATE(self).statically_allocated = 0;
  13048. _PyUnicode_UTF8_LENGTH(self) = 0;
  13049. _PyUnicode_UTF8(self) = NULL;
  13050. _PyUnicode_DATA_ANY(self) = NULL;
  13051. share_utf8 = 0;
  13052. if (kind == PyUnicode_1BYTE_KIND) {
  13053. char_size = 1;
  13054. if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
  13055. share_utf8 = 1;
  13056. }
  13057. else if (kind == PyUnicode_2BYTE_KIND) {
  13058. char_size = 2;
  13059. }
  13060. else {
  13061. assert(kind == PyUnicode_4BYTE_KIND);
  13062. char_size = 4;
  13063. }
  13064. /* Ensure we won't overflow the length. */
  13065. if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
  13066. PyErr_NoMemory();
  13067. goto onError;
  13068. }
  13069. data = PyObject_Malloc((length + 1) * char_size);
  13070. if (data == NULL) {
  13071. PyErr_NoMemory();
  13072. goto onError;
  13073. }
  13074. _PyUnicode_DATA_ANY(self) = data;
  13075. if (share_utf8) {
  13076. _PyUnicode_UTF8_LENGTH(self) = length;
  13077. _PyUnicode_UTF8(self) = data;
  13078. }
  13079. memcpy(data, PyUnicode_DATA(unicode), kind * (length + 1));
  13080. assert(_PyUnicode_CheckConsistency(self, 1));
  13081. #ifdef Py_DEBUG
  13082. _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
  13083. #endif
  13084. return self;
  13085. onError:
  13086. Py_DECREF(self);
  13087. return NULL;
  13088. }
  13089. void
  13090. _PyUnicode_ExactDealloc(PyObject *op)
  13091. {
  13092. assert(PyUnicode_CheckExact(op));
  13093. unicode_dealloc(op);
  13094. }
  13095. PyDoc_STRVAR(unicode_doc,
  13096. "str(object='') -> str\n\
  13097. str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
  13098. \n\
  13099. Create a new string object from the given object. If encoding or\n\
  13100. errors is specified, then the object must expose a data buffer\n\
  13101. that will be decoded using the given encoding and error handler.\n\
  13102. Otherwise, returns the result of object.__str__() (if defined)\n\
  13103. or repr(object).\n\
  13104. encoding defaults to sys.getdefaultencoding().\n\
  13105. errors defaults to 'strict'.");
  13106. static PyObject *unicode_iter(PyObject *seq);
  13107. PyTypeObject PyUnicode_Type = {
  13108. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  13109. "str", /* tp_name */
  13110. sizeof(PyUnicodeObject), /* tp_basicsize */
  13111. 0, /* tp_itemsize */
  13112. /* Slots */
  13113. (destructor)unicode_dealloc, /* tp_dealloc */
  13114. 0, /* tp_vectorcall_offset */
  13115. 0, /* tp_getattr */
  13116. 0, /* tp_setattr */
  13117. 0, /* tp_as_async */
  13118. unicode_repr, /* tp_repr */
  13119. &unicode_as_number, /* tp_as_number */
  13120. &unicode_as_sequence, /* tp_as_sequence */
  13121. &unicode_as_mapping, /* tp_as_mapping */
  13122. (hashfunc) unicode_hash, /* tp_hash*/
  13123. 0, /* tp_call*/
  13124. (reprfunc) unicode_str, /* tp_str */
  13125. PyObject_GenericGetAttr, /* tp_getattro */
  13126. 0, /* tp_setattro */
  13127. 0, /* tp_as_buffer */
  13128. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  13129. Py_TPFLAGS_UNICODE_SUBCLASS |
  13130. _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
  13131. unicode_doc, /* tp_doc */
  13132. 0, /* tp_traverse */
  13133. 0, /* tp_clear */
  13134. PyUnicode_RichCompare, /* tp_richcompare */
  13135. 0, /* tp_weaklistoffset */
  13136. unicode_iter, /* tp_iter */
  13137. 0, /* tp_iternext */
  13138. unicode_methods, /* tp_methods */
  13139. 0, /* tp_members */
  13140. 0, /* tp_getset */
  13141. 0, /* tp_base */
  13142. 0, /* tp_dict */
  13143. 0, /* tp_descr_get */
  13144. 0, /* tp_descr_set */
  13145. 0, /* tp_dictoffset */
  13146. 0, /* tp_init */
  13147. 0, /* tp_alloc */
  13148. unicode_new, /* tp_new */
  13149. PyObject_Del, /* tp_free */
  13150. };
  13151. /* Initialize the Unicode implementation */
  13152. static void
  13153. _init_global_state(void)
  13154. {
  13155. static int initialized = 0;
  13156. if (initialized) {
  13157. return;
  13158. }
  13159. initialized = 1;
  13160. /* initialize the linebreak bloom filter */
  13161. const Py_UCS2 linebreak[] = {
  13162. 0x000A, /* LINE FEED */
  13163. 0x000D, /* CARRIAGE RETURN */
  13164. 0x001C, /* FILE SEPARATOR */
  13165. 0x001D, /* GROUP SEPARATOR */
  13166. 0x001E, /* RECORD SEPARATOR */
  13167. 0x0085, /* NEXT LINE */
  13168. 0x2028, /* LINE SEPARATOR */
  13169. 0x2029, /* PARAGRAPH SEPARATOR */
  13170. };
  13171. bloom_linebreak = make_bloom_mask(
  13172. PyUnicode_2BYTE_KIND, linebreak,
  13173. Py_ARRAY_LENGTH(linebreak));
  13174. }
  13175. void
  13176. _PyUnicode_InitState(PyInterpreterState *interp)
  13177. {
  13178. if (!_Py_IsMainInterpreter(interp)) {
  13179. return;
  13180. }
  13181. _init_global_state();
  13182. }
  13183. PyStatus
  13184. _PyUnicode_InitGlobalObjects(PyInterpreterState *interp)
  13185. {
  13186. if (_Py_IsMainInterpreter(interp)) {
  13187. PyStatus status = init_global_interned_strings(interp);
  13188. if (_PyStatus_EXCEPTION(status)) {
  13189. return status;
  13190. }
  13191. }
  13192. assert(INTERNED_STRINGS);
  13193. return _PyStatus_OK();
  13194. }
  13195. PyStatus
  13196. _PyUnicode_InitInternDict(PyInterpreterState *interp)
  13197. {
  13198. assert(INTERNED_STRINGS);
  13199. if (init_interned_dict(interp)) {
  13200. PyErr_Clear();
  13201. return _PyStatus_ERR("failed to create interned dict");
  13202. }
  13203. return _PyStatus_OK();
  13204. }
  13205. PyStatus
  13206. _PyUnicode_InitTypes(PyInterpreterState *interp)
  13207. {
  13208. if (_PyStaticType_InitBuiltin(interp, &EncodingMapType) < 0) {
  13209. goto error;
  13210. }
  13211. if (_PyStaticType_InitBuiltin(interp, &PyFieldNameIter_Type) < 0) {
  13212. goto error;
  13213. }
  13214. if (_PyStaticType_InitBuiltin(interp, &PyFormatterIter_Type) < 0) {
  13215. goto error;
  13216. }
  13217. return _PyStatus_OK();
  13218. error:
  13219. return _PyStatus_ERR("Can't initialize unicode types");
  13220. }
  13221. static /* non-null */ PyObject*
  13222. intern_static(PyInterpreterState *interp, PyObject *s /* stolen */)
  13223. {
  13224. // Note that this steals a reference to `s`, but in many cases that
  13225. // stolen ref is returned, requiring no decref/incref.
  13226. assert(s != NULL);
  13227. assert(_PyUnicode_CHECK(s));
  13228. assert(_PyUnicode_STATE(s).statically_allocated);
  13229. assert(!PyUnicode_CHECK_INTERNED(s));
  13230. #ifdef Py_DEBUG
  13231. /* We must not add process-global interned string if there's already a
  13232. * per-interpreter interned_dict, which might contain duplicates.
  13233. */
  13234. PyObject *interned = get_interned_dict(interp);
  13235. // assert(interned == NULL);
  13236. #endif
  13237. /* Look in the global cache first. */
  13238. PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
  13239. /* We should only init each string once */
  13240. assert(r == NULL);
  13241. /* but just in case (for the non-debug build), handle this */
  13242. if (r != NULL && r != s) {
  13243. assert(_PyUnicode_STATE(r).interned == SSTATE_INTERNED_IMMORTAL_STATIC);
  13244. assert(_PyUnicode_CHECK(r));
  13245. Py_DECREF(s);
  13246. return Py_NewRef(r);
  13247. }
  13248. if (_Py_hashtable_set(INTERNED_STRINGS, s, s) < -1) {
  13249. Py_FatalError("failed to intern static string");
  13250. }
  13251. _PyUnicode_STATE(s).interned = SSTATE_INTERNED_IMMORTAL_STATIC;
  13252. return s;
  13253. }
  13254. void
  13255. _PyUnicode_InternStatic(PyInterpreterState *interp, PyObject **p)
  13256. {
  13257. // This should only be called as part of runtime initialization
  13258. assert(!Py_IsInitialized());
  13259. *p = intern_static(interp, *p);
  13260. assert(*p);
  13261. }
  13262. static void
  13263. immortalize_interned(PyObject *s)
  13264. {
  13265. assert(PyUnicode_CHECK_INTERNED(s) == SSTATE_INTERNED_MORTAL);
  13266. assert(!_Py_IsImmortal(s));
  13267. #ifdef Py_REF_DEBUG
  13268. /* The reference count value should be excluded from the RefTotal.
  13269. The decrements to these objects will not be registered so they
  13270. need to be accounted for in here. */
  13271. for (Py_ssize_t i = 0; i < Py_REFCNT(s); i++) {
  13272. _Py_DecRefTotal(_PyInterpreterState_GET());
  13273. }
  13274. #endif
  13275. _PyUnicode_STATE(s).interned = SSTATE_INTERNED_IMMORTAL;
  13276. _Py_SetImmortal(s);
  13277. }
  13278. static /* non-null */ PyObject*
  13279. intern_common(PyInterpreterState *interp, PyObject *s /* stolen */,
  13280. bool immortalize)
  13281. {
  13282. // Note that this steals a reference to `s`, but in many cases that
  13283. // stolen ref is returned, requiring no decref/incref.
  13284. #ifdef Py_DEBUG
  13285. assert(s != NULL);
  13286. assert(_PyUnicode_CHECK(s));
  13287. #else
  13288. if (s == NULL || !PyUnicode_Check(s)) {
  13289. return s;
  13290. }
  13291. #endif
  13292. /* If it's a subclass, we don't really know what putting
  13293. it in the interned dict might do. */
  13294. if (!PyUnicode_CheckExact(s)) {
  13295. return s;
  13296. }
  13297. /* Is it already interned? */
  13298. switch (PyUnicode_CHECK_INTERNED(s)) {
  13299. case SSTATE_NOT_INTERNED:
  13300. // no, go on
  13301. break;
  13302. case SSTATE_INTERNED_MORTAL:
  13303. // yes but we might need to make it immortal
  13304. if (immortalize) {
  13305. immortalize_interned(s);
  13306. }
  13307. return s;
  13308. default:
  13309. // all done
  13310. return s;
  13311. }
  13312. if (_PyUnicode_STATE(s).statically_allocated) {
  13313. return intern_static(interp, s);
  13314. }
  13315. /* If it's already immortal, intern it as such */
  13316. if (_Py_IsImmortal(s)) {
  13317. immortalize = 1;
  13318. }
  13319. /* if it's a short string, get the singleton */
  13320. if (PyUnicode_GET_LENGTH(s) == 1 &&
  13321. PyUnicode_KIND(s) == PyUnicode_1BYTE_KIND) {
  13322. PyObject *r = LATIN1(*(unsigned char*)PyUnicode_DATA(s));
  13323. assert(PyUnicode_CHECK_INTERNED(r));
  13324. Py_DECREF(s);
  13325. return r;
  13326. }
  13327. #ifdef Py_DEBUG
  13328. assert(!unicode_is_singleton(s));
  13329. #endif
  13330. /* Look in the global cache now. */
  13331. {
  13332. PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
  13333. if (r != NULL) {
  13334. assert(_PyUnicode_STATE(r).statically_allocated);
  13335. assert(r != s); // r must be statically_allocated; s is not
  13336. Py_DECREF(s);
  13337. return Py_NewRef(r);
  13338. }
  13339. }
  13340. /* Do a setdefault on the per-interpreter cache. */
  13341. PyObject *interned = get_interned_dict(interp);
  13342. assert(interned != NULL);
  13343. PyObject *t = PyDict_SetDefault(interned, s, s); // t is borrowed
  13344. if (t == NULL) {
  13345. PyErr_Clear();
  13346. return s;
  13347. }
  13348. if (t != s) {
  13349. // value was already present (not inserted)
  13350. Py_INCREF(t);
  13351. Py_DECREF(s);
  13352. if (immortalize &&
  13353. PyUnicode_CHECK_INTERNED(t) == SSTATE_INTERNED_MORTAL) {
  13354. immortalize_interned(t);
  13355. }
  13356. return t;
  13357. }
  13358. else {
  13359. // value was newly inserted
  13360. }
  13361. /* NOT_INTERNED -> INTERNED_MORTAL */
  13362. assert(_PyUnicode_STATE(s).interned == SSTATE_NOT_INTERNED);
  13363. if (!_Py_IsImmortal(s)) {
  13364. /* The two references in interned dict (key and value) are not counted.
  13365. unicode_dealloc() and _PyUnicode_ClearInterned() take care of this. */
  13366. Py_SET_REFCNT(s, Py_REFCNT(s) - 2);
  13367. #ifdef Py_REF_DEBUG
  13368. /* let's be pedantic with the ref total */
  13369. _Py_DecRefTotal(_PyInterpreterState_GET());
  13370. _Py_DecRefTotal(_PyInterpreterState_GET());
  13371. #endif
  13372. }
  13373. _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
  13374. /* INTERNED_MORTAL -> INTERNED_IMMORTAL (if needed) */
  13375. #ifdef Py_DEBUG
  13376. if (_Py_IsImmortal(s)) {
  13377. assert(immortalize);
  13378. }
  13379. #endif
  13380. if (immortalize) {
  13381. immortalize_interned(s);
  13382. }
  13383. return s;
  13384. }
  13385. void
  13386. _PyUnicode_InternImmortal(PyInterpreterState *interp, PyObject **p)
  13387. {
  13388. *p = intern_common(interp, *p, 1);
  13389. assert(*p);
  13390. }
  13391. void
  13392. _PyUnicode_InternMortal(PyInterpreterState *interp, PyObject **p)
  13393. {
  13394. *p = intern_common(interp, *p, 0);
  13395. assert(*p);
  13396. }
  13397. void
  13398. _PyUnicode_InternInPlace(PyInterpreterState *interp, PyObject **p)
  13399. {
  13400. _PyUnicode_InternImmortal(interp, p);
  13401. return;
  13402. }
  13403. void
  13404. PyUnicode_InternInPlace(PyObject **p)
  13405. {
  13406. PyInterpreterState *interp = _PyInterpreterState_GET();
  13407. _PyUnicode_InternMortal(interp, p);
  13408. }
  13409. // Public-looking name kept for the stable ABI; user should not call this:
  13410. PyAPI_FUNC(void) PyUnicode_InternImmortal(PyObject **);
  13411. void
  13412. PyUnicode_InternImmortal(PyObject **p)
  13413. {
  13414. PyInterpreterState *interp = _PyInterpreterState_GET();
  13415. _PyUnicode_InternImmortal(interp, p);
  13416. }
  13417. PyObject *
  13418. PyUnicode_InternFromString(const char *cp)
  13419. {
  13420. PyObject *s = PyUnicode_FromString(cp);
  13421. if (s == NULL) {
  13422. return NULL;
  13423. }
  13424. PyInterpreterState *interp = _PyInterpreterState_GET();
  13425. _PyUnicode_InternMortal(interp, &s);
  13426. return s;
  13427. }
  13428. void
  13429. _PyUnicode_ClearInterned(PyInterpreterState *interp)
  13430. {
  13431. PyObject *interned = get_interned_dict(interp);
  13432. if (interned == NULL) {
  13433. return;
  13434. }
  13435. assert(PyDict_CheckExact(interned));
  13436. #ifdef INTERNED_STATS
  13437. fprintf(stderr, "releasing %zd interned strings\n",
  13438. PyDict_GET_SIZE(interned));
  13439. Py_ssize_t total_length = 0;
  13440. #endif
  13441. Py_ssize_t pos = 0;
  13442. PyObject *s, *ignored_value;
  13443. while (PyDict_Next(interned, &pos, &s, &ignored_value)) {
  13444. assert(PyUnicode_IS_READY(s));
  13445. int shared = 0;
  13446. switch (PyUnicode_CHECK_INTERNED(s)) {
  13447. case SSTATE_INTERNED_IMMORTAL:
  13448. /* Make immortal interned strings mortal again.
  13449. *
  13450. * Currently, the runtime is not able to guarantee that it can exit
  13451. * without allocations that carry over to a future initialization
  13452. * of Python within the same process. i.e:
  13453. * ./python -X showrefcount -c 'import itertools'
  13454. * [237 refs, 237 blocks]
  13455. *
  13456. * This should remain disabled (`Py_DEBUG` only) until there is a
  13457. * strict guarantee that no memory will be left after
  13458. * `Py_Finalize`.
  13459. */
  13460. #ifdef Py_DEBUG
  13461. // Skip the Immortal Instance check and restore
  13462. // the two references (key and value) ignored
  13463. // by PyUnicode_InternInPlace().
  13464. s->ob_refcnt = 2;
  13465. #ifdef Py_REF_DEBUG
  13466. /* let's be pedantic with the ref total */
  13467. _Py_IncRefTotal(_PyInterpreterState_GET());
  13468. _Py_IncRefTotal(_PyInterpreterState_GET());
  13469. #endif
  13470. #ifdef INTERNED_STATS
  13471. total_length += PyUnicode_GET_LENGTH(s);
  13472. #endif
  13473. #endif // Py_DEBUG
  13474. break;
  13475. case SSTATE_INTERNED_IMMORTAL_STATIC:
  13476. /* It is shared between interpreters, so we should unmark it
  13477. only when this is the last interpreter in which it's
  13478. interned. We immortalize all the statically initialized
  13479. strings during startup, so we can rely on the
  13480. main interpreter to be the last one. */
  13481. if (!_Py_IsMainInterpreter(interp)) {
  13482. shared = 1;
  13483. }
  13484. break;
  13485. case SSTATE_INTERNED_MORTAL:
  13486. // Restore 2 references held by the interned dict; these will
  13487. // be decref'd by clear_interned_dict's PyDict_Clear.
  13488. Py_SET_REFCNT(s, Py_REFCNT(s) + 2);
  13489. #ifdef Py_REF_DEBUG
  13490. /* let's be pedantic with the ref total */
  13491. _Py_IncRefTotal(_PyInterpreterState_GET());
  13492. _Py_IncRefTotal(_PyInterpreterState_GET());
  13493. #endif
  13494. break;
  13495. case SSTATE_NOT_INTERNED:
  13496. /* fall through */
  13497. default:
  13498. Py_UNREACHABLE();
  13499. }
  13500. if (!shared) {
  13501. _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
  13502. }
  13503. }
  13504. #ifdef INTERNED_STATS
  13505. fprintf(stderr,
  13506. "total length of all interned strings: %zd characters\n",
  13507. total_length);
  13508. #endif
  13509. struct _Py_unicode_state *state = &interp->unicode;
  13510. struct _Py_unicode_ids *ids = &state->ids;
  13511. for (Py_ssize_t i=0; i < ids->size; i++) {
  13512. Py_XINCREF(ids->array[i]);
  13513. }
  13514. clear_interned_dict(interp);
  13515. if (_Py_IsMainInterpreter(interp)) {
  13516. clear_global_interned_strings();
  13517. }
  13518. }
  13519. /********************* Unicode Iterator **************************/
  13520. typedef struct {
  13521. PyObject_HEAD
  13522. Py_ssize_t it_index;
  13523. PyObject *it_seq; /* Set to NULL when iterator is exhausted */
  13524. } unicodeiterobject;
  13525. static void
  13526. unicodeiter_dealloc(unicodeiterobject *it)
  13527. {
  13528. _PyObject_GC_UNTRACK(it);
  13529. Py_XDECREF(it->it_seq);
  13530. PyObject_GC_Del(it);
  13531. }
  13532. static int
  13533. unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
  13534. {
  13535. Py_VISIT(it->it_seq);
  13536. return 0;
  13537. }
  13538. static PyObject *
  13539. unicodeiter_next(unicodeiterobject *it)
  13540. {
  13541. PyObject *seq;
  13542. assert(it != NULL);
  13543. seq = it->it_seq;
  13544. if (seq == NULL)
  13545. return NULL;
  13546. assert(_PyUnicode_CHECK(seq));
  13547. if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
  13548. int kind = PyUnicode_KIND(seq);
  13549. const void *data = PyUnicode_DATA(seq);
  13550. Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
  13551. it->it_index++;
  13552. return unicode_char(chr);
  13553. }
  13554. it->it_seq = NULL;
  13555. Py_DECREF(seq);
  13556. return NULL;
  13557. }
  13558. static PyObject *
  13559. unicode_ascii_iter_next(unicodeiterobject *it)
  13560. {
  13561. assert(it != NULL);
  13562. PyObject *seq = it->it_seq;
  13563. if (seq == NULL) {
  13564. return NULL;
  13565. }
  13566. assert(_PyUnicode_CHECK(seq));
  13567. assert(PyUnicode_IS_COMPACT_ASCII(seq));
  13568. if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
  13569. const void *data = ((void*)(_PyASCIIObject_CAST(seq) + 1));
  13570. Py_UCS1 chr = (Py_UCS1)PyUnicode_READ(PyUnicode_1BYTE_KIND,
  13571. data, it->it_index);
  13572. it->it_index++;
  13573. PyObject *item = (PyObject*)&_Py_SINGLETON(strings).ascii[chr];
  13574. return Py_NewRef(item);
  13575. }
  13576. it->it_seq = NULL;
  13577. Py_DECREF(seq);
  13578. return NULL;
  13579. }
  13580. static PyObject *
  13581. unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
  13582. {
  13583. Py_ssize_t len = 0;
  13584. if (it->it_seq)
  13585. len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
  13586. return PyLong_FromSsize_t(len);
  13587. }
  13588. PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
  13589. static PyObject *
  13590. unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
  13591. {
  13592. PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
  13593. /* _PyEval_GetBuiltin can invoke arbitrary code,
  13594. * call must be before access of iterator pointers.
  13595. * see issue #101765 */
  13596. if (it->it_seq != NULL) {
  13597. return Py_BuildValue("N(O)n", iter, it->it_seq, it->it_index);
  13598. } else {
  13599. PyObject *u = unicode_new_empty();
  13600. if (u == NULL) {
  13601. Py_XDECREF(iter);
  13602. return NULL;
  13603. }
  13604. return Py_BuildValue("N(N)", iter, u);
  13605. }
  13606. }
  13607. PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
  13608. static PyObject *
  13609. unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
  13610. {
  13611. Py_ssize_t index = PyLong_AsSsize_t(state);
  13612. if (index == -1 && PyErr_Occurred())
  13613. return NULL;
  13614. if (it->it_seq != NULL) {
  13615. if (index < 0)
  13616. index = 0;
  13617. else if (index > PyUnicode_GET_LENGTH(it->it_seq))
  13618. index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
  13619. it->it_index = index;
  13620. }
  13621. Py_RETURN_NONE;
  13622. }
  13623. PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
  13624. static PyMethodDef unicodeiter_methods[] = {
  13625. {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
  13626. length_hint_doc},
  13627. {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
  13628. reduce_doc},
  13629. {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
  13630. setstate_doc},
  13631. {NULL, NULL} /* sentinel */
  13632. };
  13633. PyTypeObject PyUnicodeIter_Type = {
  13634. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  13635. "str_iterator", /* tp_name */
  13636. sizeof(unicodeiterobject), /* tp_basicsize */
  13637. 0, /* tp_itemsize */
  13638. /* methods */
  13639. (destructor)unicodeiter_dealloc, /* tp_dealloc */
  13640. 0, /* tp_vectorcall_offset */
  13641. 0, /* tp_getattr */
  13642. 0, /* tp_setattr */
  13643. 0, /* tp_as_async */
  13644. 0, /* tp_repr */
  13645. 0, /* tp_as_number */
  13646. 0, /* tp_as_sequence */
  13647. 0, /* tp_as_mapping */
  13648. 0, /* tp_hash */
  13649. 0, /* tp_call */
  13650. 0, /* tp_str */
  13651. PyObject_GenericGetAttr, /* tp_getattro */
  13652. 0, /* tp_setattro */
  13653. 0, /* tp_as_buffer */
  13654. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  13655. 0, /* tp_doc */
  13656. (traverseproc)unicodeiter_traverse, /* tp_traverse */
  13657. 0, /* tp_clear */
  13658. 0, /* tp_richcompare */
  13659. 0, /* tp_weaklistoffset */
  13660. PyObject_SelfIter, /* tp_iter */
  13661. (iternextfunc)unicodeiter_next, /* tp_iternext */
  13662. unicodeiter_methods, /* tp_methods */
  13663. 0,
  13664. };
  13665. PyTypeObject _PyUnicodeASCIIIter_Type = {
  13666. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  13667. .tp_name = "str_ascii_iterator",
  13668. .tp_basicsize = sizeof(unicodeiterobject),
  13669. .tp_dealloc = (destructor)unicodeiter_dealloc,
  13670. .tp_getattro = PyObject_GenericGetAttr,
  13671. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  13672. .tp_traverse = (traverseproc)unicodeiter_traverse,
  13673. .tp_iter = PyObject_SelfIter,
  13674. .tp_iternext = (iternextfunc)unicode_ascii_iter_next,
  13675. .tp_methods = unicodeiter_methods,
  13676. };
  13677. static PyObject *
  13678. unicode_iter(PyObject *seq)
  13679. {
  13680. unicodeiterobject *it;
  13681. if (!PyUnicode_Check(seq)) {
  13682. PyErr_BadInternalCall();
  13683. return NULL;
  13684. }
  13685. if (PyUnicode_IS_COMPACT_ASCII(seq)) {
  13686. it = PyObject_GC_New(unicodeiterobject, &_PyUnicodeASCIIIter_Type);
  13687. }
  13688. else {
  13689. it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
  13690. }
  13691. if (it == NULL)
  13692. return NULL;
  13693. it->it_index = 0;
  13694. it->it_seq = Py_NewRef(seq);
  13695. _PyObject_GC_TRACK(it);
  13696. return (PyObject *)it;
  13697. }
  13698. static int
  13699. encode_wstr_utf8(wchar_t *wstr, char **str, const char *name)
  13700. {
  13701. int res;
  13702. res = _Py_EncodeUTF8Ex(wstr, str, NULL, NULL, 1, _Py_ERROR_STRICT);
  13703. if (res == -2) {
  13704. PyErr_Format(PyExc_RuntimeWarning, "cannot decode %s", name);
  13705. return -1;
  13706. }
  13707. if (res < 0) {
  13708. PyErr_NoMemory();
  13709. return -1;
  13710. }
  13711. return 0;
  13712. }
  13713. static int
  13714. config_get_codec_name(wchar_t **config_encoding)
  13715. {
  13716. char *encoding;
  13717. if (encode_wstr_utf8(*config_encoding, &encoding, "stdio_encoding") < 0) {
  13718. return -1;
  13719. }
  13720. PyObject *name_obj = NULL;
  13721. PyObject *codec = _PyCodec_Lookup(encoding);
  13722. PyMem_RawFree(encoding);
  13723. if (!codec)
  13724. goto error;
  13725. name_obj = PyObject_GetAttrString(codec, "name");
  13726. Py_CLEAR(codec);
  13727. if (!name_obj) {
  13728. goto error;
  13729. }
  13730. wchar_t *wname = PyUnicode_AsWideCharString(name_obj, NULL);
  13731. Py_DECREF(name_obj);
  13732. if (wname == NULL) {
  13733. goto error;
  13734. }
  13735. wchar_t *raw_wname = _PyMem_RawWcsdup(wname);
  13736. if (raw_wname == NULL) {
  13737. PyMem_Free(wname);
  13738. PyErr_NoMemory();
  13739. goto error;
  13740. }
  13741. PyMem_RawFree(*config_encoding);
  13742. *config_encoding = raw_wname;
  13743. PyMem_Free(wname);
  13744. return 0;
  13745. error:
  13746. Py_XDECREF(codec);
  13747. Py_XDECREF(name_obj);
  13748. return -1;
  13749. }
  13750. static PyStatus
  13751. init_stdio_encoding(PyInterpreterState *interp)
  13752. {
  13753. /* Update the stdio encoding to the normalized Python codec name. */
  13754. PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
  13755. if (config_get_codec_name(&config->stdio_encoding) < 0) {
  13756. return _PyStatus_ERR("failed to get the Python codec name "
  13757. "of the stdio encoding");
  13758. }
  13759. return _PyStatus_OK();
  13760. }
  13761. static int
  13762. init_fs_codec(PyInterpreterState *interp)
  13763. {
  13764. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  13765. _Py_error_handler error_handler;
  13766. error_handler = get_error_handler_wide(config->filesystem_errors);
  13767. if (error_handler == _Py_ERROR_UNKNOWN) {
  13768. PyErr_SetString(PyExc_RuntimeError, "unknown filesystem error handler");
  13769. return -1;
  13770. }
  13771. char *encoding, *errors;
  13772. if (encode_wstr_utf8(config->filesystem_encoding,
  13773. &encoding,
  13774. "filesystem_encoding") < 0) {
  13775. return -1;
  13776. }
  13777. if (encode_wstr_utf8(config->filesystem_errors,
  13778. &errors,
  13779. "filesystem_errors") < 0) {
  13780. PyMem_RawFree(encoding);
  13781. return -1;
  13782. }
  13783. struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
  13784. PyMem_RawFree(fs_codec->encoding);
  13785. fs_codec->encoding = encoding;
  13786. /* encoding has been normalized by init_fs_encoding() */
  13787. fs_codec->utf8 = (strcmp(encoding, "utf-8") == 0);
  13788. PyMem_RawFree(fs_codec->errors);
  13789. fs_codec->errors = errors;
  13790. fs_codec->error_handler = error_handler;
  13791. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  13792. assert(fs_codec->utf8 == 1);
  13793. #endif
  13794. /* At this point, PyUnicode_EncodeFSDefault() and
  13795. PyUnicode_DecodeFSDefault() can now use the Python codec rather than
  13796. the C implementation of the filesystem encoding. */
  13797. /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
  13798. global configuration variables. */
  13799. if (_Py_IsMainInterpreter(interp)) {
  13800. if (_Py_SetFileSystemEncoding(fs_codec->encoding,
  13801. fs_codec->errors) < 0) {
  13802. PyErr_NoMemory();
  13803. return -1;
  13804. }
  13805. }
  13806. return 0;
  13807. }
  13808. static PyStatus
  13809. init_fs_encoding(PyThreadState *tstate)
  13810. {
  13811. PyInterpreterState *interp = tstate->interp;
  13812. /* Update the filesystem encoding to the normalized Python codec name.
  13813. For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
  13814. (Python codec name). */
  13815. PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
  13816. if (config_get_codec_name(&config->filesystem_encoding) < 0) {
  13817. _Py_DumpPathConfig(tstate);
  13818. return _PyStatus_ERR("failed to get the Python codec "
  13819. "of the filesystem encoding");
  13820. }
  13821. if (init_fs_codec(interp) < 0) {
  13822. return _PyStatus_ERR("cannot initialize filesystem codec");
  13823. }
  13824. return _PyStatus_OK();
  13825. }
  13826. PyStatus
  13827. _PyUnicode_InitEncodings(PyThreadState *tstate)
  13828. {
  13829. PyStatus status = init_fs_encoding(tstate);
  13830. if (_PyStatus_EXCEPTION(status)) {
  13831. return status;
  13832. }
  13833. return init_stdio_encoding(tstate->interp);
  13834. }
  13835. static void
  13836. _PyUnicode_FiniEncodings(struct _Py_unicode_fs_codec *fs_codec)
  13837. {
  13838. PyMem_RawFree(fs_codec->encoding);
  13839. fs_codec->encoding = NULL;
  13840. fs_codec->utf8 = 0;
  13841. PyMem_RawFree(fs_codec->errors);
  13842. fs_codec->errors = NULL;
  13843. fs_codec->error_handler = _Py_ERROR_UNKNOWN;
  13844. }
  13845. #ifdef MS_WINDOWS
  13846. int
  13847. _PyUnicode_EnableLegacyWindowsFSEncoding(void)
  13848. {
  13849. PyInterpreterState *interp = _PyInterpreterState_GET();
  13850. PyConfig *config = (PyConfig *)_PyInterpreterState_GetConfig(interp);
  13851. /* Set the filesystem encoding to mbcs/replace (PEP 529) */
  13852. wchar_t *encoding = _PyMem_RawWcsdup(L"mbcs");
  13853. wchar_t *errors = _PyMem_RawWcsdup(L"replace");
  13854. if (encoding == NULL || errors == NULL) {
  13855. PyMem_RawFree(encoding);
  13856. PyMem_RawFree(errors);
  13857. PyErr_NoMemory();
  13858. return -1;
  13859. }
  13860. PyMem_RawFree(config->filesystem_encoding);
  13861. config->filesystem_encoding = encoding;
  13862. PyMem_RawFree(config->filesystem_errors);
  13863. config->filesystem_errors = errors;
  13864. return init_fs_codec(interp);
  13865. }
  13866. #endif
  13867. #ifdef Py_DEBUG
  13868. static inline int
  13869. unicode_is_finalizing(void)
  13870. {
  13871. return (get_interned_dict(_PyInterpreterState_Main()) == NULL);
  13872. }
  13873. #endif
  13874. void
  13875. _PyUnicode_FiniTypes(PyInterpreterState *interp)
  13876. {
  13877. _PyStaticType_Dealloc(interp, &EncodingMapType);
  13878. _PyStaticType_Dealloc(interp, &PyFieldNameIter_Type);
  13879. _PyStaticType_Dealloc(interp, &PyFormatterIter_Type);
  13880. }
  13881. void
  13882. _PyUnicode_Fini(PyInterpreterState *interp)
  13883. {
  13884. struct _Py_unicode_state *state = &interp->unicode;
  13885. // _PyUnicode_ClearInterned() must be called before _PyUnicode_Fini()
  13886. assert(get_interned_dict(interp) == NULL);
  13887. _PyUnicode_FiniEncodings(&state->fs_codec);
  13888. // bpo-47182: force a unicodedata CAPI capsule re-import on
  13889. // subsequent initialization of interpreter.
  13890. interp->unicode.ucnhash_capi = NULL;
  13891. unicode_clear_identifiers(state);
  13892. }
  13893. /* A _string module, to export formatter_parser and formatter_field_name_split
  13894. to the string.Formatter class implemented in Python. */
  13895. static PyMethodDef _string_methods[] = {
  13896. {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
  13897. METH_O, PyDoc_STR("split the argument as a field name")},
  13898. {"formatter_parser", (PyCFunction) formatter_parser,
  13899. METH_O, PyDoc_STR("parse the argument as a format string")},
  13900. {NULL, NULL}
  13901. };
  13902. static PyModuleDef_Slot module_slots[] = {
  13903. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  13904. {0, NULL}
  13905. };
  13906. static struct PyModuleDef _string_module = {
  13907. PyModuleDef_HEAD_INIT,
  13908. .m_name = "_string",
  13909. .m_doc = PyDoc_STR("string helper module"),
  13910. .m_size = 0,
  13911. .m_methods = _string_methods,
  13912. .m_slots = module_slots,
  13913. };
  13914. PyMODINIT_FUNC
  13915. PyInit__string(void)
  13916. {
  13917. return PyModuleDef_Init(&_string_module);
  13918. }
  13919. #ifdef __cplusplus
  13920. }
  13921. #endif