unicodeobject.c 457 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760
  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. /* Return true if this interpreter should share the main interpreter's
  244. intern_dict. That's important for interpreters which load basic
  245. single-phase init extension modules (m_size == -1). There could be interned
  246. immortal strings that are shared between interpreters, due to the
  247. PyDict_Update(mdict, m_copy) call in import_find_extension().
  248. It's not safe to deallocate those strings until all interpreters that
  249. potentially use them are freed. By storing them in the main interpreter, we
  250. ensure they get freed after all other interpreters are freed.
  251. */
  252. static bool
  253. has_shared_intern_dict(PyInterpreterState *interp)
  254. {
  255. PyInterpreterState *main_interp = _PyInterpreterState_Main();
  256. return interp != main_interp && interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC;
  257. }
  258. static int
  259. init_interned_dict(PyInterpreterState *interp)
  260. {
  261. assert(get_interned_dict(interp) == NULL);
  262. PyObject *interned;
  263. if (has_shared_intern_dict(interp)) {
  264. interned = get_interned_dict(_PyInterpreterState_Main());
  265. Py_INCREF(interned);
  266. }
  267. else {
  268. interned = PyDict_New();
  269. if (interned == NULL) {
  270. return -1;
  271. }
  272. }
  273. _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = interned;
  274. return 0;
  275. }
  276. static void
  277. clear_interned_dict(PyInterpreterState *interp)
  278. {
  279. PyObject *interned = get_interned_dict(interp);
  280. if (interned != NULL) {
  281. if (!has_shared_intern_dict(interp)) {
  282. // only clear if the dict belongs to this interpreter
  283. PyDict_Clear(interned);
  284. }
  285. Py_DECREF(interned);
  286. _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = NULL;
  287. }
  288. }
  289. static PyStatus
  290. init_global_interned_strings(PyInterpreterState *interp)
  291. {
  292. assert(INTERNED_STRINGS == NULL);
  293. _Py_hashtable_allocator_t hashtable_alloc = {PyMem_RawMalloc, PyMem_RawFree};
  294. INTERNED_STRINGS = _Py_hashtable_new_full(
  295. hashtable_unicode_hash,
  296. hashtable_unicode_compare,
  297. // Objects stored here are immortal and statically allocated,
  298. // so we don't need key_destroy_func & value_destroy_func:
  299. NULL,
  300. NULL,
  301. &hashtable_alloc
  302. );
  303. if (INTERNED_STRINGS == NULL) {
  304. PyErr_Clear();
  305. return _PyStatus_ERR("failed to create global interned dict");
  306. }
  307. /* Intern statically allocated string identifiers, deepfreeze strings,
  308. * and one-byte latin-1 strings.
  309. * This must be done before any module initialization so that statically
  310. * allocated string identifiers are used instead of heap allocated strings.
  311. * Deepfreeze uses the interned identifiers if present to save space
  312. * else generates them and they are interned to speed up dict lookups.
  313. */
  314. _PyUnicode_InitStaticStrings(interp);
  315. for (int i = 0; i < 256; i++) {
  316. PyObject *s = LATIN1(i);
  317. _PyUnicode_InternStatic(interp, &s);
  318. assert(s == LATIN1(i));
  319. }
  320. #ifdef Py_DEBUG
  321. assert(_PyUnicode_CheckConsistency(&_Py_STR(empty), 1));
  322. for (int i = 0; i < 256; i++) {
  323. assert(_PyUnicode_CheckConsistency(LATIN1(i), 1));
  324. }
  325. #endif
  326. return _PyStatus_OK();
  327. }
  328. static void clear_global_interned_strings(void)
  329. {
  330. if (INTERNED_STRINGS != NULL) {
  331. _Py_hashtable_destroy(INTERNED_STRINGS);
  332. INTERNED_STRINGS = NULL;
  333. }
  334. }
  335. #define _Py_RETURN_UNICODE_EMPTY() \
  336. do { \
  337. return unicode_new_empty(); \
  338. } while (0)
  339. static inline void
  340. unicode_fill(int kind, void *data, Py_UCS4 value,
  341. Py_ssize_t start, Py_ssize_t length)
  342. {
  343. assert(0 <= start);
  344. switch (kind) {
  345. case PyUnicode_1BYTE_KIND: {
  346. assert(value <= 0xff);
  347. Py_UCS1 ch = (unsigned char)value;
  348. Py_UCS1 *to = (Py_UCS1 *)data + start;
  349. memset(to, ch, length);
  350. break;
  351. }
  352. case PyUnicode_2BYTE_KIND: {
  353. assert(value <= 0xffff);
  354. Py_UCS2 ch = (Py_UCS2)value;
  355. Py_UCS2 *to = (Py_UCS2 *)data + start;
  356. const Py_UCS2 *end = to + length;
  357. for (; to < end; ++to) *to = ch;
  358. break;
  359. }
  360. case PyUnicode_4BYTE_KIND: {
  361. assert(value <= MAX_UNICODE);
  362. Py_UCS4 ch = value;
  363. Py_UCS4 * to = (Py_UCS4 *)data + start;
  364. const Py_UCS4 *end = to + length;
  365. for (; to < end; ++to) *to = ch;
  366. break;
  367. }
  368. default: Py_UNREACHABLE();
  369. }
  370. }
  371. /* Fast detection of the most frequent whitespace characters */
  372. const unsigned char _Py_ascii_whitespace[] = {
  373. 0, 0, 0, 0, 0, 0, 0, 0,
  374. /* case 0x0009: * CHARACTER TABULATION */
  375. /* case 0x000A: * LINE FEED */
  376. /* case 0x000B: * LINE TABULATION */
  377. /* case 0x000C: * FORM FEED */
  378. /* case 0x000D: * CARRIAGE RETURN */
  379. 0, 1, 1, 1, 1, 1, 0, 0,
  380. 0, 0, 0, 0, 0, 0, 0, 0,
  381. /* case 0x001C: * FILE SEPARATOR */
  382. /* case 0x001D: * GROUP SEPARATOR */
  383. /* case 0x001E: * RECORD SEPARATOR */
  384. /* case 0x001F: * UNIT SEPARATOR */
  385. 0, 0, 0, 0, 1, 1, 1, 1,
  386. /* case 0x0020: * SPACE */
  387. 1, 0, 0, 0, 0, 0, 0, 0,
  388. 0, 0, 0, 0, 0, 0, 0, 0,
  389. 0, 0, 0, 0, 0, 0, 0, 0,
  390. 0, 0, 0, 0, 0, 0, 0, 0,
  391. 0, 0, 0, 0, 0, 0, 0, 0,
  392. 0, 0, 0, 0, 0, 0, 0, 0,
  393. 0, 0, 0, 0, 0, 0, 0, 0,
  394. 0, 0, 0, 0, 0, 0, 0, 0,
  395. 0, 0, 0, 0, 0, 0, 0, 0,
  396. 0, 0, 0, 0, 0, 0, 0, 0,
  397. 0, 0, 0, 0, 0, 0, 0, 0,
  398. 0, 0, 0, 0, 0, 0, 0, 0
  399. };
  400. /* forward */
  401. static PyObject* get_latin1_char(unsigned char ch);
  402. static int unicode_modifiable(PyObject *unicode);
  403. static PyObject *
  404. _PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
  405. static PyObject *
  406. _PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
  407. static PyObject *
  408. _PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
  409. static PyObject *
  410. unicode_encode_call_errorhandler(const char *errors,
  411. PyObject **errorHandler,const char *encoding, const char *reason,
  412. PyObject *unicode, PyObject **exceptionObject,
  413. Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
  414. static void
  415. raise_encode_exception(PyObject **exceptionObject,
  416. const char *encoding,
  417. PyObject *unicode,
  418. Py_ssize_t startpos, Py_ssize_t endpos,
  419. const char *reason);
  420. /* Same for linebreaks */
  421. static const unsigned char ascii_linebreak[] = {
  422. 0, 0, 0, 0, 0, 0, 0, 0,
  423. /* 0x000A, * LINE FEED */
  424. /* 0x000B, * LINE TABULATION */
  425. /* 0x000C, * FORM FEED */
  426. /* 0x000D, * CARRIAGE RETURN */
  427. 0, 0, 1, 1, 1, 1, 0, 0,
  428. 0, 0, 0, 0, 0, 0, 0, 0,
  429. /* 0x001C, * FILE SEPARATOR */
  430. /* 0x001D, * GROUP SEPARATOR */
  431. /* 0x001E, * RECORD SEPARATOR */
  432. 0, 0, 0, 0, 1, 1, 1, 0,
  433. 0, 0, 0, 0, 0, 0, 0, 0,
  434. 0, 0, 0, 0, 0, 0, 0, 0,
  435. 0, 0, 0, 0, 0, 0, 0, 0,
  436. 0, 0, 0, 0, 0, 0, 0, 0,
  437. 0, 0, 0, 0, 0, 0, 0, 0,
  438. 0, 0, 0, 0, 0, 0, 0, 0,
  439. 0, 0, 0, 0, 0, 0, 0, 0,
  440. 0, 0, 0, 0, 0, 0, 0, 0,
  441. 0, 0, 0, 0, 0, 0, 0, 0,
  442. 0, 0, 0, 0, 0, 0, 0, 0,
  443. 0, 0, 0, 0, 0, 0, 0, 0,
  444. 0, 0, 0, 0, 0, 0, 0, 0
  445. };
  446. static int convert_uc(PyObject *obj, void *addr);
  447. struct encoding_map;
  448. #include "clinic/unicodeobject.c.h"
  449. _Py_error_handler
  450. _Py_GetErrorHandler(const char *errors)
  451. {
  452. if (errors == NULL || strcmp(errors, "strict") == 0) {
  453. return _Py_ERROR_STRICT;
  454. }
  455. if (strcmp(errors, "surrogateescape") == 0) {
  456. return _Py_ERROR_SURROGATEESCAPE;
  457. }
  458. if (strcmp(errors, "replace") == 0) {
  459. return _Py_ERROR_REPLACE;
  460. }
  461. if (strcmp(errors, "ignore") == 0) {
  462. return _Py_ERROR_IGNORE;
  463. }
  464. if (strcmp(errors, "backslashreplace") == 0) {
  465. return _Py_ERROR_BACKSLASHREPLACE;
  466. }
  467. if (strcmp(errors, "surrogatepass") == 0) {
  468. return _Py_ERROR_SURROGATEPASS;
  469. }
  470. if (strcmp(errors, "xmlcharrefreplace") == 0) {
  471. return _Py_ERROR_XMLCHARREFREPLACE;
  472. }
  473. return _Py_ERROR_OTHER;
  474. }
  475. static _Py_error_handler
  476. get_error_handler_wide(const wchar_t *errors)
  477. {
  478. if (errors == NULL || wcscmp(errors, L"strict") == 0) {
  479. return _Py_ERROR_STRICT;
  480. }
  481. if (wcscmp(errors, L"surrogateescape") == 0) {
  482. return _Py_ERROR_SURROGATEESCAPE;
  483. }
  484. if (wcscmp(errors, L"replace") == 0) {
  485. return _Py_ERROR_REPLACE;
  486. }
  487. if (wcscmp(errors, L"ignore") == 0) {
  488. return _Py_ERROR_IGNORE;
  489. }
  490. if (wcscmp(errors, L"backslashreplace") == 0) {
  491. return _Py_ERROR_BACKSLASHREPLACE;
  492. }
  493. if (wcscmp(errors, L"surrogatepass") == 0) {
  494. return _Py_ERROR_SURROGATEPASS;
  495. }
  496. if (wcscmp(errors, L"xmlcharrefreplace") == 0) {
  497. return _Py_ERROR_XMLCHARREFREPLACE;
  498. }
  499. return _Py_ERROR_OTHER;
  500. }
  501. static inline int
  502. unicode_check_encoding_errors(const char *encoding, const char *errors)
  503. {
  504. if (encoding == NULL && errors == NULL) {
  505. return 0;
  506. }
  507. PyInterpreterState *interp = _PyInterpreterState_GET();
  508. #ifndef Py_DEBUG
  509. /* In release mode, only check in development mode (-X dev) */
  510. if (!_PyInterpreterState_GetConfig(interp)->dev_mode) {
  511. return 0;
  512. }
  513. #else
  514. /* Always check in debug mode */
  515. #endif
  516. /* Avoid calling _PyCodec_Lookup() and PyCodec_LookupError() before the
  517. codec registry is ready: before_PyUnicode_InitEncodings() is called. */
  518. if (!interp->unicode.fs_codec.encoding) {
  519. return 0;
  520. }
  521. /* Disable checks during Python finalization. For example, it allows to
  522. call _PyObject_Dump() during finalization for debugging purpose. */
  523. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  524. return 0;
  525. }
  526. if (encoding != NULL
  527. // Fast path for the most common built-in encodings. Even if the codec
  528. // is cached, _PyCodec_Lookup() decodes the bytes string from UTF-8 to
  529. // create a temporary Unicode string (the key in the cache).
  530. && strcmp(encoding, "utf-8") != 0
  531. && strcmp(encoding, "utf8") != 0
  532. && strcmp(encoding, "ascii") != 0)
  533. {
  534. PyObject *handler = _PyCodec_Lookup(encoding);
  535. if (handler == NULL) {
  536. return -1;
  537. }
  538. Py_DECREF(handler);
  539. }
  540. if (errors != NULL
  541. // Fast path for the most common built-in error handlers.
  542. && strcmp(errors, "strict") != 0
  543. && strcmp(errors, "ignore") != 0
  544. && strcmp(errors, "replace") != 0
  545. && strcmp(errors, "surrogateescape") != 0
  546. && strcmp(errors, "surrogatepass") != 0)
  547. {
  548. PyObject *handler = PyCodec_LookupError(errors);
  549. if (handler == NULL) {
  550. return -1;
  551. }
  552. Py_DECREF(handler);
  553. }
  554. return 0;
  555. }
  556. int
  557. _PyUnicode_CheckConsistency(PyObject *op, int check_content)
  558. {
  559. #define CHECK(expr) \
  560. do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
  561. assert(op != NULL);
  562. CHECK(PyUnicode_Check(op));
  563. PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
  564. int kind = ascii->state.kind;
  565. if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
  566. CHECK(kind == PyUnicode_1BYTE_KIND);
  567. }
  568. else {
  569. PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
  570. void *data;
  571. if (ascii->state.compact == 1) {
  572. data = compact + 1;
  573. CHECK(kind == PyUnicode_1BYTE_KIND
  574. || kind == PyUnicode_2BYTE_KIND
  575. || kind == PyUnicode_4BYTE_KIND);
  576. CHECK(ascii->state.ascii == 0);
  577. CHECK(compact->utf8 != data);
  578. }
  579. else {
  580. PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
  581. data = unicode->data.any;
  582. CHECK(kind == PyUnicode_1BYTE_KIND
  583. || kind == PyUnicode_2BYTE_KIND
  584. || kind == PyUnicode_4BYTE_KIND);
  585. CHECK(ascii->state.compact == 0);
  586. CHECK(data != NULL);
  587. if (ascii->state.ascii) {
  588. CHECK(compact->utf8 == data);
  589. CHECK(compact->utf8_length == ascii->length);
  590. }
  591. else {
  592. CHECK(compact->utf8 != data);
  593. }
  594. }
  595. if (compact->utf8 == NULL)
  596. CHECK(compact->utf8_length == 0);
  597. }
  598. /* check that the best kind is used: O(n) operation */
  599. if (check_content) {
  600. Py_ssize_t i;
  601. Py_UCS4 maxchar = 0;
  602. const void *data;
  603. Py_UCS4 ch;
  604. data = PyUnicode_DATA(ascii);
  605. for (i=0; i < ascii->length; i++)
  606. {
  607. ch = PyUnicode_READ(kind, data, i);
  608. if (ch > maxchar)
  609. maxchar = ch;
  610. }
  611. if (kind == PyUnicode_1BYTE_KIND) {
  612. if (ascii->state.ascii == 0) {
  613. CHECK(maxchar >= 128);
  614. CHECK(maxchar <= 255);
  615. }
  616. else
  617. CHECK(maxchar < 128);
  618. }
  619. else if (kind == PyUnicode_2BYTE_KIND) {
  620. CHECK(maxchar >= 0x100);
  621. CHECK(maxchar <= 0xFFFF);
  622. }
  623. else {
  624. CHECK(maxchar >= 0x10000);
  625. CHECK(maxchar <= MAX_UNICODE);
  626. }
  627. CHECK(PyUnicode_READ(kind, data, ascii->length) == 0);
  628. }
  629. /* Check interning state */
  630. #ifdef Py_DEBUG
  631. // Note that we do not check `_Py_IsImmortal(op)`, since stable ABI
  632. // extensions can make immortal strings mortal (but with a high enough
  633. // refcount).
  634. // The other way is extremely unlikely (worth a potential failed assertion
  635. // in a debug build), so we do check `!_Py_IsImmortal(op)`.
  636. switch (PyUnicode_CHECK_INTERNED(op)) {
  637. case SSTATE_NOT_INTERNED:
  638. if (ascii->state.statically_allocated) {
  639. // This state is for two exceptions:
  640. // - strings are currently checked before they're interned
  641. // - the 256 one-latin1-character strings
  642. // are static but use SSTATE_NOT_INTERNED
  643. }
  644. else {
  645. CHECK(!_Py_IsImmortal(op));
  646. }
  647. break;
  648. case SSTATE_INTERNED_MORTAL:
  649. CHECK(!ascii->state.statically_allocated);
  650. CHECK(!_Py_IsImmortal(op));
  651. break;
  652. case SSTATE_INTERNED_IMMORTAL:
  653. CHECK(!ascii->state.statically_allocated);
  654. break;
  655. case SSTATE_INTERNED_IMMORTAL_STATIC:
  656. CHECK(ascii->state.statically_allocated);
  657. break;
  658. default:
  659. Py_UNREACHABLE();
  660. }
  661. #endif
  662. return 1;
  663. #undef CHECK
  664. }
  665. static PyObject*
  666. unicode_result(PyObject *unicode)
  667. {
  668. assert(_PyUnicode_CHECK(unicode));
  669. Py_ssize_t length = PyUnicode_GET_LENGTH(unicode);
  670. if (length == 0) {
  671. PyObject *empty = unicode_get_empty();
  672. if (unicode != empty) {
  673. Py_DECREF(unicode);
  674. Py_INCREF(empty);
  675. }
  676. return empty;
  677. }
  678. if (length == 1) {
  679. int kind = PyUnicode_KIND(unicode);
  680. if (kind == PyUnicode_1BYTE_KIND) {
  681. const Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
  682. Py_UCS1 ch = data[0];
  683. PyObject *latin1_char = LATIN1(ch);
  684. if (unicode != latin1_char) {
  685. Py_INCREF(latin1_char);
  686. Py_DECREF(unicode);
  687. }
  688. return latin1_char;
  689. }
  690. }
  691. assert(_PyUnicode_CheckConsistency(unicode, 1));
  692. return unicode;
  693. }
  694. static PyObject*
  695. unicode_result_unchanged(PyObject *unicode)
  696. {
  697. if (PyUnicode_CheckExact(unicode)) {
  698. return Py_NewRef(unicode);
  699. }
  700. else
  701. /* Subtype -- return genuine unicode string with the same value. */
  702. return _PyUnicode_Copy(unicode);
  703. }
  704. /* Implementation of the "backslashreplace" error handler for 8-bit encodings:
  705. ASCII, Latin1, UTF-8, etc. */
  706. static char*
  707. backslashreplace(_PyBytesWriter *writer, char *str,
  708. PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
  709. {
  710. Py_ssize_t size, i;
  711. Py_UCS4 ch;
  712. int kind;
  713. const void *data;
  714. kind = PyUnicode_KIND(unicode);
  715. data = PyUnicode_DATA(unicode);
  716. size = 0;
  717. /* determine replacement size */
  718. for (i = collstart; i < collend; ++i) {
  719. Py_ssize_t incr;
  720. ch = PyUnicode_READ(kind, data, i);
  721. if (ch < 0x100)
  722. incr = 2+2;
  723. else if (ch < 0x10000)
  724. incr = 2+4;
  725. else {
  726. assert(ch <= MAX_UNICODE);
  727. incr = 2+8;
  728. }
  729. if (size > PY_SSIZE_T_MAX - incr) {
  730. PyErr_SetString(PyExc_OverflowError,
  731. "encoded result is too long for a Python string");
  732. return NULL;
  733. }
  734. size += incr;
  735. }
  736. str = _PyBytesWriter_Prepare(writer, str, size);
  737. if (str == NULL)
  738. return NULL;
  739. /* generate replacement */
  740. for (i = collstart; i < collend; ++i) {
  741. ch = PyUnicode_READ(kind, data, i);
  742. *str++ = '\\';
  743. if (ch >= 0x00010000) {
  744. *str++ = 'U';
  745. *str++ = Py_hexdigits[(ch>>28)&0xf];
  746. *str++ = Py_hexdigits[(ch>>24)&0xf];
  747. *str++ = Py_hexdigits[(ch>>20)&0xf];
  748. *str++ = Py_hexdigits[(ch>>16)&0xf];
  749. *str++ = Py_hexdigits[(ch>>12)&0xf];
  750. *str++ = Py_hexdigits[(ch>>8)&0xf];
  751. }
  752. else if (ch >= 0x100) {
  753. *str++ = 'u';
  754. *str++ = Py_hexdigits[(ch>>12)&0xf];
  755. *str++ = Py_hexdigits[(ch>>8)&0xf];
  756. }
  757. else
  758. *str++ = 'x';
  759. *str++ = Py_hexdigits[(ch>>4)&0xf];
  760. *str++ = Py_hexdigits[ch&0xf];
  761. }
  762. return str;
  763. }
  764. /* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
  765. ASCII, Latin1, UTF-8, etc. */
  766. static char*
  767. xmlcharrefreplace(_PyBytesWriter *writer, char *str,
  768. PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
  769. {
  770. Py_ssize_t size, i;
  771. Py_UCS4 ch;
  772. int kind;
  773. const void *data;
  774. kind = PyUnicode_KIND(unicode);
  775. data = PyUnicode_DATA(unicode);
  776. size = 0;
  777. /* determine replacement size */
  778. for (i = collstart; i < collend; ++i) {
  779. Py_ssize_t incr;
  780. ch = PyUnicode_READ(kind, data, i);
  781. if (ch < 10)
  782. incr = 2+1+1;
  783. else if (ch < 100)
  784. incr = 2+2+1;
  785. else if (ch < 1000)
  786. incr = 2+3+1;
  787. else if (ch < 10000)
  788. incr = 2+4+1;
  789. else if (ch < 100000)
  790. incr = 2+5+1;
  791. else if (ch < 1000000)
  792. incr = 2+6+1;
  793. else {
  794. assert(ch <= MAX_UNICODE);
  795. incr = 2+7+1;
  796. }
  797. if (size > PY_SSIZE_T_MAX - incr) {
  798. PyErr_SetString(PyExc_OverflowError,
  799. "encoded result is too long for a Python string");
  800. return NULL;
  801. }
  802. size += incr;
  803. }
  804. str = _PyBytesWriter_Prepare(writer, str, size);
  805. if (str == NULL)
  806. return NULL;
  807. /* generate replacement */
  808. for (i = collstart; i < collend; ++i) {
  809. size = sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
  810. if (size < 0) {
  811. return NULL;
  812. }
  813. str += size;
  814. }
  815. return str;
  816. }
  817. /* --- Bloom Filters ----------------------------------------------------- */
  818. /* stuff to implement simple "bloom filters" for Unicode characters.
  819. to keep things simple, we use a single bitmask, using the least 5
  820. bits from each unicode characters as the bit index. */
  821. /* the linebreak mask is set up by _PyUnicode_Init() below */
  822. #if LONG_BIT >= 128
  823. #define BLOOM_WIDTH 128
  824. #elif LONG_BIT >= 64
  825. #define BLOOM_WIDTH 64
  826. #elif LONG_BIT >= 32
  827. #define BLOOM_WIDTH 32
  828. #else
  829. #error "LONG_BIT is smaller than 32"
  830. #endif
  831. #define BLOOM_MASK unsigned long
  832. static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
  833. #define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
  834. #define BLOOM_LINEBREAK(ch) \
  835. ((ch) < 128U ? ascii_linebreak[(ch)] : \
  836. (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
  837. static inline BLOOM_MASK
  838. make_bloom_mask(int kind, const void* ptr, Py_ssize_t len)
  839. {
  840. #define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
  841. do { \
  842. TYPE *data = (TYPE *)PTR; \
  843. TYPE *end = data + LEN; \
  844. Py_UCS4 ch; \
  845. for (; data != end; data++) { \
  846. ch = *data; \
  847. MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
  848. } \
  849. break; \
  850. } while (0)
  851. /* calculate simple bloom-style bitmask for a given unicode string */
  852. BLOOM_MASK mask;
  853. mask = 0;
  854. switch (kind) {
  855. case PyUnicode_1BYTE_KIND:
  856. BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
  857. break;
  858. case PyUnicode_2BYTE_KIND:
  859. BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
  860. break;
  861. case PyUnicode_4BYTE_KIND:
  862. BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
  863. break;
  864. default:
  865. Py_UNREACHABLE();
  866. }
  867. return mask;
  868. #undef BLOOM_UPDATE
  869. }
  870. static int
  871. ensure_unicode(PyObject *obj)
  872. {
  873. if (!PyUnicode_Check(obj)) {
  874. PyErr_Format(PyExc_TypeError,
  875. "must be str, not %.100s",
  876. Py_TYPE(obj)->tp_name);
  877. return -1;
  878. }
  879. return 0;
  880. }
  881. /* Compilation of templated routines */
  882. #define STRINGLIB_GET_EMPTY() unicode_get_empty()
  883. #include "stringlib/asciilib.h"
  884. #include "stringlib/fastsearch.h"
  885. #include "stringlib/partition.h"
  886. #include "stringlib/split.h"
  887. #include "stringlib/count.h"
  888. #include "stringlib/find.h"
  889. #include "stringlib/find_max_char.h"
  890. #include "stringlib/undef.h"
  891. #include "stringlib/ucs1lib.h"
  892. #include "stringlib/fastsearch.h"
  893. #include "stringlib/partition.h"
  894. #include "stringlib/split.h"
  895. #include "stringlib/count.h"
  896. #include "stringlib/find.h"
  897. #include "stringlib/replace.h"
  898. #include "stringlib/find_max_char.h"
  899. #include "stringlib/undef.h"
  900. #include "stringlib/ucs2lib.h"
  901. #include "stringlib/fastsearch.h"
  902. #include "stringlib/partition.h"
  903. #include "stringlib/split.h"
  904. #include "stringlib/count.h"
  905. #include "stringlib/find.h"
  906. #include "stringlib/replace.h"
  907. #include "stringlib/find_max_char.h"
  908. #include "stringlib/undef.h"
  909. #include "stringlib/ucs4lib.h"
  910. #include "stringlib/fastsearch.h"
  911. #include "stringlib/partition.h"
  912. #include "stringlib/split.h"
  913. #include "stringlib/count.h"
  914. #include "stringlib/find.h"
  915. #include "stringlib/replace.h"
  916. #include "stringlib/find_max_char.h"
  917. #include "stringlib/undef.h"
  918. #undef STRINGLIB_GET_EMPTY
  919. /* --- Unicode Object ----------------------------------------------------- */
  920. static inline Py_ssize_t
  921. findchar(const void *s, int kind,
  922. Py_ssize_t size, Py_UCS4 ch,
  923. int direction)
  924. {
  925. switch (kind) {
  926. case PyUnicode_1BYTE_KIND:
  927. if ((Py_UCS1) ch != ch)
  928. return -1;
  929. if (direction > 0)
  930. return ucs1lib_find_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
  931. else
  932. return ucs1lib_rfind_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
  933. case PyUnicode_2BYTE_KIND:
  934. if ((Py_UCS2) ch != ch)
  935. return -1;
  936. if (direction > 0)
  937. return ucs2lib_find_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
  938. else
  939. return ucs2lib_rfind_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
  940. case PyUnicode_4BYTE_KIND:
  941. if (direction > 0)
  942. return ucs4lib_find_char((const Py_UCS4 *) s, size, ch);
  943. else
  944. return ucs4lib_rfind_char((const Py_UCS4 *) s, size, ch);
  945. default:
  946. Py_UNREACHABLE();
  947. }
  948. }
  949. #ifdef Py_DEBUG
  950. /* Fill the data of a Unicode string with invalid characters to detect bugs
  951. earlier.
  952. _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
  953. ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
  954. invalid character in Unicode 6.0. */
  955. static void
  956. unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
  957. {
  958. int kind = PyUnicode_KIND(unicode);
  959. Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
  960. Py_ssize_t length = _PyUnicode_LENGTH(unicode);
  961. if (length <= old_length)
  962. return;
  963. memset(data + old_length * kind, 0xff, (length - old_length) * kind);
  964. }
  965. #endif
  966. static PyObject*
  967. resize_compact(PyObject *unicode, Py_ssize_t length)
  968. {
  969. Py_ssize_t char_size;
  970. Py_ssize_t struct_size;
  971. Py_ssize_t new_size;
  972. PyObject *new_unicode;
  973. #ifdef Py_DEBUG
  974. Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
  975. #endif
  976. assert(unicode_modifiable(unicode));
  977. assert(PyUnicode_IS_COMPACT(unicode));
  978. char_size = PyUnicode_KIND(unicode);
  979. if (PyUnicode_IS_ASCII(unicode))
  980. struct_size = sizeof(PyASCIIObject);
  981. else
  982. struct_size = sizeof(PyCompactUnicodeObject);
  983. if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
  984. PyErr_NoMemory();
  985. return NULL;
  986. }
  987. new_size = (struct_size + (length + 1) * char_size);
  988. if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
  989. PyObject_Free(_PyUnicode_UTF8(unicode));
  990. _PyUnicode_UTF8(unicode) = NULL;
  991. _PyUnicode_UTF8_LENGTH(unicode) = 0;
  992. }
  993. #ifdef Py_TRACE_REFS
  994. _Py_ForgetReference(unicode);
  995. #endif
  996. new_unicode = (PyObject *)PyObject_Realloc(unicode, new_size);
  997. if (new_unicode == NULL) {
  998. _Py_NewReferenceNoTotal(unicode);
  999. PyErr_NoMemory();
  1000. return NULL;
  1001. }
  1002. unicode = new_unicode;
  1003. _Py_NewReferenceNoTotal(unicode);
  1004. _PyUnicode_LENGTH(unicode) = length;
  1005. #ifdef Py_DEBUG
  1006. unicode_fill_invalid(unicode, old_length);
  1007. #endif
  1008. PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
  1009. length, 0);
  1010. assert(_PyUnicode_CheckConsistency(unicode, 0));
  1011. return unicode;
  1012. }
  1013. static int
  1014. resize_inplace(PyObject *unicode, Py_ssize_t length)
  1015. {
  1016. assert(!PyUnicode_IS_COMPACT(unicode));
  1017. assert(Py_REFCNT(unicode) == 1);
  1018. Py_ssize_t new_size;
  1019. Py_ssize_t char_size;
  1020. int share_utf8;
  1021. void *data;
  1022. #ifdef Py_DEBUG
  1023. Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
  1024. #endif
  1025. data = _PyUnicode_DATA_ANY(unicode);
  1026. char_size = PyUnicode_KIND(unicode);
  1027. share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
  1028. if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
  1029. PyErr_NoMemory();
  1030. return -1;
  1031. }
  1032. new_size = (length + 1) * char_size;
  1033. if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
  1034. {
  1035. PyObject_Free(_PyUnicode_UTF8(unicode));
  1036. _PyUnicode_UTF8(unicode) = NULL;
  1037. _PyUnicode_UTF8_LENGTH(unicode) = 0;
  1038. }
  1039. data = (PyObject *)PyObject_Realloc(data, new_size);
  1040. if (data == NULL) {
  1041. PyErr_NoMemory();
  1042. return -1;
  1043. }
  1044. _PyUnicode_DATA_ANY(unicode) = data;
  1045. if (share_utf8) {
  1046. _PyUnicode_UTF8(unicode) = data;
  1047. _PyUnicode_UTF8_LENGTH(unicode) = length;
  1048. }
  1049. _PyUnicode_LENGTH(unicode) = length;
  1050. PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
  1051. #ifdef Py_DEBUG
  1052. unicode_fill_invalid(unicode, old_length);
  1053. #endif
  1054. /* check for integer overflow */
  1055. if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
  1056. PyErr_NoMemory();
  1057. return -1;
  1058. }
  1059. assert(_PyUnicode_CheckConsistency(unicode, 0));
  1060. return 0;
  1061. }
  1062. static PyObject*
  1063. resize_copy(PyObject *unicode, Py_ssize_t length)
  1064. {
  1065. Py_ssize_t copy_length;
  1066. PyObject *copy;
  1067. copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
  1068. if (copy == NULL)
  1069. return NULL;
  1070. copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
  1071. _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
  1072. return copy;
  1073. }
  1074. static const char*
  1075. unicode_kind_name(PyObject *unicode)
  1076. {
  1077. /* don't check consistency: unicode_kind_name() is called from
  1078. _PyUnicode_Dump() */
  1079. if (!PyUnicode_IS_COMPACT(unicode))
  1080. {
  1081. switch (PyUnicode_KIND(unicode))
  1082. {
  1083. case PyUnicode_1BYTE_KIND:
  1084. if (PyUnicode_IS_ASCII(unicode))
  1085. return "legacy ascii";
  1086. else
  1087. return "legacy latin1";
  1088. case PyUnicode_2BYTE_KIND:
  1089. return "legacy UCS2";
  1090. case PyUnicode_4BYTE_KIND:
  1091. return "legacy UCS4";
  1092. default:
  1093. return "<legacy invalid kind>";
  1094. }
  1095. }
  1096. switch (PyUnicode_KIND(unicode)) {
  1097. case PyUnicode_1BYTE_KIND:
  1098. if (PyUnicode_IS_ASCII(unicode))
  1099. return "ascii";
  1100. else
  1101. return "latin1";
  1102. case PyUnicode_2BYTE_KIND:
  1103. return "UCS2";
  1104. case PyUnicode_4BYTE_KIND:
  1105. return "UCS4";
  1106. default:
  1107. return "<invalid compact kind>";
  1108. }
  1109. }
  1110. #ifdef Py_DEBUG
  1111. /* Functions wrapping macros for use in debugger */
  1112. const char *_PyUnicode_utf8(void *unicode_raw){
  1113. PyObject *unicode = _PyObject_CAST(unicode_raw);
  1114. return PyUnicode_UTF8(unicode);
  1115. }
  1116. const void *_PyUnicode_compact_data(void *unicode_raw) {
  1117. PyObject *unicode = _PyObject_CAST(unicode_raw);
  1118. return _PyUnicode_COMPACT_DATA(unicode);
  1119. }
  1120. const void *_PyUnicode_data(void *unicode_raw) {
  1121. PyObject *unicode = _PyObject_CAST(unicode_raw);
  1122. printf("obj %p\n", (void*)unicode);
  1123. printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
  1124. printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
  1125. printf("ascii op %p\n", (void*)(_PyASCIIObject_CAST(unicode) + 1));
  1126. printf("compact op %p\n", (void*)(_PyCompactUnicodeObject_CAST(unicode) + 1));
  1127. printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
  1128. return PyUnicode_DATA(unicode);
  1129. }
  1130. void
  1131. _PyUnicode_Dump(PyObject *op)
  1132. {
  1133. PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
  1134. PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
  1135. PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
  1136. const void *data;
  1137. if (ascii->state.compact)
  1138. {
  1139. if (ascii->state.ascii)
  1140. data = (ascii + 1);
  1141. else
  1142. data = (compact + 1);
  1143. }
  1144. else
  1145. data = unicode->data.any;
  1146. printf("%s: len=%zu, ", unicode_kind_name(op), ascii->length);
  1147. if (!ascii->state.ascii) {
  1148. printf("utf8=%p (%zu)", (void *)compact->utf8, compact->utf8_length);
  1149. }
  1150. printf(", data=%p\n", data);
  1151. }
  1152. #endif
  1153. PyObject *
  1154. PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
  1155. {
  1156. /* Optimization for empty strings */
  1157. if (size == 0) {
  1158. return unicode_new_empty();
  1159. }
  1160. PyObject *obj;
  1161. PyCompactUnicodeObject *unicode;
  1162. void *data;
  1163. int kind;
  1164. int is_ascii;
  1165. Py_ssize_t char_size;
  1166. Py_ssize_t struct_size;
  1167. is_ascii = 0;
  1168. struct_size = sizeof(PyCompactUnicodeObject);
  1169. if (maxchar < 128) {
  1170. kind = PyUnicode_1BYTE_KIND;
  1171. char_size = 1;
  1172. is_ascii = 1;
  1173. struct_size = sizeof(PyASCIIObject);
  1174. }
  1175. else if (maxchar < 256) {
  1176. kind = PyUnicode_1BYTE_KIND;
  1177. char_size = 1;
  1178. }
  1179. else if (maxchar < 65536) {
  1180. kind = PyUnicode_2BYTE_KIND;
  1181. char_size = 2;
  1182. }
  1183. else {
  1184. if (maxchar > MAX_UNICODE) {
  1185. PyErr_SetString(PyExc_SystemError,
  1186. "invalid maximum character passed to PyUnicode_New");
  1187. return NULL;
  1188. }
  1189. kind = PyUnicode_4BYTE_KIND;
  1190. char_size = 4;
  1191. }
  1192. /* Ensure we won't overflow the size. */
  1193. if (size < 0) {
  1194. PyErr_SetString(PyExc_SystemError,
  1195. "Negative size passed to PyUnicode_New");
  1196. return NULL;
  1197. }
  1198. if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
  1199. return PyErr_NoMemory();
  1200. /* Duplicated allocation code from _PyObject_New() instead of a call to
  1201. * PyObject_New() so we are able to allocate space for the object and
  1202. * it's data buffer.
  1203. */
  1204. obj = (PyObject *) PyObject_Malloc(struct_size + (size + 1) * char_size);
  1205. if (obj == NULL) {
  1206. return PyErr_NoMemory();
  1207. }
  1208. _PyObject_Init(obj, &PyUnicode_Type);
  1209. unicode = (PyCompactUnicodeObject *)obj;
  1210. if (is_ascii)
  1211. data = ((PyASCIIObject*)obj) + 1;
  1212. else
  1213. data = unicode + 1;
  1214. _PyUnicode_LENGTH(unicode) = size;
  1215. _PyUnicode_HASH(unicode) = -1;
  1216. _PyUnicode_STATE(unicode).interned = 0;
  1217. _PyUnicode_STATE(unicode).kind = kind;
  1218. _PyUnicode_STATE(unicode).compact = 1;
  1219. _PyUnicode_STATE(unicode).ascii = is_ascii;
  1220. _PyUnicode_STATE(unicode).statically_allocated = 0;
  1221. if (is_ascii) {
  1222. ((char*)data)[size] = 0;
  1223. }
  1224. else if (kind == PyUnicode_1BYTE_KIND) {
  1225. ((char*)data)[size] = 0;
  1226. unicode->utf8 = NULL;
  1227. unicode->utf8_length = 0;
  1228. }
  1229. else {
  1230. unicode->utf8 = NULL;
  1231. unicode->utf8_length = 0;
  1232. if (kind == PyUnicode_2BYTE_KIND)
  1233. ((Py_UCS2*)data)[size] = 0;
  1234. else /* kind == PyUnicode_4BYTE_KIND */
  1235. ((Py_UCS4*)data)[size] = 0;
  1236. }
  1237. #ifdef Py_DEBUG
  1238. unicode_fill_invalid((PyObject*)unicode, 0);
  1239. #endif
  1240. assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
  1241. return obj;
  1242. }
  1243. #if SIZEOF_WCHAR_T == 2
  1244. /* Helper function to convert a 16-bits wchar_t representation to UCS4, this
  1245. will decode surrogate pairs, the other conversions are implemented as macros
  1246. for efficiency.
  1247. This function assumes that unicode can hold one more code point than wstr
  1248. characters for a terminating null character. */
  1249. static void
  1250. unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
  1251. PyObject *unicode)
  1252. {
  1253. const wchar_t *iter;
  1254. Py_UCS4 *ucs4_out;
  1255. assert(unicode != NULL);
  1256. assert(_PyUnicode_CHECK(unicode));
  1257. assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
  1258. ucs4_out = PyUnicode_4BYTE_DATA(unicode);
  1259. for (iter = begin; iter < end; ) {
  1260. assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
  1261. _PyUnicode_GET_LENGTH(unicode)));
  1262. if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
  1263. && (iter+1) < end
  1264. && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
  1265. {
  1266. *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
  1267. iter += 2;
  1268. }
  1269. else {
  1270. *ucs4_out++ = *iter;
  1271. iter++;
  1272. }
  1273. }
  1274. assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
  1275. _PyUnicode_GET_LENGTH(unicode)));
  1276. }
  1277. #endif
  1278. static int
  1279. unicode_check_modifiable(PyObject *unicode)
  1280. {
  1281. if (!unicode_modifiable(unicode)) {
  1282. PyErr_SetString(PyExc_SystemError,
  1283. "Cannot modify a string currently used");
  1284. return -1;
  1285. }
  1286. return 0;
  1287. }
  1288. static int
  1289. _copy_characters(PyObject *to, Py_ssize_t to_start,
  1290. PyObject *from, Py_ssize_t from_start,
  1291. Py_ssize_t how_many, int check_maxchar)
  1292. {
  1293. int from_kind, to_kind;
  1294. const void *from_data;
  1295. void *to_data;
  1296. assert(0 <= how_many);
  1297. assert(0 <= from_start);
  1298. assert(0 <= to_start);
  1299. assert(PyUnicode_Check(from));
  1300. assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
  1301. if (how_many == 0)
  1302. return 0;
  1303. assert(PyUnicode_Check(to));
  1304. assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
  1305. from_kind = PyUnicode_KIND(from);
  1306. from_data = PyUnicode_DATA(from);
  1307. to_kind = PyUnicode_KIND(to);
  1308. to_data = PyUnicode_DATA(to);
  1309. #ifdef Py_DEBUG
  1310. if (!check_maxchar
  1311. && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
  1312. {
  1313. Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
  1314. Py_UCS4 ch;
  1315. Py_ssize_t i;
  1316. for (i=0; i < how_many; i++) {
  1317. ch = PyUnicode_READ(from_kind, from_data, from_start + i);
  1318. assert(ch <= to_maxchar);
  1319. }
  1320. }
  1321. #endif
  1322. if (from_kind == to_kind) {
  1323. if (check_maxchar
  1324. && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
  1325. {
  1326. /* Writing Latin-1 characters into an ASCII string requires to
  1327. check that all written characters are pure ASCII */
  1328. Py_UCS4 max_char;
  1329. max_char = ucs1lib_find_max_char(from_data,
  1330. (const Py_UCS1*)from_data + how_many);
  1331. if (max_char >= 128)
  1332. return -1;
  1333. }
  1334. memcpy((char*)to_data + to_kind * to_start,
  1335. (const char*)from_data + from_kind * from_start,
  1336. to_kind * how_many);
  1337. }
  1338. else if (from_kind == PyUnicode_1BYTE_KIND
  1339. && to_kind == PyUnicode_2BYTE_KIND)
  1340. {
  1341. _PyUnicode_CONVERT_BYTES(
  1342. Py_UCS1, Py_UCS2,
  1343. PyUnicode_1BYTE_DATA(from) + from_start,
  1344. PyUnicode_1BYTE_DATA(from) + from_start + how_many,
  1345. PyUnicode_2BYTE_DATA(to) + to_start
  1346. );
  1347. }
  1348. else if (from_kind == PyUnicode_1BYTE_KIND
  1349. && to_kind == PyUnicode_4BYTE_KIND)
  1350. {
  1351. _PyUnicode_CONVERT_BYTES(
  1352. Py_UCS1, Py_UCS4,
  1353. PyUnicode_1BYTE_DATA(from) + from_start,
  1354. PyUnicode_1BYTE_DATA(from) + from_start + how_many,
  1355. PyUnicode_4BYTE_DATA(to) + to_start
  1356. );
  1357. }
  1358. else if (from_kind == PyUnicode_2BYTE_KIND
  1359. && to_kind == PyUnicode_4BYTE_KIND)
  1360. {
  1361. _PyUnicode_CONVERT_BYTES(
  1362. Py_UCS2, Py_UCS4,
  1363. PyUnicode_2BYTE_DATA(from) + from_start,
  1364. PyUnicode_2BYTE_DATA(from) + from_start + how_many,
  1365. PyUnicode_4BYTE_DATA(to) + to_start
  1366. );
  1367. }
  1368. else {
  1369. assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
  1370. if (!check_maxchar) {
  1371. if (from_kind == PyUnicode_2BYTE_KIND
  1372. && to_kind == PyUnicode_1BYTE_KIND)
  1373. {
  1374. _PyUnicode_CONVERT_BYTES(
  1375. Py_UCS2, Py_UCS1,
  1376. PyUnicode_2BYTE_DATA(from) + from_start,
  1377. PyUnicode_2BYTE_DATA(from) + from_start + how_many,
  1378. PyUnicode_1BYTE_DATA(to) + to_start
  1379. );
  1380. }
  1381. else if (from_kind == PyUnicode_4BYTE_KIND
  1382. && to_kind == PyUnicode_1BYTE_KIND)
  1383. {
  1384. _PyUnicode_CONVERT_BYTES(
  1385. Py_UCS4, Py_UCS1,
  1386. PyUnicode_4BYTE_DATA(from) + from_start,
  1387. PyUnicode_4BYTE_DATA(from) + from_start + how_many,
  1388. PyUnicode_1BYTE_DATA(to) + to_start
  1389. );
  1390. }
  1391. else if (from_kind == PyUnicode_4BYTE_KIND
  1392. && to_kind == PyUnicode_2BYTE_KIND)
  1393. {
  1394. _PyUnicode_CONVERT_BYTES(
  1395. Py_UCS4, Py_UCS2,
  1396. PyUnicode_4BYTE_DATA(from) + from_start,
  1397. PyUnicode_4BYTE_DATA(from) + from_start + how_many,
  1398. PyUnicode_2BYTE_DATA(to) + to_start
  1399. );
  1400. }
  1401. else {
  1402. Py_UNREACHABLE();
  1403. }
  1404. }
  1405. else {
  1406. const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
  1407. Py_UCS4 ch;
  1408. Py_ssize_t i;
  1409. for (i=0; i < how_many; i++) {
  1410. ch = PyUnicode_READ(from_kind, from_data, from_start + i);
  1411. if (ch > to_maxchar)
  1412. return -1;
  1413. PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
  1414. }
  1415. }
  1416. }
  1417. return 0;
  1418. }
  1419. void
  1420. _PyUnicode_FastCopyCharacters(
  1421. PyObject *to, Py_ssize_t to_start,
  1422. PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
  1423. {
  1424. (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
  1425. }
  1426. Py_ssize_t
  1427. PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
  1428. PyObject *from, Py_ssize_t from_start,
  1429. Py_ssize_t how_many)
  1430. {
  1431. int err;
  1432. if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
  1433. PyErr_BadInternalCall();
  1434. return -1;
  1435. }
  1436. if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
  1437. PyErr_SetString(PyExc_IndexError, "string index out of range");
  1438. return -1;
  1439. }
  1440. if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
  1441. PyErr_SetString(PyExc_IndexError, "string index out of range");
  1442. return -1;
  1443. }
  1444. if (how_many < 0) {
  1445. PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
  1446. return -1;
  1447. }
  1448. how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
  1449. if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
  1450. PyErr_Format(PyExc_SystemError,
  1451. "Cannot write %zi characters at %zi "
  1452. "in a string of %zi characters",
  1453. how_many, to_start, PyUnicode_GET_LENGTH(to));
  1454. return -1;
  1455. }
  1456. if (how_many == 0)
  1457. return 0;
  1458. if (unicode_check_modifiable(to))
  1459. return -1;
  1460. err = _copy_characters(to, to_start, from, from_start, how_many, 1);
  1461. if (err) {
  1462. PyErr_Format(PyExc_SystemError,
  1463. "Cannot copy %s characters "
  1464. "into a string of %s characters",
  1465. unicode_kind_name(from),
  1466. unicode_kind_name(to));
  1467. return -1;
  1468. }
  1469. return how_many;
  1470. }
  1471. /* Find the maximum code point and count the number of surrogate pairs so a
  1472. correct string length can be computed before converting a string to UCS4.
  1473. This function counts single surrogates as a character and not as a pair.
  1474. Return 0 on success, or -1 on error. */
  1475. static int
  1476. find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
  1477. Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
  1478. {
  1479. const wchar_t *iter;
  1480. Py_UCS4 ch;
  1481. assert(num_surrogates != NULL && maxchar != NULL);
  1482. *num_surrogates = 0;
  1483. *maxchar = 0;
  1484. for (iter = begin; iter < end; ) {
  1485. #if SIZEOF_WCHAR_T == 2
  1486. if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
  1487. && (iter+1) < end
  1488. && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
  1489. {
  1490. ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
  1491. ++(*num_surrogates);
  1492. iter += 2;
  1493. }
  1494. else
  1495. #endif
  1496. {
  1497. ch = *iter;
  1498. iter++;
  1499. }
  1500. if (ch > *maxchar) {
  1501. *maxchar = ch;
  1502. if (*maxchar > MAX_UNICODE) {
  1503. PyErr_Format(PyExc_ValueError,
  1504. "character U+%x is not in range [U+0000; U+%x]",
  1505. ch, MAX_UNICODE);
  1506. return -1;
  1507. }
  1508. }
  1509. }
  1510. return 0;
  1511. }
  1512. static void
  1513. unicode_dealloc(PyObject *unicode)
  1514. {
  1515. #ifdef Py_DEBUG
  1516. if (!unicode_is_finalizing() && unicode_is_singleton(unicode)) {
  1517. _Py_FatalRefcountError("deallocating an Unicode singleton");
  1518. }
  1519. #endif
  1520. if (_PyUnicode_STATE(unicode).statically_allocated) {
  1521. /* This should never get called, but we also don't want to SEGV if
  1522. * we accidentally decref an immortal string out of existence. Since
  1523. * the string is an immortal object, just re-set the reference count.
  1524. */
  1525. #ifdef Py_DEBUG
  1526. Py_UNREACHABLE();
  1527. #endif
  1528. _Py_SetImmortal(unicode);
  1529. return;
  1530. }
  1531. switch (_PyUnicode_STATE(unicode).interned) {
  1532. case SSTATE_NOT_INTERNED:
  1533. break;
  1534. case SSTATE_INTERNED_MORTAL:
  1535. /* Remove the object from the intern dict.
  1536. * Before doing so, we set the refcount to 3: the key and value
  1537. * in the interned_dict, plus one to work with.
  1538. */
  1539. assert(Py_REFCNT(unicode) == 0);
  1540. Py_SET_REFCNT(unicode, 3);
  1541. #ifdef Py_REF_DEBUG
  1542. /* let's be pedantic with the ref total */
  1543. _Py_IncRefTotal(_PyInterpreterState_GET());
  1544. _Py_IncRefTotal(_PyInterpreterState_GET());
  1545. _Py_IncRefTotal(_PyInterpreterState_GET());
  1546. #endif
  1547. PyInterpreterState *interp = _PyInterpreterState_GET();
  1548. PyObject *interned = get_interned_dict(interp);
  1549. assert(interned != NULL);
  1550. int r = PyDict_DelItem(interned, unicode);
  1551. if (r == -1) {
  1552. PyErr_WriteUnraisable(unicode);
  1553. // We don't know what happened to the string. It's probably
  1554. // best to leak it:
  1555. // - if it was not found, something is very wrong
  1556. // - if it was deleted, there are no more references to it
  1557. // so it can't cause trouble (except wasted memory)
  1558. // - if it wasn't deleted, it'll remain interned
  1559. _Py_SetImmortal(unicode);
  1560. _PyUnicode_STATE(unicode).interned = SSTATE_INTERNED_IMMORTAL;
  1561. return;
  1562. }
  1563. // Only our work reference should be left; remove it too.
  1564. assert(Py_REFCNT(unicode) == 1);
  1565. Py_SET_REFCNT(unicode, 0);
  1566. #ifdef Py_REF_DEBUG
  1567. /* let's be pedantic with the ref total */
  1568. _Py_DecRefTotal(_PyInterpreterState_GET());
  1569. #endif
  1570. break;
  1571. default:
  1572. // As with `statically_allocated` above.
  1573. #ifdef Py_REF_DEBUG
  1574. Py_UNREACHABLE();
  1575. #endif
  1576. _Py_SetImmortal(unicode);
  1577. return;
  1578. }
  1579. if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
  1580. PyObject_Free(_PyUnicode_UTF8(unicode));
  1581. }
  1582. if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode)) {
  1583. PyObject_Free(_PyUnicode_DATA_ANY(unicode));
  1584. }
  1585. Py_TYPE(unicode)->tp_free(unicode);
  1586. }
  1587. #ifdef Py_DEBUG
  1588. static int
  1589. unicode_is_singleton(PyObject *unicode)
  1590. {
  1591. if (unicode == &_Py_STR(empty)) {
  1592. return 1;
  1593. }
  1594. PyASCIIObject *ascii = _PyASCIIObject_CAST(unicode);
  1595. if (ascii->length == 1) {
  1596. Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
  1597. if (ch < 256 && LATIN1(ch) == unicode) {
  1598. return 1;
  1599. }
  1600. }
  1601. return 0;
  1602. }
  1603. #endif
  1604. static int
  1605. unicode_modifiable(PyObject *unicode)
  1606. {
  1607. assert(_PyUnicode_CHECK(unicode));
  1608. if (Py_REFCNT(unicode) != 1)
  1609. return 0;
  1610. if (_PyUnicode_HASH(unicode) != -1)
  1611. return 0;
  1612. if (PyUnicode_CHECK_INTERNED(unicode))
  1613. return 0;
  1614. if (!PyUnicode_CheckExact(unicode))
  1615. return 0;
  1616. #ifdef Py_DEBUG
  1617. /* singleton refcount is greater than 1 */
  1618. assert(!unicode_is_singleton(unicode));
  1619. #endif
  1620. return 1;
  1621. }
  1622. static int
  1623. unicode_resize(PyObject **p_unicode, Py_ssize_t length)
  1624. {
  1625. PyObject *unicode;
  1626. Py_ssize_t old_length;
  1627. assert(p_unicode != NULL);
  1628. unicode = *p_unicode;
  1629. assert(unicode != NULL);
  1630. assert(PyUnicode_Check(unicode));
  1631. assert(0 <= length);
  1632. old_length = PyUnicode_GET_LENGTH(unicode);
  1633. if (old_length == length)
  1634. return 0;
  1635. if (length == 0) {
  1636. PyObject *empty = unicode_new_empty();
  1637. Py_SETREF(*p_unicode, empty);
  1638. return 0;
  1639. }
  1640. if (!unicode_modifiable(unicode)) {
  1641. PyObject *copy = resize_copy(unicode, length);
  1642. if (copy == NULL)
  1643. return -1;
  1644. Py_SETREF(*p_unicode, copy);
  1645. return 0;
  1646. }
  1647. if (PyUnicode_IS_COMPACT(unicode)) {
  1648. PyObject *new_unicode = resize_compact(unicode, length);
  1649. if (new_unicode == NULL)
  1650. return -1;
  1651. *p_unicode = new_unicode;
  1652. return 0;
  1653. }
  1654. return resize_inplace(unicode, length);
  1655. }
  1656. int
  1657. PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
  1658. {
  1659. PyObject *unicode;
  1660. if (p_unicode == NULL) {
  1661. PyErr_BadInternalCall();
  1662. return -1;
  1663. }
  1664. unicode = *p_unicode;
  1665. if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
  1666. {
  1667. PyErr_BadInternalCall();
  1668. return -1;
  1669. }
  1670. return unicode_resize(p_unicode, length);
  1671. }
  1672. /* Copy an ASCII or latin1 char* string into a Python Unicode string.
  1673. WARNING: The function doesn't copy the terminating null character and
  1674. doesn't check the maximum character (may write a latin1 character in an
  1675. ASCII string). */
  1676. static void
  1677. unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
  1678. const char *str, Py_ssize_t len)
  1679. {
  1680. int kind = PyUnicode_KIND(unicode);
  1681. const void *data = PyUnicode_DATA(unicode);
  1682. const char *end = str + len;
  1683. assert(index + len <= PyUnicode_GET_LENGTH(unicode));
  1684. switch (kind) {
  1685. case PyUnicode_1BYTE_KIND: {
  1686. #ifdef Py_DEBUG
  1687. if (PyUnicode_IS_ASCII(unicode)) {
  1688. Py_UCS4 maxchar = ucs1lib_find_max_char(
  1689. (const Py_UCS1*)str,
  1690. (const Py_UCS1*)str + len);
  1691. assert(maxchar < 128);
  1692. }
  1693. #endif
  1694. memcpy((char *) data + index, str, len);
  1695. break;
  1696. }
  1697. case PyUnicode_2BYTE_KIND: {
  1698. Py_UCS2 *start = (Py_UCS2 *)data + index;
  1699. Py_UCS2 *ucs2 = start;
  1700. for (; str < end; ++ucs2, ++str)
  1701. *ucs2 = (Py_UCS2)*str;
  1702. assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
  1703. break;
  1704. }
  1705. case PyUnicode_4BYTE_KIND: {
  1706. Py_UCS4 *start = (Py_UCS4 *)data + index;
  1707. Py_UCS4 *ucs4 = start;
  1708. for (; str < end; ++ucs4, ++str)
  1709. *ucs4 = (Py_UCS4)*str;
  1710. assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
  1711. break;
  1712. }
  1713. default:
  1714. Py_UNREACHABLE();
  1715. }
  1716. }
  1717. static PyObject*
  1718. get_latin1_char(Py_UCS1 ch)
  1719. {
  1720. PyObject *o = LATIN1(ch);
  1721. return o;
  1722. }
  1723. static PyObject*
  1724. unicode_char(Py_UCS4 ch)
  1725. {
  1726. PyObject *unicode;
  1727. assert(ch <= MAX_UNICODE);
  1728. if (ch < 256) {
  1729. return get_latin1_char(ch);
  1730. }
  1731. unicode = PyUnicode_New(1, ch);
  1732. if (unicode == NULL)
  1733. return NULL;
  1734. assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
  1735. if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
  1736. PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
  1737. } else {
  1738. assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
  1739. PyUnicode_4BYTE_DATA(unicode)[0] = ch;
  1740. }
  1741. assert(_PyUnicode_CheckConsistency(unicode, 1));
  1742. return unicode;
  1743. }
  1744. PyObject *
  1745. PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
  1746. {
  1747. PyObject *unicode;
  1748. Py_UCS4 maxchar = 0;
  1749. Py_ssize_t num_surrogates;
  1750. if (u == NULL && size != 0) {
  1751. PyErr_BadInternalCall();
  1752. return NULL;
  1753. }
  1754. if (size == -1) {
  1755. size = wcslen(u);
  1756. }
  1757. /* If the Unicode data is known at construction time, we can apply
  1758. some optimizations which share commonly used objects. */
  1759. /* Optimization for empty strings */
  1760. if (size == 0)
  1761. _Py_RETURN_UNICODE_EMPTY();
  1762. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  1763. /* Oracle Solaris uses non-Unicode internal wchar_t form for
  1764. non-Unicode locales and hence needs conversion to UCS-4 first. */
  1765. if (_Py_LocaleUsesNonUnicodeWchar()) {
  1766. wchar_t* converted = _Py_DecodeNonUnicodeWchar(u, size);
  1767. if (!converted) {
  1768. return NULL;
  1769. }
  1770. PyObject *unicode = _PyUnicode_FromUCS4(converted, size);
  1771. PyMem_Free(converted);
  1772. return unicode;
  1773. }
  1774. #endif
  1775. /* Single character Unicode objects in the Latin-1 range are
  1776. shared when using this constructor */
  1777. if (size == 1 && (Py_UCS4)*u < 256)
  1778. return get_latin1_char((unsigned char)*u);
  1779. /* If not empty and not single character, copy the Unicode data
  1780. into the new object */
  1781. if (find_maxchar_surrogates(u, u + size,
  1782. &maxchar, &num_surrogates) == -1)
  1783. return NULL;
  1784. unicode = PyUnicode_New(size - num_surrogates, maxchar);
  1785. if (!unicode)
  1786. return NULL;
  1787. switch (PyUnicode_KIND(unicode)) {
  1788. case PyUnicode_1BYTE_KIND:
  1789. _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
  1790. u, u + size, PyUnicode_1BYTE_DATA(unicode));
  1791. break;
  1792. case PyUnicode_2BYTE_KIND:
  1793. #if Py_UNICODE_SIZE == 2
  1794. memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
  1795. #else
  1796. _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
  1797. u, u + size, PyUnicode_2BYTE_DATA(unicode));
  1798. #endif
  1799. break;
  1800. case PyUnicode_4BYTE_KIND:
  1801. #if SIZEOF_WCHAR_T == 2
  1802. /* This is the only case which has to process surrogates, thus
  1803. a simple copy loop is not enough and we need a function. */
  1804. unicode_convert_wchar_to_ucs4(u, u + size, unicode);
  1805. #else
  1806. assert(num_surrogates == 0);
  1807. memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
  1808. #endif
  1809. break;
  1810. default:
  1811. Py_UNREACHABLE();
  1812. }
  1813. return unicode_result(unicode);
  1814. }
  1815. PyObject *
  1816. PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
  1817. {
  1818. if (size < 0) {
  1819. PyErr_SetString(PyExc_SystemError,
  1820. "Negative size passed to PyUnicode_FromStringAndSize");
  1821. return NULL;
  1822. }
  1823. if (u != NULL) {
  1824. return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
  1825. }
  1826. if (size > 0) {
  1827. PyErr_SetString(PyExc_SystemError,
  1828. "NULL string with positive size with NULL passed to PyUnicode_FromStringAndSize");
  1829. return NULL;
  1830. }
  1831. return unicode_new_empty();
  1832. }
  1833. PyObject *
  1834. PyUnicode_FromString(const char *u)
  1835. {
  1836. #if defined(__has_feature)
  1837. # if __has_feature(memory_sanitizer)
  1838. __msan_unpoison_string(u);
  1839. # endif
  1840. #endif
  1841. size_t size = strlen(u);
  1842. if (size > PY_SSIZE_T_MAX) {
  1843. PyErr_SetString(PyExc_OverflowError, "input too long");
  1844. return NULL;
  1845. }
  1846. return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
  1847. }
  1848. PyObject *
  1849. _PyUnicode_FromId(_Py_Identifier *id)
  1850. {
  1851. PyInterpreterState *interp = _PyInterpreterState_GET();
  1852. struct _Py_unicode_ids *ids = &interp->unicode.ids;
  1853. Py_ssize_t index = _Py_atomic_size_get(&id->index);
  1854. if (index < 0) {
  1855. struct _Py_unicode_runtime_ids *rt_ids = &interp->runtime->unicode_state.ids;
  1856. PyThread_acquire_lock(rt_ids->lock, WAIT_LOCK);
  1857. // Check again to detect concurrent access. Another thread can have
  1858. // initialized the index while this thread waited for the lock.
  1859. index = _Py_atomic_size_get(&id->index);
  1860. if (index < 0) {
  1861. assert(rt_ids->next_index < PY_SSIZE_T_MAX);
  1862. index = rt_ids->next_index;
  1863. rt_ids->next_index++;
  1864. _Py_atomic_size_set(&id->index, index);
  1865. }
  1866. PyThread_release_lock(rt_ids->lock);
  1867. }
  1868. assert(index >= 0);
  1869. PyObject *obj;
  1870. if (index < ids->size) {
  1871. obj = ids->array[index];
  1872. if (obj) {
  1873. // Return a borrowed reference
  1874. return obj;
  1875. }
  1876. }
  1877. obj = PyUnicode_DecodeUTF8Stateful(id->string, strlen(id->string),
  1878. NULL, NULL);
  1879. if (!obj) {
  1880. return NULL;
  1881. }
  1882. _PyUnicode_InternImmortal(interp, &obj);
  1883. if (index >= ids->size) {
  1884. // Overallocate to reduce the number of realloc
  1885. Py_ssize_t new_size = Py_MAX(index * 2, 16);
  1886. Py_ssize_t item_size = sizeof(ids->array[0]);
  1887. PyObject **new_array = PyMem_Realloc(ids->array, new_size * item_size);
  1888. if (new_array == NULL) {
  1889. PyErr_NoMemory();
  1890. return NULL;
  1891. }
  1892. memset(&new_array[ids->size], 0, (new_size - ids->size) * item_size);
  1893. ids->array = new_array;
  1894. ids->size = new_size;
  1895. }
  1896. // The array stores a strong reference
  1897. ids->array[index] = obj;
  1898. // Return a borrowed reference
  1899. return obj;
  1900. }
  1901. static void
  1902. unicode_clear_identifiers(struct _Py_unicode_state *state)
  1903. {
  1904. struct _Py_unicode_ids *ids = &state->ids;
  1905. for (Py_ssize_t i=0; i < ids->size; i++) {
  1906. Py_XDECREF(ids->array[i]);
  1907. }
  1908. ids->size = 0;
  1909. PyMem_Free(ids->array);
  1910. ids->array = NULL;
  1911. // Don't reset _PyRuntime next_index: _Py_Identifier.id remains valid
  1912. // after Py_Finalize().
  1913. }
  1914. /* Internal function, doesn't check maximum character */
  1915. PyObject*
  1916. _PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
  1917. {
  1918. const unsigned char *s = (const unsigned char *)buffer;
  1919. PyObject *unicode;
  1920. if (size == 1) {
  1921. #ifdef Py_DEBUG
  1922. assert((unsigned char)s[0] < 128);
  1923. #endif
  1924. return get_latin1_char(s[0]);
  1925. }
  1926. unicode = PyUnicode_New(size, 127);
  1927. if (!unicode)
  1928. return NULL;
  1929. memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
  1930. assert(_PyUnicode_CheckConsistency(unicode, 1));
  1931. return unicode;
  1932. }
  1933. static Py_UCS4
  1934. kind_maxchar_limit(int kind)
  1935. {
  1936. switch (kind) {
  1937. case PyUnicode_1BYTE_KIND:
  1938. return 0x80;
  1939. case PyUnicode_2BYTE_KIND:
  1940. return 0x100;
  1941. case PyUnicode_4BYTE_KIND:
  1942. return 0x10000;
  1943. default:
  1944. Py_UNREACHABLE();
  1945. }
  1946. }
  1947. static PyObject*
  1948. _PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
  1949. {
  1950. PyObject *res;
  1951. unsigned char max_char;
  1952. if (size == 0) {
  1953. _Py_RETURN_UNICODE_EMPTY();
  1954. }
  1955. assert(size > 0);
  1956. if (size == 1) {
  1957. return get_latin1_char(u[0]);
  1958. }
  1959. max_char = ucs1lib_find_max_char(u, u + size);
  1960. res = PyUnicode_New(size, max_char);
  1961. if (!res)
  1962. return NULL;
  1963. memcpy(PyUnicode_1BYTE_DATA(res), u, size);
  1964. assert(_PyUnicode_CheckConsistency(res, 1));
  1965. return res;
  1966. }
  1967. static PyObject*
  1968. _PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
  1969. {
  1970. PyObject *res;
  1971. Py_UCS2 max_char;
  1972. if (size == 0)
  1973. _Py_RETURN_UNICODE_EMPTY();
  1974. assert(size > 0);
  1975. if (size == 1)
  1976. return unicode_char(u[0]);
  1977. max_char = ucs2lib_find_max_char(u, u + size);
  1978. res = PyUnicode_New(size, max_char);
  1979. if (!res)
  1980. return NULL;
  1981. if (max_char >= 256)
  1982. memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
  1983. else {
  1984. _PyUnicode_CONVERT_BYTES(
  1985. Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
  1986. }
  1987. assert(_PyUnicode_CheckConsistency(res, 1));
  1988. return res;
  1989. }
  1990. static PyObject*
  1991. _PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
  1992. {
  1993. PyObject *res;
  1994. Py_UCS4 max_char;
  1995. if (size == 0)
  1996. _Py_RETURN_UNICODE_EMPTY();
  1997. assert(size > 0);
  1998. if (size == 1)
  1999. return unicode_char(u[0]);
  2000. max_char = ucs4lib_find_max_char(u, u + size);
  2001. res = PyUnicode_New(size, max_char);
  2002. if (!res)
  2003. return NULL;
  2004. if (max_char < 256)
  2005. _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
  2006. PyUnicode_1BYTE_DATA(res));
  2007. else if (max_char < 0x10000)
  2008. _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
  2009. PyUnicode_2BYTE_DATA(res));
  2010. else
  2011. memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
  2012. assert(_PyUnicode_CheckConsistency(res, 1));
  2013. return res;
  2014. }
  2015. PyObject*
  2016. PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
  2017. {
  2018. if (size < 0) {
  2019. PyErr_SetString(PyExc_ValueError, "size must be positive");
  2020. return NULL;
  2021. }
  2022. switch (kind) {
  2023. case PyUnicode_1BYTE_KIND:
  2024. return _PyUnicode_FromUCS1(buffer, size);
  2025. case PyUnicode_2BYTE_KIND:
  2026. return _PyUnicode_FromUCS2(buffer, size);
  2027. case PyUnicode_4BYTE_KIND:
  2028. return _PyUnicode_FromUCS4(buffer, size);
  2029. default:
  2030. PyErr_SetString(PyExc_SystemError, "invalid kind");
  2031. return NULL;
  2032. }
  2033. }
  2034. Py_UCS4
  2035. _PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
  2036. {
  2037. int kind;
  2038. const void *startptr, *endptr;
  2039. assert(0 <= start);
  2040. assert(end <= PyUnicode_GET_LENGTH(unicode));
  2041. assert(start <= end);
  2042. if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
  2043. return PyUnicode_MAX_CHAR_VALUE(unicode);
  2044. if (start == end)
  2045. return 127;
  2046. if (PyUnicode_IS_ASCII(unicode))
  2047. return 127;
  2048. kind = PyUnicode_KIND(unicode);
  2049. startptr = PyUnicode_DATA(unicode);
  2050. endptr = (char *)startptr + end * kind;
  2051. startptr = (char *)startptr + start * kind;
  2052. switch(kind) {
  2053. case PyUnicode_1BYTE_KIND:
  2054. return ucs1lib_find_max_char(startptr, endptr);
  2055. case PyUnicode_2BYTE_KIND:
  2056. return ucs2lib_find_max_char(startptr, endptr);
  2057. case PyUnicode_4BYTE_KIND:
  2058. return ucs4lib_find_max_char(startptr, endptr);
  2059. default:
  2060. Py_UNREACHABLE();
  2061. }
  2062. }
  2063. /* Ensure that a string uses the most efficient storage, if it is not the
  2064. case: create a new string with of the right kind. Write NULL into *p_unicode
  2065. on error. */
  2066. static void
  2067. unicode_adjust_maxchar(PyObject **p_unicode)
  2068. {
  2069. PyObject *unicode, *copy;
  2070. Py_UCS4 max_char;
  2071. Py_ssize_t len;
  2072. int kind;
  2073. assert(p_unicode != NULL);
  2074. unicode = *p_unicode;
  2075. if (PyUnicode_IS_ASCII(unicode))
  2076. return;
  2077. len = PyUnicode_GET_LENGTH(unicode);
  2078. kind = PyUnicode_KIND(unicode);
  2079. if (kind == PyUnicode_1BYTE_KIND) {
  2080. const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
  2081. max_char = ucs1lib_find_max_char(u, u + len);
  2082. if (max_char >= 128)
  2083. return;
  2084. }
  2085. else if (kind == PyUnicode_2BYTE_KIND) {
  2086. const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
  2087. max_char = ucs2lib_find_max_char(u, u + len);
  2088. if (max_char >= 256)
  2089. return;
  2090. }
  2091. else if (kind == PyUnicode_4BYTE_KIND) {
  2092. const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
  2093. max_char = ucs4lib_find_max_char(u, u + len);
  2094. if (max_char >= 0x10000)
  2095. return;
  2096. }
  2097. else
  2098. Py_UNREACHABLE();
  2099. copy = PyUnicode_New(len, max_char);
  2100. if (copy != NULL)
  2101. _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
  2102. Py_DECREF(unicode);
  2103. *p_unicode = copy;
  2104. }
  2105. PyObject*
  2106. _PyUnicode_Copy(PyObject *unicode)
  2107. {
  2108. Py_ssize_t length;
  2109. PyObject *copy;
  2110. if (!PyUnicode_Check(unicode)) {
  2111. PyErr_BadInternalCall();
  2112. return NULL;
  2113. }
  2114. length = PyUnicode_GET_LENGTH(unicode);
  2115. copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
  2116. if (!copy)
  2117. return NULL;
  2118. assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
  2119. memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
  2120. length * PyUnicode_KIND(unicode));
  2121. assert(_PyUnicode_CheckConsistency(copy, 1));
  2122. return copy;
  2123. }
  2124. /* Widen Unicode objects to larger buffers. Don't write terminating null
  2125. character. Return NULL on error. */
  2126. static void*
  2127. unicode_askind(int skind, void const *data, Py_ssize_t len, int kind)
  2128. {
  2129. void *result;
  2130. assert(skind < kind);
  2131. switch (kind) {
  2132. case PyUnicode_2BYTE_KIND:
  2133. result = PyMem_New(Py_UCS2, len);
  2134. if (!result)
  2135. return PyErr_NoMemory();
  2136. assert(skind == PyUnicode_1BYTE_KIND);
  2137. _PyUnicode_CONVERT_BYTES(
  2138. Py_UCS1, Py_UCS2,
  2139. (const Py_UCS1 *)data,
  2140. ((const Py_UCS1 *)data) + len,
  2141. result);
  2142. return result;
  2143. case PyUnicode_4BYTE_KIND:
  2144. result = PyMem_New(Py_UCS4, len);
  2145. if (!result)
  2146. return PyErr_NoMemory();
  2147. if (skind == PyUnicode_2BYTE_KIND) {
  2148. _PyUnicode_CONVERT_BYTES(
  2149. Py_UCS2, Py_UCS4,
  2150. (const Py_UCS2 *)data,
  2151. ((const Py_UCS2 *)data) + len,
  2152. result);
  2153. }
  2154. else {
  2155. assert(skind == PyUnicode_1BYTE_KIND);
  2156. _PyUnicode_CONVERT_BYTES(
  2157. Py_UCS1, Py_UCS4,
  2158. (const Py_UCS1 *)data,
  2159. ((const Py_UCS1 *)data) + len,
  2160. result);
  2161. }
  2162. return result;
  2163. default:
  2164. Py_UNREACHABLE();
  2165. return NULL;
  2166. }
  2167. }
  2168. static Py_UCS4*
  2169. as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
  2170. int copy_null)
  2171. {
  2172. int kind;
  2173. const void *data;
  2174. Py_ssize_t len, targetlen;
  2175. kind = PyUnicode_KIND(string);
  2176. data = PyUnicode_DATA(string);
  2177. len = PyUnicode_GET_LENGTH(string);
  2178. targetlen = len;
  2179. if (copy_null)
  2180. targetlen++;
  2181. if (!target) {
  2182. target = PyMem_New(Py_UCS4, targetlen);
  2183. if (!target) {
  2184. PyErr_NoMemory();
  2185. return NULL;
  2186. }
  2187. }
  2188. else {
  2189. if (targetsize < targetlen) {
  2190. PyErr_Format(PyExc_SystemError,
  2191. "string is longer than the buffer");
  2192. if (copy_null && 0 < targetsize)
  2193. target[0] = 0;
  2194. return NULL;
  2195. }
  2196. }
  2197. if (kind == PyUnicode_1BYTE_KIND) {
  2198. const Py_UCS1 *start = (const Py_UCS1 *) data;
  2199. _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
  2200. }
  2201. else if (kind == PyUnicode_2BYTE_KIND) {
  2202. const Py_UCS2 *start = (const Py_UCS2 *) data;
  2203. _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
  2204. }
  2205. else if (kind == PyUnicode_4BYTE_KIND) {
  2206. memcpy(target, data, len * sizeof(Py_UCS4));
  2207. }
  2208. else {
  2209. Py_UNREACHABLE();
  2210. }
  2211. if (copy_null)
  2212. target[len] = 0;
  2213. return target;
  2214. }
  2215. Py_UCS4*
  2216. PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
  2217. int copy_null)
  2218. {
  2219. if (target == NULL || targetsize < 0) {
  2220. PyErr_BadInternalCall();
  2221. return NULL;
  2222. }
  2223. return as_ucs4(string, target, targetsize, copy_null);
  2224. }
  2225. Py_UCS4*
  2226. PyUnicode_AsUCS4Copy(PyObject *string)
  2227. {
  2228. return as_ucs4(string, NULL, 0, 1);
  2229. }
  2230. /* maximum number of characters required for output of %jo or %jd or %p.
  2231. We need at most ceil(log8(256)*sizeof(intmax_t)) digits,
  2232. plus 1 for the sign, plus 2 for the 0x prefix (for %p),
  2233. plus 1 for the terminal NUL. */
  2234. #define MAX_INTMAX_CHARS (5 + (sizeof(intmax_t)*8-1) / 3)
  2235. static int
  2236. unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
  2237. Py_ssize_t width, Py_ssize_t precision, int flags)
  2238. {
  2239. Py_ssize_t length, fill, arglen;
  2240. Py_UCS4 maxchar;
  2241. length = PyUnicode_GET_LENGTH(str);
  2242. if ((precision == -1 || precision >= length)
  2243. && width <= length)
  2244. return _PyUnicodeWriter_WriteStr(writer, str);
  2245. if (precision != -1)
  2246. length = Py_MIN(precision, length);
  2247. arglen = Py_MAX(length, width);
  2248. if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
  2249. maxchar = _PyUnicode_FindMaxChar(str, 0, length);
  2250. else
  2251. maxchar = writer->maxchar;
  2252. if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
  2253. return -1;
  2254. fill = Py_MAX(width - length, 0);
  2255. if (fill && !(flags & F_LJUST)) {
  2256. if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
  2257. return -1;
  2258. writer->pos += fill;
  2259. }
  2260. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  2261. str, 0, length);
  2262. writer->pos += length;
  2263. if (fill && (flags & F_LJUST)) {
  2264. if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
  2265. return -1;
  2266. writer->pos += fill;
  2267. }
  2268. return 0;
  2269. }
  2270. static int
  2271. unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
  2272. Py_ssize_t width, Py_ssize_t precision, int flags)
  2273. {
  2274. /* UTF-8 */
  2275. Py_ssize_t length;
  2276. PyObject *unicode;
  2277. int res;
  2278. if (precision == -1) {
  2279. length = strlen(str);
  2280. }
  2281. else {
  2282. length = 0;
  2283. while (length < precision && str[length]) {
  2284. length++;
  2285. }
  2286. }
  2287. unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
  2288. if (unicode == NULL)
  2289. return -1;
  2290. res = unicode_fromformat_write_str(writer, unicode, width, -1, flags);
  2291. Py_DECREF(unicode);
  2292. return res;
  2293. }
  2294. static int
  2295. unicode_fromformat_write_wcstr(_PyUnicodeWriter *writer, const wchar_t *str,
  2296. Py_ssize_t width, Py_ssize_t precision, int flags)
  2297. {
  2298. /* UTF-8 */
  2299. Py_ssize_t length;
  2300. PyObject *unicode;
  2301. int res;
  2302. if (precision == -1) {
  2303. length = wcslen(str);
  2304. }
  2305. else {
  2306. length = 0;
  2307. while (length < precision && str[length]) {
  2308. length++;
  2309. }
  2310. }
  2311. unicode = PyUnicode_FromWideChar(str, length);
  2312. if (unicode == NULL)
  2313. return -1;
  2314. res = unicode_fromformat_write_str(writer, unicode, width, -1, flags);
  2315. Py_DECREF(unicode);
  2316. return res;
  2317. }
  2318. #define F_LONG 1
  2319. #define F_LONGLONG 2
  2320. #define F_SIZE 3
  2321. #define F_PTRDIFF 4
  2322. #define F_INTMAX 5
  2323. static const char * const formats[] = {"%d", "%ld", "%lld", "%zd", "%td", "%jd"};
  2324. static const char * const formats_o[] = {"%o", "%lo", "%llo", "%zo", "%to", "%jo"};
  2325. static const char * const formats_u[] = {"%u", "%lu", "%llu", "%zu", "%tu", "%ju"};
  2326. static const char * const formats_x[] = {"%x", "%lx", "%llx", "%zx", "%tx", "%jx"};
  2327. static const char * const formats_X[] = {"%X", "%lX", "%llX", "%zX", "%tX", "%jX"};
  2328. static const char*
  2329. unicode_fromformat_arg(_PyUnicodeWriter *writer,
  2330. const char *f, va_list *vargs)
  2331. {
  2332. const char *p;
  2333. Py_ssize_t len;
  2334. int flags = 0;
  2335. Py_ssize_t width;
  2336. Py_ssize_t precision;
  2337. p = f;
  2338. f++;
  2339. if (*f == '%') {
  2340. if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
  2341. return NULL;
  2342. f++;
  2343. return f;
  2344. }
  2345. /* Parse flags. Example: "%-i" => flags=F_LJUST. */
  2346. /* Flags '+', ' ' and '#' are not particularly useful.
  2347. * They are not worth the implementation and maintenance costs.
  2348. * In addition, '#' should add "0" for "o" conversions for compatibility
  2349. * with printf, but it would confuse Python users. */
  2350. while (1) {
  2351. switch (*f++) {
  2352. case '-': flags |= F_LJUST; continue;
  2353. case '0': flags |= F_ZERO; continue;
  2354. }
  2355. f--;
  2356. break;
  2357. }
  2358. /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
  2359. width = -1;
  2360. if (*f == '*') {
  2361. width = va_arg(*vargs, int);
  2362. if (width < 0) {
  2363. flags |= F_LJUST;
  2364. width = -width;
  2365. }
  2366. f++;
  2367. }
  2368. else if (Py_ISDIGIT((unsigned)*f)) {
  2369. width = *f - '0';
  2370. f++;
  2371. while (Py_ISDIGIT((unsigned)*f)) {
  2372. if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
  2373. PyErr_SetString(PyExc_ValueError,
  2374. "width too big");
  2375. return NULL;
  2376. }
  2377. width = (width * 10) + (*f - '0');
  2378. f++;
  2379. }
  2380. }
  2381. precision = -1;
  2382. if (*f == '.') {
  2383. f++;
  2384. if (*f == '*') {
  2385. precision = va_arg(*vargs, int);
  2386. if (precision < 0) {
  2387. precision = -2;
  2388. }
  2389. f++;
  2390. }
  2391. else if (Py_ISDIGIT((unsigned)*f)) {
  2392. precision = (*f - '0');
  2393. f++;
  2394. while (Py_ISDIGIT((unsigned)*f)) {
  2395. if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
  2396. PyErr_SetString(PyExc_ValueError,
  2397. "precision too big");
  2398. return NULL;
  2399. }
  2400. precision = (precision * 10) + (*f - '0');
  2401. f++;
  2402. }
  2403. }
  2404. }
  2405. int sizemod = 0;
  2406. if (*f == 'l') {
  2407. if (f[1] == 'l') {
  2408. sizemod = F_LONGLONG;
  2409. f += 2;
  2410. }
  2411. else {
  2412. sizemod = F_LONG;
  2413. ++f;
  2414. }
  2415. }
  2416. else if (*f == 'z') {
  2417. sizemod = F_SIZE;
  2418. ++f;
  2419. }
  2420. else if (*f == 't') {
  2421. sizemod = F_PTRDIFF;
  2422. ++f;
  2423. }
  2424. else if (*f == 'j') {
  2425. sizemod = F_INTMAX;
  2426. ++f;
  2427. }
  2428. if (f[0] != '\0' && f[1] == '\0')
  2429. writer->overallocate = 0;
  2430. switch (*f) {
  2431. case 'd': case 'i': case 'o': case 'u': case 'x': case 'X':
  2432. break;
  2433. case 'c': case 'p':
  2434. if (sizemod || width >= 0 || precision >= 0) goto invalid_format;
  2435. break;
  2436. case 's':
  2437. case 'V':
  2438. if (sizemod && sizemod != F_LONG) goto invalid_format;
  2439. break;
  2440. default:
  2441. if (sizemod) goto invalid_format;
  2442. break;
  2443. }
  2444. switch (*f) {
  2445. case 'c':
  2446. {
  2447. int ordinal = va_arg(*vargs, int);
  2448. if (ordinal < 0 || ordinal > MAX_UNICODE) {
  2449. PyErr_SetString(PyExc_OverflowError,
  2450. "character argument not in range(0x110000)");
  2451. return NULL;
  2452. }
  2453. if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
  2454. return NULL;
  2455. break;
  2456. }
  2457. case 'd': case 'i':
  2458. case 'o': case 'u': case 'x': case 'X':
  2459. {
  2460. /* used by sprintf */
  2461. char buffer[MAX_INTMAX_CHARS];
  2462. const char *fmt = NULL;
  2463. switch (*f) {
  2464. case 'o': fmt = formats_o[sizemod]; break;
  2465. case 'u': fmt = formats_u[sizemod]; break;
  2466. case 'x': fmt = formats_x[sizemod]; break;
  2467. case 'X': fmt = formats_X[sizemod]; break;
  2468. default: fmt = formats[sizemod]; break;
  2469. }
  2470. int issigned = (*f == 'd' || *f == 'i');
  2471. switch (sizemod) {
  2472. case F_LONG:
  2473. len = issigned ?
  2474. sprintf(buffer, fmt, va_arg(*vargs, long)) :
  2475. sprintf(buffer, fmt, va_arg(*vargs, unsigned long));
  2476. break;
  2477. case F_LONGLONG:
  2478. len = issigned ?
  2479. sprintf(buffer, fmt, va_arg(*vargs, long long)) :
  2480. sprintf(buffer, fmt, va_arg(*vargs, unsigned long long));
  2481. break;
  2482. case F_SIZE:
  2483. len = issigned ?
  2484. sprintf(buffer, fmt, va_arg(*vargs, Py_ssize_t)) :
  2485. sprintf(buffer, fmt, va_arg(*vargs, size_t));
  2486. break;
  2487. case F_PTRDIFF:
  2488. len = sprintf(buffer, fmt, va_arg(*vargs, ptrdiff_t));
  2489. break;
  2490. case F_INTMAX:
  2491. len = issigned ?
  2492. sprintf(buffer, fmt, va_arg(*vargs, intmax_t)) :
  2493. sprintf(buffer, fmt, va_arg(*vargs, uintmax_t));
  2494. break;
  2495. default:
  2496. len = issigned ?
  2497. sprintf(buffer, fmt, va_arg(*vargs, int)) :
  2498. sprintf(buffer, fmt, va_arg(*vargs, unsigned int));
  2499. break;
  2500. }
  2501. assert(len >= 0);
  2502. int sign = (buffer[0] == '-');
  2503. len -= sign;
  2504. precision = Py_MAX(precision, len);
  2505. width = Py_MAX(width, precision + sign);
  2506. if ((flags & F_ZERO) && !(flags & F_LJUST)) {
  2507. precision = width - sign;
  2508. }
  2509. Py_ssize_t spacepad = Py_MAX(width - precision - sign, 0);
  2510. Py_ssize_t zeropad = Py_MAX(precision - len, 0);
  2511. if (_PyUnicodeWriter_Prepare(writer, width, 127) == -1)
  2512. return NULL;
  2513. if (spacepad && !(flags & F_LJUST)) {
  2514. if (PyUnicode_Fill(writer->buffer, writer->pos, spacepad, ' ') == -1)
  2515. return NULL;
  2516. writer->pos += spacepad;
  2517. }
  2518. if (sign) {
  2519. if (_PyUnicodeWriter_WriteChar(writer, '-') == -1)
  2520. return NULL;
  2521. }
  2522. if (zeropad) {
  2523. if (PyUnicode_Fill(writer->buffer, writer->pos, zeropad, '0') == -1)
  2524. return NULL;
  2525. writer->pos += zeropad;
  2526. }
  2527. if (_PyUnicodeWriter_WriteASCIIString(writer, &buffer[sign], len) < 0)
  2528. return NULL;
  2529. if (spacepad && (flags & F_LJUST)) {
  2530. if (PyUnicode_Fill(writer->buffer, writer->pos, spacepad, ' ') == -1)
  2531. return NULL;
  2532. writer->pos += spacepad;
  2533. }
  2534. break;
  2535. }
  2536. case 'p':
  2537. {
  2538. char number[MAX_INTMAX_CHARS];
  2539. len = sprintf(number, "%p", va_arg(*vargs, void*));
  2540. assert(len >= 0);
  2541. /* %p is ill-defined: ensure leading 0x. */
  2542. if (number[1] == 'X')
  2543. number[1] = 'x';
  2544. else if (number[1] != 'x') {
  2545. memmove(number + 2, number,
  2546. strlen(number) + 1);
  2547. number[0] = '0';
  2548. number[1] = 'x';
  2549. len += 2;
  2550. }
  2551. if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
  2552. return NULL;
  2553. break;
  2554. }
  2555. case 's':
  2556. {
  2557. if (sizemod) {
  2558. const wchar_t *s = va_arg(*vargs, const wchar_t*);
  2559. if (unicode_fromformat_write_wcstr(writer, s, width, precision, flags) < 0)
  2560. return NULL;
  2561. }
  2562. else {
  2563. /* UTF-8 */
  2564. const char *s = va_arg(*vargs, const char*);
  2565. if (unicode_fromformat_write_cstr(writer, s, width, precision, flags) < 0)
  2566. return NULL;
  2567. }
  2568. break;
  2569. }
  2570. case 'U':
  2571. {
  2572. PyObject *obj = va_arg(*vargs, PyObject *);
  2573. assert(obj && _PyUnicode_CHECK(obj));
  2574. if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
  2575. return NULL;
  2576. break;
  2577. }
  2578. case 'V':
  2579. {
  2580. PyObject *obj = va_arg(*vargs, PyObject *);
  2581. const char *str;
  2582. const wchar_t *wstr;
  2583. if (sizemod) {
  2584. wstr = va_arg(*vargs, const wchar_t*);
  2585. }
  2586. else {
  2587. str = va_arg(*vargs, const char *);
  2588. }
  2589. if (obj) {
  2590. assert(_PyUnicode_CHECK(obj));
  2591. if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
  2592. return NULL;
  2593. }
  2594. else if (sizemod) {
  2595. assert(wstr != NULL);
  2596. if (unicode_fromformat_write_wcstr(writer, wstr, width, precision, flags) < 0)
  2597. return NULL;
  2598. }
  2599. else {
  2600. assert(str != NULL);
  2601. if (unicode_fromformat_write_cstr(writer, str, width, precision, flags) < 0)
  2602. return NULL;
  2603. }
  2604. break;
  2605. }
  2606. case 'S':
  2607. {
  2608. PyObject *obj = va_arg(*vargs, PyObject *);
  2609. PyObject *str;
  2610. assert(obj);
  2611. str = PyObject_Str(obj);
  2612. if (!str)
  2613. return NULL;
  2614. if (unicode_fromformat_write_str(writer, str, width, precision, flags) == -1) {
  2615. Py_DECREF(str);
  2616. return NULL;
  2617. }
  2618. Py_DECREF(str);
  2619. break;
  2620. }
  2621. case 'R':
  2622. {
  2623. PyObject *obj = va_arg(*vargs, PyObject *);
  2624. PyObject *repr;
  2625. assert(obj);
  2626. repr = PyObject_Repr(obj);
  2627. if (!repr)
  2628. return NULL;
  2629. if (unicode_fromformat_write_str(writer, repr, width, precision, flags) == -1) {
  2630. Py_DECREF(repr);
  2631. return NULL;
  2632. }
  2633. Py_DECREF(repr);
  2634. break;
  2635. }
  2636. case 'A':
  2637. {
  2638. PyObject *obj = va_arg(*vargs, PyObject *);
  2639. PyObject *ascii;
  2640. assert(obj);
  2641. ascii = PyObject_ASCII(obj);
  2642. if (!ascii)
  2643. return NULL;
  2644. if (unicode_fromformat_write_str(writer, ascii, width, precision, flags) == -1) {
  2645. Py_DECREF(ascii);
  2646. return NULL;
  2647. }
  2648. Py_DECREF(ascii);
  2649. break;
  2650. }
  2651. default:
  2652. invalid_format:
  2653. PyErr_Format(PyExc_SystemError, "invalid format string: %s", p);
  2654. return NULL;
  2655. }
  2656. f++;
  2657. return f;
  2658. }
  2659. PyObject *
  2660. PyUnicode_FromFormatV(const char *format, va_list vargs)
  2661. {
  2662. va_list vargs2;
  2663. const char *f;
  2664. _PyUnicodeWriter writer;
  2665. _PyUnicodeWriter_Init(&writer);
  2666. writer.min_length = strlen(format) + 100;
  2667. writer.overallocate = 1;
  2668. // Copy varags to be able to pass a reference to a subfunction.
  2669. va_copy(vargs2, vargs);
  2670. for (f = format; *f; ) {
  2671. if (*f == '%') {
  2672. f = unicode_fromformat_arg(&writer, f, &vargs2);
  2673. if (f == NULL)
  2674. goto fail;
  2675. }
  2676. else {
  2677. const char *p;
  2678. Py_ssize_t len;
  2679. p = f;
  2680. do
  2681. {
  2682. if ((unsigned char)*p > 127) {
  2683. PyErr_Format(PyExc_ValueError,
  2684. "PyUnicode_FromFormatV() expects an ASCII-encoded format "
  2685. "string, got a non-ASCII byte: 0x%02x",
  2686. (unsigned char)*p);
  2687. goto fail;
  2688. }
  2689. p++;
  2690. }
  2691. while (*p != '\0' && *p != '%');
  2692. len = p - f;
  2693. if (*p == '\0')
  2694. writer.overallocate = 0;
  2695. if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
  2696. goto fail;
  2697. f = p;
  2698. }
  2699. }
  2700. va_end(vargs2);
  2701. return _PyUnicodeWriter_Finish(&writer);
  2702. fail:
  2703. va_end(vargs2);
  2704. _PyUnicodeWriter_Dealloc(&writer);
  2705. return NULL;
  2706. }
  2707. PyObject *
  2708. PyUnicode_FromFormat(const char *format, ...)
  2709. {
  2710. PyObject* ret;
  2711. va_list vargs;
  2712. va_start(vargs, format);
  2713. ret = PyUnicode_FromFormatV(format, vargs);
  2714. va_end(vargs);
  2715. return ret;
  2716. }
  2717. static Py_ssize_t
  2718. unicode_get_widechar_size(PyObject *unicode)
  2719. {
  2720. Py_ssize_t res;
  2721. assert(unicode != NULL);
  2722. assert(_PyUnicode_CHECK(unicode));
  2723. res = _PyUnicode_LENGTH(unicode);
  2724. #if SIZEOF_WCHAR_T == 2
  2725. if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
  2726. const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
  2727. const Py_UCS4 *end = s + res;
  2728. for (; s < end; ++s) {
  2729. if (*s > 0xFFFF) {
  2730. ++res;
  2731. }
  2732. }
  2733. }
  2734. #endif
  2735. return res;
  2736. }
  2737. static void
  2738. unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
  2739. {
  2740. assert(unicode != NULL);
  2741. assert(_PyUnicode_CHECK(unicode));
  2742. if (PyUnicode_KIND(unicode) == sizeof(wchar_t)) {
  2743. memcpy(w, PyUnicode_DATA(unicode), size * sizeof(wchar_t));
  2744. return;
  2745. }
  2746. if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
  2747. const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
  2748. for (; size--; ++s, ++w) {
  2749. *w = *s;
  2750. }
  2751. }
  2752. else {
  2753. #if SIZEOF_WCHAR_T == 4
  2754. assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
  2755. const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
  2756. for (; size--; ++s, ++w) {
  2757. *w = *s;
  2758. }
  2759. #else
  2760. assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
  2761. const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
  2762. for (; size--; ++s, ++w) {
  2763. Py_UCS4 ch = *s;
  2764. if (ch > 0xFFFF) {
  2765. assert(ch <= MAX_UNICODE);
  2766. /* encode surrogate pair in this case */
  2767. *w++ = Py_UNICODE_HIGH_SURROGATE(ch);
  2768. if (!size--)
  2769. break;
  2770. *w = Py_UNICODE_LOW_SURROGATE(ch);
  2771. }
  2772. else {
  2773. *w = ch;
  2774. }
  2775. }
  2776. #endif
  2777. }
  2778. }
  2779. #ifdef HAVE_WCHAR_H
  2780. /* Convert a Unicode object to a wide character string.
  2781. - If w is NULL: return the number of wide characters (including the null
  2782. character) required to convert the unicode object. Ignore size argument.
  2783. - Otherwise: return the number of wide characters (excluding the null
  2784. character) written into w. Write at most size wide characters (including
  2785. the null character). */
  2786. Py_ssize_t
  2787. PyUnicode_AsWideChar(PyObject *unicode,
  2788. wchar_t *w,
  2789. Py_ssize_t size)
  2790. {
  2791. Py_ssize_t res;
  2792. if (unicode == NULL) {
  2793. PyErr_BadInternalCall();
  2794. return -1;
  2795. }
  2796. if (!PyUnicode_Check(unicode)) {
  2797. PyErr_BadArgument();
  2798. return -1;
  2799. }
  2800. res = unicode_get_widechar_size(unicode);
  2801. if (w == NULL) {
  2802. return res + 1;
  2803. }
  2804. if (size > res) {
  2805. size = res + 1;
  2806. }
  2807. else {
  2808. res = size;
  2809. }
  2810. unicode_copy_as_widechar(unicode, w, size);
  2811. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  2812. /* Oracle Solaris uses non-Unicode internal wchar_t form for
  2813. non-Unicode locales and hence needs conversion first. */
  2814. if (_Py_LocaleUsesNonUnicodeWchar()) {
  2815. if (_Py_EncodeNonUnicodeWchar_InPlace(w, size) < 0) {
  2816. return -1;
  2817. }
  2818. }
  2819. #endif
  2820. return res;
  2821. }
  2822. wchar_t*
  2823. PyUnicode_AsWideCharString(PyObject *unicode,
  2824. Py_ssize_t *size)
  2825. {
  2826. wchar_t *buffer;
  2827. Py_ssize_t buflen;
  2828. if (unicode == NULL) {
  2829. PyErr_BadInternalCall();
  2830. return NULL;
  2831. }
  2832. if (!PyUnicode_Check(unicode)) {
  2833. PyErr_BadArgument();
  2834. return NULL;
  2835. }
  2836. buflen = unicode_get_widechar_size(unicode);
  2837. buffer = (wchar_t *) PyMem_New(wchar_t, (buflen + 1));
  2838. if (buffer == NULL) {
  2839. PyErr_NoMemory();
  2840. return NULL;
  2841. }
  2842. unicode_copy_as_widechar(unicode, buffer, buflen + 1);
  2843. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  2844. /* Oracle Solaris uses non-Unicode internal wchar_t form for
  2845. non-Unicode locales and hence needs conversion first. */
  2846. if (_Py_LocaleUsesNonUnicodeWchar()) {
  2847. if (_Py_EncodeNonUnicodeWchar_InPlace(buffer, (buflen + 1)) < 0) {
  2848. return NULL;
  2849. }
  2850. }
  2851. #endif
  2852. if (size != NULL) {
  2853. *size = buflen;
  2854. }
  2855. else if (wcslen(buffer) != (size_t)buflen) {
  2856. PyMem_Free(buffer);
  2857. PyErr_SetString(PyExc_ValueError,
  2858. "embedded null character");
  2859. return NULL;
  2860. }
  2861. return buffer;
  2862. }
  2863. #endif /* HAVE_WCHAR_H */
  2864. int
  2865. _PyUnicode_WideCharString_Converter(PyObject *obj, void *ptr)
  2866. {
  2867. wchar_t **p = (wchar_t **)ptr;
  2868. if (obj == NULL) {
  2869. PyMem_Free(*p);
  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, not %.50s",
  2882. Py_TYPE(obj)->tp_name);
  2883. return 0;
  2884. }
  2885. int
  2886. _PyUnicode_WideCharString_Opt_Converter(PyObject *obj, void *ptr)
  2887. {
  2888. wchar_t **p = (wchar_t **)ptr;
  2889. if (obj == NULL) {
  2890. PyMem_Free(*p);
  2891. *p = NULL;
  2892. return 1;
  2893. }
  2894. if (obj == Py_None) {
  2895. *p = NULL;
  2896. return 1;
  2897. }
  2898. if (PyUnicode_Check(obj)) {
  2899. *p = PyUnicode_AsWideCharString(obj, NULL);
  2900. if (*p == NULL) {
  2901. return 0;
  2902. }
  2903. return Py_CLEANUP_SUPPORTED;
  2904. }
  2905. PyErr_Format(PyExc_TypeError,
  2906. "argument must be str or None, not %.50s",
  2907. Py_TYPE(obj)->tp_name);
  2908. return 0;
  2909. }
  2910. PyObject *
  2911. PyUnicode_FromOrdinal(int ordinal)
  2912. {
  2913. if (ordinal < 0 || ordinal > MAX_UNICODE) {
  2914. PyErr_SetString(PyExc_ValueError,
  2915. "chr() arg not in range(0x110000)");
  2916. return NULL;
  2917. }
  2918. return unicode_char((Py_UCS4)ordinal);
  2919. }
  2920. PyObject *
  2921. PyUnicode_FromObject(PyObject *obj)
  2922. {
  2923. /* XXX Perhaps we should make this API an alias of
  2924. PyObject_Str() instead ?! */
  2925. if (PyUnicode_CheckExact(obj)) {
  2926. return Py_NewRef(obj);
  2927. }
  2928. if (PyUnicode_Check(obj)) {
  2929. /* For a Unicode subtype that's not a Unicode object,
  2930. return a true Unicode object with the same data. */
  2931. return _PyUnicode_Copy(obj);
  2932. }
  2933. PyErr_Format(PyExc_TypeError,
  2934. "Can't convert '%.100s' object to str implicitly",
  2935. Py_TYPE(obj)->tp_name);
  2936. return NULL;
  2937. }
  2938. PyObject *
  2939. PyUnicode_FromEncodedObject(PyObject *obj,
  2940. const char *encoding,
  2941. const char *errors)
  2942. {
  2943. Py_buffer buffer;
  2944. PyObject *v;
  2945. if (obj == NULL) {
  2946. PyErr_BadInternalCall();
  2947. return NULL;
  2948. }
  2949. /* Decoding bytes objects is the most common case and should be fast */
  2950. if (PyBytes_Check(obj)) {
  2951. if (PyBytes_GET_SIZE(obj) == 0) {
  2952. if (unicode_check_encoding_errors(encoding, errors) < 0) {
  2953. return NULL;
  2954. }
  2955. _Py_RETURN_UNICODE_EMPTY();
  2956. }
  2957. return PyUnicode_Decode(
  2958. PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
  2959. encoding, errors);
  2960. }
  2961. if (PyUnicode_Check(obj)) {
  2962. PyErr_SetString(PyExc_TypeError,
  2963. "decoding str is not supported");
  2964. return NULL;
  2965. }
  2966. /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
  2967. if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
  2968. PyErr_Format(PyExc_TypeError,
  2969. "decoding to str: need a bytes-like object, %.80s found",
  2970. Py_TYPE(obj)->tp_name);
  2971. return NULL;
  2972. }
  2973. if (buffer.len == 0) {
  2974. PyBuffer_Release(&buffer);
  2975. if (unicode_check_encoding_errors(encoding, errors) < 0) {
  2976. return NULL;
  2977. }
  2978. _Py_RETURN_UNICODE_EMPTY();
  2979. }
  2980. v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
  2981. PyBuffer_Release(&buffer);
  2982. return v;
  2983. }
  2984. /* Normalize an encoding name: similar to encodings.normalize_encoding(), but
  2985. also convert to lowercase. Return 1 on success, or 0 on error (encoding is
  2986. longer than lower_len-1). */
  2987. int
  2988. _Py_normalize_encoding(const char *encoding,
  2989. char *lower,
  2990. size_t lower_len)
  2991. {
  2992. const char *e;
  2993. char *l;
  2994. char *l_end;
  2995. int punct;
  2996. assert(encoding != NULL);
  2997. e = encoding;
  2998. l = lower;
  2999. l_end = &lower[lower_len - 1];
  3000. punct = 0;
  3001. while (1) {
  3002. char c = *e;
  3003. if (c == 0) {
  3004. break;
  3005. }
  3006. if (Py_ISALNUM(c) || c == '.') {
  3007. if (punct && l != lower) {
  3008. if (l == l_end) {
  3009. return 0;
  3010. }
  3011. *l++ = '_';
  3012. }
  3013. punct = 0;
  3014. if (l == l_end) {
  3015. return 0;
  3016. }
  3017. *l++ = Py_TOLOWER(c);
  3018. }
  3019. else {
  3020. punct = 1;
  3021. }
  3022. e++;
  3023. }
  3024. *l = '\0';
  3025. return 1;
  3026. }
  3027. PyObject *
  3028. PyUnicode_Decode(const char *s,
  3029. Py_ssize_t size,
  3030. const char *encoding,
  3031. const char *errors)
  3032. {
  3033. PyObject *buffer = NULL, *unicode;
  3034. Py_buffer info;
  3035. char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
  3036. if (unicode_check_encoding_errors(encoding, errors) < 0) {
  3037. return NULL;
  3038. }
  3039. if (size == 0) {
  3040. _Py_RETURN_UNICODE_EMPTY();
  3041. }
  3042. if (encoding == NULL) {
  3043. return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
  3044. }
  3045. /* Shortcuts for common default encodings */
  3046. if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
  3047. char *lower = buflower;
  3048. /* Fast paths */
  3049. if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
  3050. lower += 3;
  3051. if (*lower == '_') {
  3052. /* Match "utf8" and "utf_8" */
  3053. lower++;
  3054. }
  3055. if (lower[0] == '8' && lower[1] == 0) {
  3056. return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
  3057. }
  3058. else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
  3059. return PyUnicode_DecodeUTF16(s, size, errors, 0);
  3060. }
  3061. else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
  3062. return PyUnicode_DecodeUTF32(s, size, errors, 0);
  3063. }
  3064. }
  3065. else {
  3066. if (strcmp(lower, "ascii") == 0
  3067. || strcmp(lower, "us_ascii") == 0) {
  3068. return PyUnicode_DecodeASCII(s, size, errors);
  3069. }
  3070. #ifdef MS_WINDOWS
  3071. else if (strcmp(lower, "mbcs") == 0) {
  3072. return PyUnicode_DecodeMBCS(s, size, errors);
  3073. }
  3074. #endif
  3075. else if (strcmp(lower, "latin1") == 0
  3076. || strcmp(lower, "latin_1") == 0
  3077. || strcmp(lower, "iso_8859_1") == 0
  3078. || strcmp(lower, "iso8859_1") == 0) {
  3079. return PyUnicode_DecodeLatin1(s, size, errors);
  3080. }
  3081. }
  3082. }
  3083. /* Decode via the codec registry */
  3084. buffer = NULL;
  3085. if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
  3086. goto onError;
  3087. buffer = PyMemoryView_FromBuffer(&info);
  3088. if (buffer == NULL)
  3089. goto onError;
  3090. unicode = _PyCodec_DecodeText(buffer, encoding, errors);
  3091. if (unicode == NULL)
  3092. goto onError;
  3093. if (!PyUnicode_Check(unicode)) {
  3094. PyErr_Format(PyExc_TypeError,
  3095. "'%.400s' decoder returned '%.400s' instead of 'str'; "
  3096. "use codecs.decode() to decode to arbitrary types",
  3097. encoding,
  3098. Py_TYPE(unicode)->tp_name);
  3099. Py_DECREF(unicode);
  3100. goto onError;
  3101. }
  3102. Py_DECREF(buffer);
  3103. return unicode_result(unicode);
  3104. onError:
  3105. Py_XDECREF(buffer);
  3106. return NULL;
  3107. }
  3108. PyObject *
  3109. PyUnicode_AsDecodedObject(PyObject *unicode,
  3110. const char *encoding,
  3111. const char *errors)
  3112. {
  3113. if (!PyUnicode_Check(unicode)) {
  3114. PyErr_BadArgument();
  3115. return NULL;
  3116. }
  3117. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  3118. "PyUnicode_AsDecodedObject() is deprecated; "
  3119. "use PyCodec_Decode() to decode from str", 1) < 0)
  3120. return NULL;
  3121. if (encoding == NULL)
  3122. encoding = PyUnicode_GetDefaultEncoding();
  3123. /* Decode via the codec registry */
  3124. return PyCodec_Decode(unicode, encoding, errors);
  3125. }
  3126. PyObject *
  3127. PyUnicode_AsDecodedUnicode(PyObject *unicode,
  3128. const char *encoding,
  3129. const char *errors)
  3130. {
  3131. PyObject *v;
  3132. if (!PyUnicode_Check(unicode)) {
  3133. PyErr_BadArgument();
  3134. goto onError;
  3135. }
  3136. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  3137. "PyUnicode_AsDecodedUnicode() is deprecated; "
  3138. "use PyCodec_Decode() to decode from str to str", 1) < 0)
  3139. return NULL;
  3140. if (encoding == NULL)
  3141. encoding = PyUnicode_GetDefaultEncoding();
  3142. /* Decode via the codec registry */
  3143. v = PyCodec_Decode(unicode, encoding, errors);
  3144. if (v == NULL)
  3145. goto onError;
  3146. if (!PyUnicode_Check(v)) {
  3147. PyErr_Format(PyExc_TypeError,
  3148. "'%.400s' decoder returned '%.400s' instead of 'str'; "
  3149. "use codecs.decode() to decode to arbitrary types",
  3150. encoding,
  3151. Py_TYPE(unicode)->tp_name);
  3152. Py_DECREF(v);
  3153. goto onError;
  3154. }
  3155. return unicode_result(v);
  3156. onError:
  3157. return NULL;
  3158. }
  3159. PyObject *
  3160. PyUnicode_AsEncodedObject(PyObject *unicode,
  3161. const char *encoding,
  3162. const char *errors)
  3163. {
  3164. PyObject *v;
  3165. if (!PyUnicode_Check(unicode)) {
  3166. PyErr_BadArgument();
  3167. goto onError;
  3168. }
  3169. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  3170. "PyUnicode_AsEncodedObject() is deprecated; "
  3171. "use PyUnicode_AsEncodedString() to encode from str to bytes "
  3172. "or PyCodec_Encode() for generic encoding", 1) < 0)
  3173. return NULL;
  3174. if (encoding == NULL)
  3175. encoding = PyUnicode_GetDefaultEncoding();
  3176. /* Encode via the codec registry */
  3177. v = PyCodec_Encode(unicode, encoding, errors);
  3178. if (v == NULL)
  3179. goto onError;
  3180. return v;
  3181. onError:
  3182. return NULL;
  3183. }
  3184. static PyObject *
  3185. unicode_encode_locale(PyObject *unicode, _Py_error_handler error_handler,
  3186. int current_locale)
  3187. {
  3188. Py_ssize_t wlen;
  3189. wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
  3190. if (wstr == NULL) {
  3191. return NULL;
  3192. }
  3193. if ((size_t)wlen != wcslen(wstr)) {
  3194. PyErr_SetString(PyExc_ValueError, "embedded null character");
  3195. PyMem_Free(wstr);
  3196. return NULL;
  3197. }
  3198. char *str;
  3199. size_t error_pos;
  3200. const char *reason;
  3201. int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
  3202. current_locale, error_handler);
  3203. PyMem_Free(wstr);
  3204. if (res != 0) {
  3205. if (res == -2) {
  3206. PyObject *exc;
  3207. exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
  3208. "locale", unicode,
  3209. (Py_ssize_t)error_pos,
  3210. (Py_ssize_t)(error_pos+1),
  3211. reason);
  3212. if (exc != NULL) {
  3213. PyCodec_StrictErrors(exc);
  3214. Py_DECREF(exc);
  3215. }
  3216. }
  3217. else if (res == -3) {
  3218. PyErr_SetString(PyExc_ValueError, "unsupported error handler");
  3219. }
  3220. else {
  3221. PyErr_NoMemory();
  3222. }
  3223. return NULL;
  3224. }
  3225. PyObject *bytes = PyBytes_FromString(str);
  3226. PyMem_RawFree(str);
  3227. return bytes;
  3228. }
  3229. PyObject *
  3230. PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
  3231. {
  3232. _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
  3233. return unicode_encode_locale(unicode, error_handler, 1);
  3234. }
  3235. PyObject *
  3236. PyUnicode_EncodeFSDefault(PyObject *unicode)
  3237. {
  3238. PyInterpreterState *interp = _PyInterpreterState_GET();
  3239. struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
  3240. if (fs_codec->utf8) {
  3241. return unicode_encode_utf8(unicode,
  3242. fs_codec->error_handler,
  3243. fs_codec->errors);
  3244. }
  3245. #ifndef _Py_FORCE_UTF8_FS_ENCODING
  3246. else if (fs_codec->encoding) {
  3247. return PyUnicode_AsEncodedString(unicode,
  3248. fs_codec->encoding,
  3249. fs_codec->errors);
  3250. }
  3251. #endif
  3252. else {
  3253. /* Before _PyUnicode_InitEncodings() is called, the Python codec
  3254. machinery is not ready and so cannot be used:
  3255. use wcstombs() in this case. */
  3256. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  3257. const wchar_t *filesystem_errors = config->filesystem_errors;
  3258. assert(filesystem_errors != NULL);
  3259. _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
  3260. assert(errors != _Py_ERROR_UNKNOWN);
  3261. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  3262. return unicode_encode_utf8(unicode, errors, NULL);
  3263. #else
  3264. return unicode_encode_locale(unicode, errors, 0);
  3265. #endif
  3266. }
  3267. }
  3268. PyObject *
  3269. PyUnicode_AsEncodedString(PyObject *unicode,
  3270. const char *encoding,
  3271. const char *errors)
  3272. {
  3273. PyObject *v;
  3274. char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
  3275. if (!PyUnicode_Check(unicode)) {
  3276. PyErr_BadArgument();
  3277. return NULL;
  3278. }
  3279. if (unicode_check_encoding_errors(encoding, errors) < 0) {
  3280. return NULL;
  3281. }
  3282. if (encoding == NULL) {
  3283. return _PyUnicode_AsUTF8String(unicode, errors);
  3284. }
  3285. /* Shortcuts for common default encodings */
  3286. if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
  3287. char *lower = buflower;
  3288. /* Fast paths */
  3289. if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
  3290. lower += 3;
  3291. if (*lower == '_') {
  3292. /* Match "utf8" and "utf_8" */
  3293. lower++;
  3294. }
  3295. if (lower[0] == '8' && lower[1] == 0) {
  3296. return _PyUnicode_AsUTF8String(unicode, errors);
  3297. }
  3298. else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
  3299. return _PyUnicode_EncodeUTF16(unicode, errors, 0);
  3300. }
  3301. else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
  3302. return _PyUnicode_EncodeUTF32(unicode, errors, 0);
  3303. }
  3304. }
  3305. else {
  3306. if (strcmp(lower, "ascii") == 0
  3307. || strcmp(lower, "us_ascii") == 0) {
  3308. return _PyUnicode_AsASCIIString(unicode, errors);
  3309. }
  3310. #ifdef MS_WINDOWS
  3311. else if (strcmp(lower, "mbcs") == 0) {
  3312. return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
  3313. }
  3314. #endif
  3315. else if (strcmp(lower, "latin1") == 0 ||
  3316. strcmp(lower, "latin_1") == 0 ||
  3317. strcmp(lower, "iso_8859_1") == 0 ||
  3318. strcmp(lower, "iso8859_1") == 0) {
  3319. return _PyUnicode_AsLatin1String(unicode, errors);
  3320. }
  3321. }
  3322. }
  3323. /* Encode via the codec registry */
  3324. v = _PyCodec_EncodeText(unicode, encoding, errors);
  3325. if (v == NULL)
  3326. return NULL;
  3327. /* The normal path */
  3328. if (PyBytes_Check(v))
  3329. return v;
  3330. /* If the codec returns a buffer, raise a warning and convert to bytes */
  3331. if (PyByteArray_Check(v)) {
  3332. int error;
  3333. PyObject *b;
  3334. error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
  3335. "encoder %s returned bytearray instead of bytes; "
  3336. "use codecs.encode() to encode to arbitrary types",
  3337. encoding);
  3338. if (error) {
  3339. Py_DECREF(v);
  3340. return NULL;
  3341. }
  3342. b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
  3343. PyByteArray_GET_SIZE(v));
  3344. Py_DECREF(v);
  3345. return b;
  3346. }
  3347. PyErr_Format(PyExc_TypeError,
  3348. "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
  3349. "use codecs.encode() to encode to arbitrary types",
  3350. encoding,
  3351. Py_TYPE(v)->tp_name);
  3352. Py_DECREF(v);
  3353. return NULL;
  3354. }
  3355. PyObject *
  3356. PyUnicode_AsEncodedUnicode(PyObject *unicode,
  3357. const char *encoding,
  3358. const char *errors)
  3359. {
  3360. PyObject *v;
  3361. if (!PyUnicode_Check(unicode)) {
  3362. PyErr_BadArgument();
  3363. goto onError;
  3364. }
  3365. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  3366. "PyUnicode_AsEncodedUnicode() is deprecated; "
  3367. "use PyCodec_Encode() to encode from str to str", 1) < 0)
  3368. return NULL;
  3369. if (encoding == NULL)
  3370. encoding = PyUnicode_GetDefaultEncoding();
  3371. /* Encode via the codec registry */
  3372. v = PyCodec_Encode(unicode, encoding, errors);
  3373. if (v == NULL)
  3374. goto onError;
  3375. if (!PyUnicode_Check(v)) {
  3376. PyErr_Format(PyExc_TypeError,
  3377. "'%.400s' encoder returned '%.400s' instead of 'str'; "
  3378. "use codecs.encode() to encode to arbitrary types",
  3379. encoding,
  3380. Py_TYPE(v)->tp_name);
  3381. Py_DECREF(v);
  3382. goto onError;
  3383. }
  3384. return v;
  3385. onError:
  3386. return NULL;
  3387. }
  3388. static PyObject*
  3389. unicode_decode_locale(const char *str, Py_ssize_t len,
  3390. _Py_error_handler errors, int current_locale)
  3391. {
  3392. if (str[len] != '\0' || (size_t)len != strlen(str)) {
  3393. PyErr_SetString(PyExc_ValueError, "embedded null byte");
  3394. return NULL;
  3395. }
  3396. wchar_t *wstr;
  3397. size_t wlen;
  3398. const char *reason;
  3399. int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
  3400. current_locale, errors);
  3401. if (res != 0) {
  3402. if (res == -2) {
  3403. PyObject *exc;
  3404. exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
  3405. "locale", str, len,
  3406. (Py_ssize_t)wlen,
  3407. (Py_ssize_t)(wlen + 1),
  3408. reason);
  3409. if (exc != NULL) {
  3410. PyCodec_StrictErrors(exc);
  3411. Py_DECREF(exc);
  3412. }
  3413. }
  3414. else if (res == -3) {
  3415. PyErr_SetString(PyExc_ValueError, "unsupported error handler");
  3416. }
  3417. else {
  3418. PyErr_NoMemory();
  3419. }
  3420. return NULL;
  3421. }
  3422. PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
  3423. PyMem_RawFree(wstr);
  3424. return unicode;
  3425. }
  3426. PyObject*
  3427. PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
  3428. const char *errors)
  3429. {
  3430. _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
  3431. return unicode_decode_locale(str, len, error_handler, 1);
  3432. }
  3433. PyObject*
  3434. PyUnicode_DecodeLocale(const char *str, const char *errors)
  3435. {
  3436. Py_ssize_t size = (Py_ssize_t)strlen(str);
  3437. _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
  3438. return unicode_decode_locale(str, size, error_handler, 1);
  3439. }
  3440. PyObject*
  3441. PyUnicode_DecodeFSDefault(const char *s) {
  3442. Py_ssize_t size = (Py_ssize_t)strlen(s);
  3443. return PyUnicode_DecodeFSDefaultAndSize(s, size);
  3444. }
  3445. PyObject*
  3446. PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
  3447. {
  3448. PyInterpreterState *interp = _PyInterpreterState_GET();
  3449. struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
  3450. if (fs_codec->utf8) {
  3451. return unicode_decode_utf8(s, size,
  3452. fs_codec->error_handler,
  3453. fs_codec->errors,
  3454. NULL);
  3455. }
  3456. #ifndef _Py_FORCE_UTF8_FS_ENCODING
  3457. else if (fs_codec->encoding) {
  3458. return PyUnicode_Decode(s, size,
  3459. fs_codec->encoding,
  3460. fs_codec->errors);
  3461. }
  3462. #endif
  3463. else {
  3464. /* Before _PyUnicode_InitEncodings() is called, the Python codec
  3465. machinery is not ready and so cannot be used:
  3466. use mbstowcs() in this case. */
  3467. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  3468. const wchar_t *filesystem_errors = config->filesystem_errors;
  3469. assert(filesystem_errors != NULL);
  3470. _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
  3471. assert(errors != _Py_ERROR_UNKNOWN);
  3472. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  3473. return unicode_decode_utf8(s, size, errors, NULL, NULL);
  3474. #else
  3475. return unicode_decode_locale(s, size, errors, 0);
  3476. #endif
  3477. }
  3478. }
  3479. int
  3480. PyUnicode_FSConverter(PyObject* arg, void* addr)
  3481. {
  3482. PyObject *path = NULL;
  3483. PyObject *output = NULL;
  3484. Py_ssize_t size;
  3485. const char *data;
  3486. if (arg == NULL) {
  3487. Py_DECREF(*(PyObject**)addr);
  3488. *(PyObject**)addr = NULL;
  3489. return 1;
  3490. }
  3491. path = PyOS_FSPath(arg);
  3492. if (path == NULL) {
  3493. return 0;
  3494. }
  3495. if (PyBytes_Check(path)) {
  3496. output = path;
  3497. }
  3498. else { // PyOS_FSPath() guarantees its returned value is bytes or str.
  3499. output = PyUnicode_EncodeFSDefault(path);
  3500. Py_DECREF(path);
  3501. if (!output) {
  3502. return 0;
  3503. }
  3504. assert(PyBytes_Check(output));
  3505. }
  3506. size = PyBytes_GET_SIZE(output);
  3507. data = PyBytes_AS_STRING(output);
  3508. if ((size_t)size != strlen(data)) {
  3509. PyErr_SetString(PyExc_ValueError, "embedded null byte");
  3510. Py_DECREF(output);
  3511. return 0;
  3512. }
  3513. *(PyObject**)addr = output;
  3514. return Py_CLEANUP_SUPPORTED;
  3515. }
  3516. int
  3517. PyUnicode_FSDecoder(PyObject* arg, void* addr)
  3518. {
  3519. if (arg == NULL) {
  3520. Py_DECREF(*(PyObject**)addr);
  3521. *(PyObject**)addr = NULL;
  3522. return 1;
  3523. }
  3524. PyObject *path = PyOS_FSPath(arg);
  3525. if (path == NULL) {
  3526. return 0;
  3527. }
  3528. PyObject *output = NULL;
  3529. if (PyUnicode_Check(path)) {
  3530. output = path;
  3531. }
  3532. else if (PyBytes_Check(path)) {
  3533. output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path),
  3534. PyBytes_GET_SIZE(path));
  3535. Py_DECREF(path);
  3536. if (!output) {
  3537. return 0;
  3538. }
  3539. }
  3540. else {
  3541. PyErr_Format(PyExc_TypeError,
  3542. "path should be string, bytes, or os.PathLike, not %.200s",
  3543. Py_TYPE(arg)->tp_name);
  3544. Py_DECREF(path);
  3545. return 0;
  3546. }
  3547. if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
  3548. PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
  3549. PyErr_SetString(PyExc_ValueError, "embedded null character");
  3550. Py_DECREF(output);
  3551. return 0;
  3552. }
  3553. *(PyObject**)addr = output;
  3554. return Py_CLEANUP_SUPPORTED;
  3555. }
  3556. static int unicode_fill_utf8(PyObject *unicode);
  3557. const char *
  3558. PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
  3559. {
  3560. if (!PyUnicode_Check(unicode)) {
  3561. PyErr_BadArgument();
  3562. return NULL;
  3563. }
  3564. if (PyUnicode_UTF8(unicode) == NULL) {
  3565. if (unicode_fill_utf8(unicode) == -1) {
  3566. return NULL;
  3567. }
  3568. }
  3569. if (psize)
  3570. *psize = PyUnicode_UTF8_LENGTH(unicode);
  3571. return PyUnicode_UTF8(unicode);
  3572. }
  3573. const char *
  3574. PyUnicode_AsUTF8(PyObject *unicode)
  3575. {
  3576. return PyUnicode_AsUTF8AndSize(unicode, NULL);
  3577. }
  3578. const char *
  3579. _PyUnicode_AsUTF8NoNUL(PyObject *unicode)
  3580. {
  3581. Py_ssize_t size;
  3582. const char *s = PyUnicode_AsUTF8AndSize(unicode, &size);
  3583. if (s && strlen(s) != (size_t)size) {
  3584. PyErr_SetString(PyExc_ValueError, "embedded null character");
  3585. return NULL;
  3586. }
  3587. return s;
  3588. }
  3589. /*
  3590. PyUnicode_GetSize() has been deprecated since Python 3.3
  3591. because it returned length of Py_UNICODE.
  3592. But this function is part of stable abi, because it don't
  3593. include Py_UNICODE in signature and it was not excluded from
  3594. stable abi in PEP 384.
  3595. */
  3596. PyAPI_FUNC(Py_ssize_t)
  3597. PyUnicode_GetSize(PyObject *unicode)
  3598. {
  3599. PyErr_SetString(PyExc_RuntimeError,
  3600. "PyUnicode_GetSize has been removed.");
  3601. return -1;
  3602. }
  3603. Py_ssize_t
  3604. PyUnicode_GetLength(PyObject *unicode)
  3605. {
  3606. if (!PyUnicode_Check(unicode)) {
  3607. PyErr_BadArgument();
  3608. return -1;
  3609. }
  3610. return PyUnicode_GET_LENGTH(unicode);
  3611. }
  3612. Py_UCS4
  3613. PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
  3614. {
  3615. const void *data;
  3616. int kind;
  3617. if (!PyUnicode_Check(unicode)) {
  3618. PyErr_BadArgument();
  3619. return (Py_UCS4)-1;
  3620. }
  3621. if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
  3622. PyErr_SetString(PyExc_IndexError, "string index out of range");
  3623. return (Py_UCS4)-1;
  3624. }
  3625. data = PyUnicode_DATA(unicode);
  3626. kind = PyUnicode_KIND(unicode);
  3627. return PyUnicode_READ(kind, data, index);
  3628. }
  3629. int
  3630. PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
  3631. {
  3632. if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
  3633. PyErr_BadArgument();
  3634. return -1;
  3635. }
  3636. if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
  3637. PyErr_SetString(PyExc_IndexError, "string index out of range");
  3638. return -1;
  3639. }
  3640. if (unicode_check_modifiable(unicode))
  3641. return -1;
  3642. if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
  3643. PyErr_SetString(PyExc_ValueError, "character out of range");
  3644. return -1;
  3645. }
  3646. PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
  3647. index, ch);
  3648. return 0;
  3649. }
  3650. const char *
  3651. PyUnicode_GetDefaultEncoding(void)
  3652. {
  3653. return "utf-8";
  3654. }
  3655. /* create or adjust a UnicodeDecodeError */
  3656. static void
  3657. make_decode_exception(PyObject **exceptionObject,
  3658. const char *encoding,
  3659. const char *input, Py_ssize_t length,
  3660. Py_ssize_t startpos, Py_ssize_t endpos,
  3661. const char *reason)
  3662. {
  3663. if (*exceptionObject == NULL) {
  3664. *exceptionObject = PyUnicodeDecodeError_Create(
  3665. encoding, input, length, startpos, endpos, reason);
  3666. }
  3667. else {
  3668. if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
  3669. goto onError;
  3670. if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
  3671. goto onError;
  3672. if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
  3673. goto onError;
  3674. }
  3675. return;
  3676. onError:
  3677. Py_CLEAR(*exceptionObject);
  3678. }
  3679. #ifdef MS_WINDOWS
  3680. static int
  3681. widechar_resize(wchar_t **buf, Py_ssize_t *size, Py_ssize_t newsize)
  3682. {
  3683. if (newsize > *size) {
  3684. wchar_t *newbuf = *buf;
  3685. if (PyMem_Resize(newbuf, wchar_t, newsize) == NULL) {
  3686. PyErr_NoMemory();
  3687. return -1;
  3688. }
  3689. *buf = newbuf;
  3690. }
  3691. *size = newsize;
  3692. return 0;
  3693. }
  3694. /* error handling callback helper:
  3695. build arguments, call the callback and check the arguments,
  3696. if no exception occurred, copy the replacement to the output
  3697. and adjust various state variables.
  3698. return 0 on success, -1 on error
  3699. */
  3700. static int
  3701. unicode_decode_call_errorhandler_wchar(
  3702. const char *errors, PyObject **errorHandler,
  3703. const char *encoding, const char *reason,
  3704. const char **input, const char **inend, Py_ssize_t *startinpos,
  3705. Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
  3706. wchar_t **buf, Py_ssize_t *bufsize, Py_ssize_t *outpos)
  3707. {
  3708. static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
  3709. PyObject *restuple = NULL;
  3710. PyObject *repunicode = NULL;
  3711. Py_ssize_t outsize;
  3712. Py_ssize_t insize;
  3713. Py_ssize_t requiredsize;
  3714. Py_ssize_t newpos;
  3715. PyObject *inputobj = NULL;
  3716. Py_ssize_t repwlen;
  3717. if (*errorHandler == NULL) {
  3718. *errorHandler = PyCodec_LookupError(errors);
  3719. if (*errorHandler == NULL)
  3720. goto onError;
  3721. }
  3722. make_decode_exception(exceptionObject,
  3723. encoding,
  3724. *input, *inend - *input,
  3725. *startinpos, *endinpos,
  3726. reason);
  3727. if (*exceptionObject == NULL)
  3728. goto onError;
  3729. restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
  3730. if (restuple == NULL)
  3731. goto onError;
  3732. if (!PyTuple_Check(restuple)) {
  3733. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  3734. goto onError;
  3735. }
  3736. if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
  3737. goto onError;
  3738. /* Copy back the bytes variables, which might have been modified by the
  3739. callback */
  3740. inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
  3741. if (!inputobj)
  3742. goto onError;
  3743. *input = PyBytes_AS_STRING(inputobj);
  3744. insize = PyBytes_GET_SIZE(inputobj);
  3745. *inend = *input + insize;
  3746. /* we can DECREF safely, as the exception has another reference,
  3747. so the object won't go away. */
  3748. Py_DECREF(inputobj);
  3749. if (newpos<0)
  3750. newpos = insize+newpos;
  3751. if (newpos<0 || newpos>insize) {
  3752. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
  3753. goto onError;
  3754. }
  3755. repwlen = PyUnicode_AsWideChar(repunicode, NULL, 0);
  3756. if (repwlen < 0)
  3757. goto onError;
  3758. repwlen--;
  3759. /* need more space? (at least enough for what we
  3760. have+the replacement+the rest of the string (starting
  3761. at the new input position), so we won't have to check space
  3762. when there are no errors in the rest of the string) */
  3763. requiredsize = *outpos;
  3764. if (requiredsize > PY_SSIZE_T_MAX - repwlen)
  3765. goto overflow;
  3766. requiredsize += repwlen;
  3767. if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
  3768. goto overflow;
  3769. requiredsize += insize - newpos;
  3770. outsize = *bufsize;
  3771. if (requiredsize > outsize) {
  3772. if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
  3773. requiredsize = 2*outsize;
  3774. if (widechar_resize(buf, bufsize, requiredsize) < 0) {
  3775. goto onError;
  3776. }
  3777. }
  3778. PyUnicode_AsWideChar(repunicode, *buf + *outpos, repwlen);
  3779. *outpos += repwlen;
  3780. *endinpos = newpos;
  3781. *inptr = *input + newpos;
  3782. /* we made it! */
  3783. Py_DECREF(restuple);
  3784. return 0;
  3785. overflow:
  3786. PyErr_SetString(PyExc_OverflowError,
  3787. "decoded result is too long for a Python string");
  3788. onError:
  3789. Py_XDECREF(restuple);
  3790. return -1;
  3791. }
  3792. #endif /* MS_WINDOWS */
  3793. static int
  3794. unicode_decode_call_errorhandler_writer(
  3795. const char *errors, PyObject **errorHandler,
  3796. const char *encoding, const char *reason,
  3797. const char **input, const char **inend, Py_ssize_t *startinpos,
  3798. Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
  3799. _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
  3800. {
  3801. static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
  3802. PyObject *restuple = NULL;
  3803. PyObject *repunicode = NULL;
  3804. Py_ssize_t insize;
  3805. Py_ssize_t newpos;
  3806. Py_ssize_t replen;
  3807. Py_ssize_t remain;
  3808. PyObject *inputobj = NULL;
  3809. int need_to_grow = 0;
  3810. const char *new_inptr;
  3811. if (*errorHandler == NULL) {
  3812. *errorHandler = PyCodec_LookupError(errors);
  3813. if (*errorHandler == NULL)
  3814. goto onError;
  3815. }
  3816. make_decode_exception(exceptionObject,
  3817. encoding,
  3818. *input, *inend - *input,
  3819. *startinpos, *endinpos,
  3820. reason);
  3821. if (*exceptionObject == NULL)
  3822. goto onError;
  3823. restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
  3824. if (restuple == NULL)
  3825. goto onError;
  3826. if (!PyTuple_Check(restuple)) {
  3827. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  3828. goto onError;
  3829. }
  3830. if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
  3831. goto onError;
  3832. /* Copy back the bytes variables, which might have been modified by the
  3833. callback */
  3834. inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
  3835. if (!inputobj)
  3836. goto onError;
  3837. remain = *inend - *input - *endinpos;
  3838. *input = PyBytes_AS_STRING(inputobj);
  3839. insize = PyBytes_GET_SIZE(inputobj);
  3840. *inend = *input + insize;
  3841. /* we can DECREF safely, as the exception has another reference,
  3842. so the object won't go away. */
  3843. Py_DECREF(inputobj);
  3844. if (newpos<0)
  3845. newpos = insize+newpos;
  3846. if (newpos<0 || newpos>insize) {
  3847. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
  3848. goto onError;
  3849. }
  3850. replen = PyUnicode_GET_LENGTH(repunicode);
  3851. if (replen > 1) {
  3852. writer->min_length += replen - 1;
  3853. need_to_grow = 1;
  3854. }
  3855. new_inptr = *input + newpos;
  3856. if (*inend - new_inptr > remain) {
  3857. /* We don't know the decoding algorithm here so we make the worst
  3858. assumption that one byte decodes to one unicode character.
  3859. If unfortunately one byte could decode to more unicode characters,
  3860. the decoder may write out-of-bound then. Is it possible for the
  3861. algorithms using this function? */
  3862. writer->min_length += *inend - new_inptr - remain;
  3863. need_to_grow = 1;
  3864. }
  3865. if (need_to_grow) {
  3866. writer->overallocate = 1;
  3867. if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
  3868. PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
  3869. goto onError;
  3870. }
  3871. if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
  3872. goto onError;
  3873. *endinpos = newpos;
  3874. *inptr = new_inptr;
  3875. /* we made it! */
  3876. Py_DECREF(restuple);
  3877. return 0;
  3878. onError:
  3879. Py_XDECREF(restuple);
  3880. return -1;
  3881. }
  3882. /* --- UTF-7 Codec -------------------------------------------------------- */
  3883. /* See RFC2152 for details. We encode conservatively and decode liberally. */
  3884. /* Three simple macros defining base-64. */
  3885. /* Is c a base-64 character? */
  3886. #define IS_BASE64(c) \
  3887. (((c) >= 'A' && (c) <= 'Z') || \
  3888. ((c) >= 'a' && (c) <= 'z') || \
  3889. ((c) >= '0' && (c) <= '9') || \
  3890. (c) == '+' || (c) == '/')
  3891. /* given that c is a base-64 character, what is its base-64 value? */
  3892. #define FROM_BASE64(c) \
  3893. (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
  3894. ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
  3895. ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
  3896. (c) == '+' ? 62 : 63)
  3897. /* What is the base-64 character of the bottom 6 bits of n? */
  3898. #define TO_BASE64(n) \
  3899. ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
  3900. /* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
  3901. * decoded as itself. We are permissive on decoding; the only ASCII
  3902. * byte not decoding to itself is the + which begins a base64
  3903. * string. */
  3904. #define DECODE_DIRECT(c) \
  3905. ((c) <= 127 && (c) != '+')
  3906. /* The UTF-7 encoder treats ASCII characters differently according to
  3907. * whether they are Set D, Set O, Whitespace, or special (i.e. none of
  3908. * the above). See RFC2152. This array identifies these different
  3909. * sets:
  3910. * 0 : "Set D"
  3911. * alphanumeric and '(),-./:?
  3912. * 1 : "Set O"
  3913. * !"#$%&*;<=>@[]^_`{|}
  3914. * 2 : "whitespace"
  3915. * ht nl cr sp
  3916. * 3 : special (must be base64 encoded)
  3917. * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
  3918. */
  3919. static
  3920. char utf7_category[128] = {
  3921. /* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
  3922. 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
  3923. /* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
  3924. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  3925. /* sp ! " # $ % & ' ( ) * + , - . / */
  3926. 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
  3927. /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
  3928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
  3929. /* @ A B C D E F G H I J K L M N O */
  3930. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  3931. /* P Q R S T U V W X Y Z [ \ ] ^ _ */
  3932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
  3933. /* ` a b c d e f g h i j k l m n o */
  3934. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  3935. /* p q r s t u v w x y z { | } ~ del */
  3936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
  3937. };
  3938. /* ENCODE_DIRECT: this character should be encoded as itself. The
  3939. * answer depends on whether we are encoding set O as itself, and also
  3940. * on whether we are encoding whitespace as itself. RFC2152 makes it
  3941. * clear that the answers to these questions vary between
  3942. * applications, so this code needs to be flexible. */
  3943. #define ENCODE_DIRECT(c, directO, directWS) \
  3944. ((c) < 128 && (c) > 0 && \
  3945. ((utf7_category[(c)] == 0) || \
  3946. (directWS && (utf7_category[(c)] == 2)) || \
  3947. (directO && (utf7_category[(c)] == 1))))
  3948. PyObject *
  3949. PyUnicode_DecodeUTF7(const char *s,
  3950. Py_ssize_t size,
  3951. const char *errors)
  3952. {
  3953. return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
  3954. }
  3955. /* The decoder. The only state we preserve is our read position,
  3956. * i.e. how many characters we have consumed. So if we end in the
  3957. * middle of a shift sequence we have to back off the read position
  3958. * and the output to the beginning of the sequence, otherwise we lose
  3959. * all the shift state (seen bits, number of bits seen, high
  3960. * surrogate). */
  3961. PyObject *
  3962. PyUnicode_DecodeUTF7Stateful(const char *s,
  3963. Py_ssize_t size,
  3964. const char *errors,
  3965. Py_ssize_t *consumed)
  3966. {
  3967. const char *starts = s;
  3968. Py_ssize_t startinpos;
  3969. Py_ssize_t endinpos;
  3970. const char *e;
  3971. _PyUnicodeWriter writer;
  3972. const char *errmsg = "";
  3973. int inShift = 0;
  3974. Py_ssize_t shiftOutStart;
  3975. unsigned int base64bits = 0;
  3976. unsigned long base64buffer = 0;
  3977. Py_UCS4 surrogate = 0;
  3978. PyObject *errorHandler = NULL;
  3979. PyObject *exc = NULL;
  3980. if (size == 0) {
  3981. if (consumed)
  3982. *consumed = 0;
  3983. _Py_RETURN_UNICODE_EMPTY();
  3984. }
  3985. /* Start off assuming it's all ASCII. Widen later as necessary. */
  3986. _PyUnicodeWriter_Init(&writer);
  3987. writer.min_length = size;
  3988. shiftOutStart = 0;
  3989. e = s + size;
  3990. while (s < e) {
  3991. Py_UCS4 ch;
  3992. restart:
  3993. ch = (unsigned char) *s;
  3994. if (inShift) { /* in a base-64 section */
  3995. if (IS_BASE64(ch)) { /* consume a base-64 character */
  3996. base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
  3997. base64bits += 6;
  3998. s++;
  3999. if (base64bits >= 16) {
  4000. /* we have enough bits for a UTF-16 value */
  4001. Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
  4002. base64bits -= 16;
  4003. base64buffer &= (1 << base64bits) - 1; /* clear high bits */
  4004. assert(outCh <= 0xffff);
  4005. if (surrogate) {
  4006. /* expecting a second surrogate */
  4007. if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
  4008. Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
  4009. if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
  4010. goto onError;
  4011. surrogate = 0;
  4012. continue;
  4013. }
  4014. else {
  4015. if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
  4016. goto onError;
  4017. surrogate = 0;
  4018. }
  4019. }
  4020. if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
  4021. /* first surrogate */
  4022. surrogate = outCh;
  4023. }
  4024. else {
  4025. if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
  4026. goto onError;
  4027. }
  4028. }
  4029. }
  4030. else { /* now leaving a base-64 section */
  4031. inShift = 0;
  4032. if (base64bits > 0) { /* left-over bits */
  4033. if (base64bits >= 6) {
  4034. /* We've seen at least one base-64 character */
  4035. s++;
  4036. errmsg = "partial character in shift sequence";
  4037. goto utf7Error;
  4038. }
  4039. else {
  4040. /* Some bits remain; they should be zero */
  4041. if (base64buffer != 0) {
  4042. s++;
  4043. errmsg = "non-zero padding bits in shift sequence";
  4044. goto utf7Error;
  4045. }
  4046. }
  4047. }
  4048. if (surrogate && DECODE_DIRECT(ch)) {
  4049. if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
  4050. goto onError;
  4051. }
  4052. surrogate = 0;
  4053. if (ch == '-') {
  4054. /* '-' is absorbed; other terminating
  4055. characters are preserved */
  4056. s++;
  4057. }
  4058. }
  4059. }
  4060. else if ( ch == '+' ) {
  4061. startinpos = s-starts;
  4062. s++; /* consume '+' */
  4063. if (s < e && *s == '-') { /* '+-' encodes '+' */
  4064. s++;
  4065. if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
  4066. goto onError;
  4067. }
  4068. else if (s < e && !IS_BASE64(*s)) {
  4069. s++;
  4070. errmsg = "ill-formed sequence";
  4071. goto utf7Error;
  4072. }
  4073. else { /* begin base64-encoded section */
  4074. inShift = 1;
  4075. surrogate = 0;
  4076. shiftOutStart = writer.pos;
  4077. base64bits = 0;
  4078. base64buffer = 0;
  4079. }
  4080. }
  4081. else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
  4082. s++;
  4083. if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
  4084. goto onError;
  4085. }
  4086. else {
  4087. startinpos = s-starts;
  4088. s++;
  4089. errmsg = "unexpected special character";
  4090. goto utf7Error;
  4091. }
  4092. continue;
  4093. utf7Error:
  4094. endinpos = s-starts;
  4095. if (unicode_decode_call_errorhandler_writer(
  4096. errors, &errorHandler,
  4097. "utf7", errmsg,
  4098. &starts, &e, &startinpos, &endinpos, &exc, &s,
  4099. &writer))
  4100. goto onError;
  4101. }
  4102. /* end of string */
  4103. if (inShift && !consumed) { /* in shift sequence, no more to follow */
  4104. /* if we're in an inconsistent state, that's an error */
  4105. inShift = 0;
  4106. if (surrogate ||
  4107. (base64bits >= 6) ||
  4108. (base64bits > 0 && base64buffer != 0)) {
  4109. endinpos = size;
  4110. if (unicode_decode_call_errorhandler_writer(
  4111. errors, &errorHandler,
  4112. "utf7", "unterminated shift sequence",
  4113. &starts, &e, &startinpos, &endinpos, &exc, &s,
  4114. &writer))
  4115. goto onError;
  4116. if (s < e)
  4117. goto restart;
  4118. }
  4119. }
  4120. /* return state */
  4121. if (consumed) {
  4122. if (inShift) {
  4123. *consumed = startinpos;
  4124. if (writer.pos != shiftOutStart && writer.maxchar > 127) {
  4125. PyObject *result = PyUnicode_FromKindAndData(
  4126. writer.kind, writer.data, shiftOutStart);
  4127. Py_XDECREF(errorHandler);
  4128. Py_XDECREF(exc);
  4129. _PyUnicodeWriter_Dealloc(&writer);
  4130. return result;
  4131. }
  4132. writer.pos = shiftOutStart; /* back off output */
  4133. }
  4134. else {
  4135. *consumed = s-starts;
  4136. }
  4137. }
  4138. Py_XDECREF(errorHandler);
  4139. Py_XDECREF(exc);
  4140. return _PyUnicodeWriter_Finish(&writer);
  4141. onError:
  4142. Py_XDECREF(errorHandler);
  4143. Py_XDECREF(exc);
  4144. _PyUnicodeWriter_Dealloc(&writer);
  4145. return NULL;
  4146. }
  4147. PyObject *
  4148. _PyUnicode_EncodeUTF7(PyObject *str,
  4149. int base64SetO,
  4150. int base64WhiteSpace,
  4151. const char *errors)
  4152. {
  4153. int kind;
  4154. const void *data;
  4155. Py_ssize_t len;
  4156. PyObject *v;
  4157. int inShift = 0;
  4158. Py_ssize_t i;
  4159. unsigned int base64bits = 0;
  4160. unsigned long base64buffer = 0;
  4161. char * out;
  4162. const char * start;
  4163. kind = PyUnicode_KIND(str);
  4164. data = PyUnicode_DATA(str);
  4165. len = PyUnicode_GET_LENGTH(str);
  4166. if (len == 0)
  4167. return PyBytes_FromStringAndSize(NULL, 0);
  4168. /* It might be possible to tighten this worst case */
  4169. if (len > PY_SSIZE_T_MAX / 8)
  4170. return PyErr_NoMemory();
  4171. v = PyBytes_FromStringAndSize(NULL, len * 8);
  4172. if (v == NULL)
  4173. return NULL;
  4174. start = out = PyBytes_AS_STRING(v);
  4175. for (i = 0; i < len; ++i) {
  4176. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  4177. if (inShift) {
  4178. if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
  4179. /* shifting out */
  4180. if (base64bits) { /* output remaining bits */
  4181. *out++ = TO_BASE64(base64buffer << (6-base64bits));
  4182. base64buffer = 0;
  4183. base64bits = 0;
  4184. }
  4185. inShift = 0;
  4186. /* Characters not in the BASE64 set implicitly unshift the sequence
  4187. so no '-' is required, except if the character is itself a '-' */
  4188. if (IS_BASE64(ch) || ch == '-') {
  4189. *out++ = '-';
  4190. }
  4191. *out++ = (char) ch;
  4192. }
  4193. else {
  4194. goto encode_char;
  4195. }
  4196. }
  4197. else { /* not in a shift sequence */
  4198. if (ch == '+') {
  4199. *out++ = '+';
  4200. *out++ = '-';
  4201. }
  4202. else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
  4203. *out++ = (char) ch;
  4204. }
  4205. else {
  4206. *out++ = '+';
  4207. inShift = 1;
  4208. goto encode_char;
  4209. }
  4210. }
  4211. continue;
  4212. encode_char:
  4213. if (ch >= 0x10000) {
  4214. assert(ch <= MAX_UNICODE);
  4215. /* code first surrogate */
  4216. base64bits += 16;
  4217. base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
  4218. while (base64bits >= 6) {
  4219. *out++ = TO_BASE64(base64buffer >> (base64bits-6));
  4220. base64bits -= 6;
  4221. }
  4222. /* prepare second surrogate */
  4223. ch = Py_UNICODE_LOW_SURROGATE(ch);
  4224. }
  4225. base64bits += 16;
  4226. base64buffer = (base64buffer << 16) | ch;
  4227. while (base64bits >= 6) {
  4228. *out++ = TO_BASE64(base64buffer >> (base64bits-6));
  4229. base64bits -= 6;
  4230. }
  4231. }
  4232. if (base64bits)
  4233. *out++= TO_BASE64(base64buffer << (6-base64bits) );
  4234. if (inShift)
  4235. *out++ = '-';
  4236. if (_PyBytes_Resize(&v, out - start) < 0)
  4237. return NULL;
  4238. return v;
  4239. }
  4240. #undef IS_BASE64
  4241. #undef FROM_BASE64
  4242. #undef TO_BASE64
  4243. #undef DECODE_DIRECT
  4244. #undef ENCODE_DIRECT
  4245. /* --- UTF-8 Codec -------------------------------------------------------- */
  4246. PyObject *
  4247. PyUnicode_DecodeUTF8(const char *s,
  4248. Py_ssize_t size,
  4249. const char *errors)
  4250. {
  4251. return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
  4252. }
  4253. #include "stringlib/asciilib.h"
  4254. #include "stringlib/codecs.h"
  4255. #include "stringlib/undef.h"
  4256. #include "stringlib/ucs1lib.h"
  4257. #include "stringlib/codecs.h"
  4258. #include "stringlib/undef.h"
  4259. #include "stringlib/ucs2lib.h"
  4260. #include "stringlib/codecs.h"
  4261. #include "stringlib/undef.h"
  4262. #include "stringlib/ucs4lib.h"
  4263. #include "stringlib/codecs.h"
  4264. #include "stringlib/undef.h"
  4265. /* Mask to quickly check whether a C 'size_t' contains a
  4266. non-ASCII, UTF8-encoded char. */
  4267. #if (SIZEOF_SIZE_T == 8)
  4268. # define ASCII_CHAR_MASK 0x8080808080808080ULL
  4269. #elif (SIZEOF_SIZE_T == 4)
  4270. # define ASCII_CHAR_MASK 0x80808080U
  4271. #else
  4272. # error C 'size_t' size should be either 4 or 8!
  4273. #endif
  4274. static Py_ssize_t
  4275. ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
  4276. {
  4277. const char *p = start;
  4278. #if SIZEOF_SIZE_T <= SIZEOF_VOID_P
  4279. assert(_Py_IS_ALIGNED(dest, ALIGNOF_SIZE_T));
  4280. if (_Py_IS_ALIGNED(p, ALIGNOF_SIZE_T)) {
  4281. /* Fast path, see in STRINGLIB(utf8_decode) for
  4282. an explanation. */
  4283. /* Help allocation */
  4284. const char *_p = p;
  4285. Py_UCS1 * q = dest;
  4286. while (_p + SIZEOF_SIZE_T <= end) {
  4287. size_t value = *(const size_t *) _p;
  4288. if (value & ASCII_CHAR_MASK)
  4289. break;
  4290. *((size_t *)q) = value;
  4291. _p += SIZEOF_SIZE_T;
  4292. q += SIZEOF_SIZE_T;
  4293. }
  4294. p = _p;
  4295. while (p < end) {
  4296. if ((unsigned char)*p & 0x80)
  4297. break;
  4298. *q++ = *p++;
  4299. }
  4300. return p - start;
  4301. }
  4302. #endif
  4303. while (p < end) {
  4304. /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
  4305. for an explanation. */
  4306. if (_Py_IS_ALIGNED(p, ALIGNOF_SIZE_T)) {
  4307. /* Help allocation */
  4308. const char *_p = p;
  4309. while (_p + SIZEOF_SIZE_T <= end) {
  4310. size_t value = *(const size_t *) _p;
  4311. if (value & ASCII_CHAR_MASK)
  4312. break;
  4313. _p += SIZEOF_SIZE_T;
  4314. }
  4315. p = _p;
  4316. if (_p == end)
  4317. break;
  4318. }
  4319. if ((unsigned char)*p & 0x80)
  4320. break;
  4321. ++p;
  4322. }
  4323. memcpy(dest, start, p - start);
  4324. return p - start;
  4325. }
  4326. static PyObject *
  4327. unicode_decode_utf8(const char *s, Py_ssize_t size,
  4328. _Py_error_handler error_handler, const char *errors,
  4329. Py_ssize_t *consumed)
  4330. {
  4331. if (size == 0) {
  4332. if (consumed)
  4333. *consumed = 0;
  4334. _Py_RETURN_UNICODE_EMPTY();
  4335. }
  4336. /* ASCII is equivalent to the first 128 ordinals in Unicode. */
  4337. if (size == 1 && (unsigned char)s[0] < 128) {
  4338. if (consumed) {
  4339. *consumed = 1;
  4340. }
  4341. return get_latin1_char((unsigned char)s[0]);
  4342. }
  4343. const char *starts = s;
  4344. const char *end = s + size;
  4345. // fast path: try ASCII string.
  4346. PyObject *u = PyUnicode_New(size, 127);
  4347. if (u == NULL) {
  4348. return NULL;
  4349. }
  4350. s += ascii_decode(s, end, PyUnicode_1BYTE_DATA(u));
  4351. if (s == end) {
  4352. if (consumed) {
  4353. *consumed = size;
  4354. }
  4355. return u;
  4356. }
  4357. // Use _PyUnicodeWriter after fast path is failed.
  4358. _PyUnicodeWriter writer;
  4359. _PyUnicodeWriter_InitWithBuffer(&writer, u);
  4360. writer.pos = s - starts;
  4361. Py_ssize_t startinpos, endinpos;
  4362. const char *errmsg = "";
  4363. PyObject *error_handler_obj = NULL;
  4364. PyObject *exc = NULL;
  4365. while (s < end) {
  4366. Py_UCS4 ch;
  4367. int kind = writer.kind;
  4368. if (kind == PyUnicode_1BYTE_KIND) {
  4369. if (PyUnicode_IS_ASCII(writer.buffer))
  4370. ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
  4371. else
  4372. ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
  4373. } else if (kind == PyUnicode_2BYTE_KIND) {
  4374. ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
  4375. } else {
  4376. assert(kind == PyUnicode_4BYTE_KIND);
  4377. ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
  4378. }
  4379. switch (ch) {
  4380. case 0:
  4381. if (s == end || consumed)
  4382. goto End;
  4383. errmsg = "unexpected end of data";
  4384. startinpos = s - starts;
  4385. endinpos = end - starts;
  4386. break;
  4387. case 1:
  4388. errmsg = "invalid start byte";
  4389. startinpos = s - starts;
  4390. endinpos = startinpos + 1;
  4391. break;
  4392. case 2:
  4393. if (consumed && (unsigned char)s[0] == 0xED && end - s == 2
  4394. && (unsigned char)s[1] >= 0xA0 && (unsigned char)s[1] <= 0xBF)
  4395. {
  4396. /* Truncated surrogate code in range D800-DFFF */
  4397. goto End;
  4398. }
  4399. /* fall through */
  4400. case 3:
  4401. case 4:
  4402. errmsg = "invalid continuation byte";
  4403. startinpos = s - starts;
  4404. endinpos = startinpos + ch - 1;
  4405. break;
  4406. default:
  4407. if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
  4408. goto onError;
  4409. continue;
  4410. }
  4411. if (error_handler == _Py_ERROR_UNKNOWN)
  4412. error_handler = _Py_GetErrorHandler(errors);
  4413. switch (error_handler) {
  4414. case _Py_ERROR_IGNORE:
  4415. s += (endinpos - startinpos);
  4416. break;
  4417. case _Py_ERROR_REPLACE:
  4418. if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
  4419. goto onError;
  4420. s += (endinpos - startinpos);
  4421. break;
  4422. case _Py_ERROR_SURROGATEESCAPE:
  4423. {
  4424. Py_ssize_t i;
  4425. if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
  4426. goto onError;
  4427. for (i=startinpos; i<endinpos; i++) {
  4428. ch = (Py_UCS4)(unsigned char)(starts[i]);
  4429. PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
  4430. ch + 0xdc00);
  4431. writer.pos++;
  4432. }
  4433. s += (endinpos - startinpos);
  4434. break;
  4435. }
  4436. default:
  4437. if (unicode_decode_call_errorhandler_writer(
  4438. errors, &error_handler_obj,
  4439. "utf-8", errmsg,
  4440. &starts, &end, &startinpos, &endinpos, &exc, &s,
  4441. &writer))
  4442. goto onError;
  4443. }
  4444. }
  4445. End:
  4446. if (consumed)
  4447. *consumed = s - starts;
  4448. Py_XDECREF(error_handler_obj);
  4449. Py_XDECREF(exc);
  4450. return _PyUnicodeWriter_Finish(&writer);
  4451. onError:
  4452. Py_XDECREF(error_handler_obj);
  4453. Py_XDECREF(exc);
  4454. _PyUnicodeWriter_Dealloc(&writer);
  4455. return NULL;
  4456. }
  4457. PyObject *
  4458. PyUnicode_DecodeUTF8Stateful(const char *s,
  4459. Py_ssize_t size,
  4460. const char *errors,
  4461. Py_ssize_t *consumed)
  4462. {
  4463. return unicode_decode_utf8(s, size, _Py_ERROR_UNKNOWN, errors, consumed);
  4464. }
  4465. /* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
  4466. non-zero, use strict error handler otherwise.
  4467. On success, write a pointer to a newly allocated wide character string into
  4468. *wstr (use PyMem_RawFree() to free the memory) and write the output length
  4469. (in number of wchar_t units) into *wlen (if wlen is set).
  4470. On memory allocation failure, return -1.
  4471. On decoding error (if surrogateescape is zero), return -2. If wlen is
  4472. non-NULL, write the start of the illegal byte sequence into *wlen. If reason
  4473. is not NULL, write the decoding error message into *reason. */
  4474. int
  4475. _Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
  4476. const char **reason, _Py_error_handler errors)
  4477. {
  4478. const char *orig_s = s;
  4479. const char *e;
  4480. wchar_t *unicode;
  4481. Py_ssize_t outpos;
  4482. int surrogateescape = 0;
  4483. int surrogatepass = 0;
  4484. switch (errors)
  4485. {
  4486. case _Py_ERROR_STRICT:
  4487. break;
  4488. case _Py_ERROR_SURROGATEESCAPE:
  4489. surrogateescape = 1;
  4490. break;
  4491. case _Py_ERROR_SURROGATEPASS:
  4492. surrogatepass = 1;
  4493. break;
  4494. default:
  4495. return -3;
  4496. }
  4497. /* Note: size will always be longer than the resulting Unicode
  4498. character count */
  4499. if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1 < size) {
  4500. return -1;
  4501. }
  4502. unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
  4503. if (!unicode) {
  4504. return -1;
  4505. }
  4506. /* Unpack UTF-8 encoded data */
  4507. e = s + size;
  4508. outpos = 0;
  4509. while (s < e) {
  4510. Py_UCS4 ch;
  4511. #if SIZEOF_WCHAR_T == 4
  4512. ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
  4513. #else
  4514. ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
  4515. #endif
  4516. if (ch > 0xFF) {
  4517. #if SIZEOF_WCHAR_T == 4
  4518. Py_UNREACHABLE();
  4519. #else
  4520. assert(ch > 0xFFFF && ch <= MAX_UNICODE);
  4521. /* write a surrogate pair */
  4522. unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
  4523. unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
  4524. #endif
  4525. }
  4526. else {
  4527. if (!ch && s == e) {
  4528. break;
  4529. }
  4530. if (surrogateescape) {
  4531. unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
  4532. }
  4533. else {
  4534. /* Is it a valid three-byte code? */
  4535. if (surrogatepass
  4536. && (e - s) >= 3
  4537. && (s[0] & 0xf0) == 0xe0
  4538. && (s[1] & 0xc0) == 0x80
  4539. && (s[2] & 0xc0) == 0x80)
  4540. {
  4541. ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
  4542. s += 3;
  4543. unicode[outpos++] = ch;
  4544. }
  4545. else {
  4546. PyMem_RawFree(unicode );
  4547. if (reason != NULL) {
  4548. switch (ch) {
  4549. case 0:
  4550. *reason = "unexpected end of data";
  4551. break;
  4552. case 1:
  4553. *reason = "invalid start byte";
  4554. break;
  4555. /* 2, 3, 4 */
  4556. default:
  4557. *reason = "invalid continuation byte";
  4558. break;
  4559. }
  4560. }
  4561. if (wlen != NULL) {
  4562. *wlen = s - orig_s;
  4563. }
  4564. return -2;
  4565. }
  4566. }
  4567. }
  4568. }
  4569. unicode[outpos] = L'\0';
  4570. if (wlen) {
  4571. *wlen = outpos;
  4572. }
  4573. *wstr = unicode;
  4574. return 0;
  4575. }
  4576. wchar_t*
  4577. _Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen,
  4578. size_t *wlen)
  4579. {
  4580. wchar_t *wstr;
  4581. int res = _Py_DecodeUTF8Ex(arg, arglen,
  4582. &wstr, wlen,
  4583. NULL, _Py_ERROR_SURROGATEESCAPE);
  4584. if (res != 0) {
  4585. /* _Py_DecodeUTF8Ex() must support _Py_ERROR_SURROGATEESCAPE */
  4586. assert(res != -3);
  4587. if (wlen) {
  4588. *wlen = (size_t)res;
  4589. }
  4590. return NULL;
  4591. }
  4592. return wstr;
  4593. }
  4594. /* UTF-8 encoder using the surrogateescape error handler .
  4595. On success, return 0 and write the newly allocated character string (use
  4596. PyMem_Free() to free the memory) into *str.
  4597. On encoding failure, return -2 and write the position of the invalid
  4598. surrogate character into *error_pos (if error_pos is set) and the decoding
  4599. error message into *reason (if reason is set).
  4600. On memory allocation failure, return -1. */
  4601. int
  4602. _Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
  4603. const char **reason, int raw_malloc, _Py_error_handler errors)
  4604. {
  4605. const Py_ssize_t max_char_size = 4;
  4606. Py_ssize_t len = wcslen(text);
  4607. assert(len >= 0);
  4608. int surrogateescape = 0;
  4609. int surrogatepass = 0;
  4610. switch (errors)
  4611. {
  4612. case _Py_ERROR_STRICT:
  4613. break;
  4614. case _Py_ERROR_SURROGATEESCAPE:
  4615. surrogateescape = 1;
  4616. break;
  4617. case _Py_ERROR_SURROGATEPASS:
  4618. surrogatepass = 1;
  4619. break;
  4620. default:
  4621. return -3;
  4622. }
  4623. if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
  4624. return -1;
  4625. }
  4626. char *bytes;
  4627. if (raw_malloc) {
  4628. bytes = PyMem_RawMalloc((len + 1) * max_char_size);
  4629. }
  4630. else {
  4631. bytes = PyMem_Malloc((len + 1) * max_char_size);
  4632. }
  4633. if (bytes == NULL) {
  4634. return -1;
  4635. }
  4636. char *p = bytes;
  4637. Py_ssize_t i;
  4638. for (i = 0; i < len; ) {
  4639. Py_ssize_t ch_pos = i;
  4640. Py_UCS4 ch = text[i];
  4641. i++;
  4642. #if Py_UNICODE_SIZE == 2
  4643. if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
  4644. && i < len
  4645. && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
  4646. {
  4647. ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
  4648. i++;
  4649. }
  4650. #endif
  4651. if (ch < 0x80) {
  4652. /* Encode ASCII */
  4653. *p++ = (char) ch;
  4654. }
  4655. else if (ch < 0x0800) {
  4656. /* Encode Latin-1 */
  4657. *p++ = (char)(0xc0 | (ch >> 6));
  4658. *p++ = (char)(0x80 | (ch & 0x3f));
  4659. }
  4660. else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
  4661. /* surrogateescape error handler */
  4662. if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
  4663. if (error_pos != NULL) {
  4664. *error_pos = (size_t)ch_pos;
  4665. }
  4666. if (reason != NULL) {
  4667. *reason = "encoding error";
  4668. }
  4669. if (raw_malloc) {
  4670. PyMem_RawFree(bytes);
  4671. }
  4672. else {
  4673. PyMem_Free(bytes);
  4674. }
  4675. return -2;
  4676. }
  4677. *p++ = (char)(ch & 0xff);
  4678. }
  4679. else if (ch < 0x10000) {
  4680. *p++ = (char)(0xe0 | (ch >> 12));
  4681. *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
  4682. *p++ = (char)(0x80 | (ch & 0x3f));
  4683. }
  4684. else { /* ch >= 0x10000 */
  4685. assert(ch <= MAX_UNICODE);
  4686. /* Encode UCS4 Unicode ordinals */
  4687. *p++ = (char)(0xf0 | (ch >> 18));
  4688. *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
  4689. *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
  4690. *p++ = (char)(0x80 | (ch & 0x3f));
  4691. }
  4692. }
  4693. *p++ = '\0';
  4694. size_t final_size = (p - bytes);
  4695. char *bytes2;
  4696. if (raw_malloc) {
  4697. bytes2 = PyMem_RawRealloc(bytes, final_size);
  4698. }
  4699. else {
  4700. bytes2 = PyMem_Realloc(bytes, final_size);
  4701. }
  4702. if (bytes2 == NULL) {
  4703. if (error_pos != NULL) {
  4704. *error_pos = (size_t)-1;
  4705. }
  4706. if (raw_malloc) {
  4707. PyMem_RawFree(bytes);
  4708. }
  4709. else {
  4710. PyMem_Free(bytes);
  4711. }
  4712. return -1;
  4713. }
  4714. *str = bytes2;
  4715. return 0;
  4716. }
  4717. /* Primary internal function which creates utf8 encoded bytes objects.
  4718. Allocation strategy: if the string is short, convert into a stack buffer
  4719. and allocate exactly as much space needed at the end. Else allocate the
  4720. maximum possible needed (4 result bytes per Unicode character), and return
  4721. the excess memory at the end.
  4722. */
  4723. static PyObject *
  4724. unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
  4725. const char *errors)
  4726. {
  4727. if (!PyUnicode_Check(unicode)) {
  4728. PyErr_BadArgument();
  4729. return NULL;
  4730. }
  4731. if (PyUnicode_UTF8(unicode))
  4732. return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
  4733. PyUnicode_UTF8_LENGTH(unicode));
  4734. int kind = PyUnicode_KIND(unicode);
  4735. const void *data = PyUnicode_DATA(unicode);
  4736. Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
  4737. _PyBytesWriter writer;
  4738. char *end;
  4739. switch (kind) {
  4740. default:
  4741. Py_UNREACHABLE();
  4742. case PyUnicode_1BYTE_KIND:
  4743. /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
  4744. assert(!PyUnicode_IS_ASCII(unicode));
  4745. end = ucs1lib_utf8_encoder(&writer, unicode, data, size, error_handler, errors);
  4746. break;
  4747. case PyUnicode_2BYTE_KIND:
  4748. end = ucs2lib_utf8_encoder(&writer, unicode, data, size, error_handler, errors);
  4749. break;
  4750. case PyUnicode_4BYTE_KIND:
  4751. end = ucs4lib_utf8_encoder(&writer, unicode, data, size, error_handler, errors);
  4752. break;
  4753. }
  4754. if (end == NULL) {
  4755. _PyBytesWriter_Dealloc(&writer);
  4756. return NULL;
  4757. }
  4758. return _PyBytesWriter_Finish(&writer, end);
  4759. }
  4760. static int
  4761. unicode_fill_utf8(PyObject *unicode)
  4762. {
  4763. /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
  4764. assert(!PyUnicode_IS_ASCII(unicode));
  4765. int kind = PyUnicode_KIND(unicode);
  4766. const void *data = PyUnicode_DATA(unicode);
  4767. Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
  4768. _PyBytesWriter writer;
  4769. char *end;
  4770. switch (kind) {
  4771. default:
  4772. Py_UNREACHABLE();
  4773. case PyUnicode_1BYTE_KIND:
  4774. end = ucs1lib_utf8_encoder(&writer, unicode, data, size,
  4775. _Py_ERROR_STRICT, NULL);
  4776. break;
  4777. case PyUnicode_2BYTE_KIND:
  4778. end = ucs2lib_utf8_encoder(&writer, unicode, data, size,
  4779. _Py_ERROR_STRICT, NULL);
  4780. break;
  4781. case PyUnicode_4BYTE_KIND:
  4782. end = ucs4lib_utf8_encoder(&writer, unicode, data, size,
  4783. _Py_ERROR_STRICT, NULL);
  4784. break;
  4785. }
  4786. if (end == NULL) {
  4787. _PyBytesWriter_Dealloc(&writer);
  4788. return -1;
  4789. }
  4790. const char *start = writer.use_small_buffer ? writer.small_buffer :
  4791. PyBytes_AS_STRING(writer.buffer);
  4792. Py_ssize_t len = end - start;
  4793. char *cache = PyObject_Malloc(len + 1);
  4794. if (cache == NULL) {
  4795. _PyBytesWriter_Dealloc(&writer);
  4796. PyErr_NoMemory();
  4797. return -1;
  4798. }
  4799. _PyUnicode_UTF8(unicode) = cache;
  4800. _PyUnicode_UTF8_LENGTH(unicode) = len;
  4801. memcpy(cache, start, len);
  4802. cache[len] = '\0';
  4803. _PyBytesWriter_Dealloc(&writer);
  4804. return 0;
  4805. }
  4806. PyObject *
  4807. _PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
  4808. {
  4809. return unicode_encode_utf8(unicode, _Py_ERROR_UNKNOWN, errors);
  4810. }
  4811. PyObject *
  4812. PyUnicode_AsUTF8String(PyObject *unicode)
  4813. {
  4814. return _PyUnicode_AsUTF8String(unicode, NULL);
  4815. }
  4816. /* --- UTF-32 Codec ------------------------------------------------------- */
  4817. PyObject *
  4818. PyUnicode_DecodeUTF32(const char *s,
  4819. Py_ssize_t size,
  4820. const char *errors,
  4821. int *byteorder)
  4822. {
  4823. return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
  4824. }
  4825. PyObject *
  4826. PyUnicode_DecodeUTF32Stateful(const char *s,
  4827. Py_ssize_t size,
  4828. const char *errors,
  4829. int *byteorder,
  4830. Py_ssize_t *consumed)
  4831. {
  4832. const char *starts = s;
  4833. Py_ssize_t startinpos;
  4834. Py_ssize_t endinpos;
  4835. _PyUnicodeWriter writer;
  4836. const unsigned char *q, *e;
  4837. int le, bo = 0; /* assume native ordering by default */
  4838. const char *encoding;
  4839. const char *errmsg = "";
  4840. PyObject *errorHandler = NULL;
  4841. PyObject *exc = NULL;
  4842. q = (const unsigned char *)s;
  4843. e = q + size;
  4844. if (byteorder)
  4845. bo = *byteorder;
  4846. /* Check for BOM marks (U+FEFF) in the input and adjust current
  4847. byte order setting accordingly. In native mode, the leading BOM
  4848. mark is skipped, in all other modes, it is copied to the output
  4849. stream as-is (giving a ZWNBSP character). */
  4850. if (bo == 0 && size >= 4) {
  4851. Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
  4852. if (bom == 0x0000FEFF) {
  4853. bo = -1;
  4854. q += 4;
  4855. }
  4856. else if (bom == 0xFFFE0000) {
  4857. bo = 1;
  4858. q += 4;
  4859. }
  4860. if (byteorder)
  4861. *byteorder = bo;
  4862. }
  4863. if (q == e) {
  4864. if (consumed)
  4865. *consumed = size;
  4866. _Py_RETURN_UNICODE_EMPTY();
  4867. }
  4868. #ifdef WORDS_BIGENDIAN
  4869. le = bo < 0;
  4870. #else
  4871. le = bo <= 0;
  4872. #endif
  4873. encoding = le ? "utf-32-le" : "utf-32-be";
  4874. _PyUnicodeWriter_Init(&writer);
  4875. writer.min_length = (e - q + 3) / 4;
  4876. if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
  4877. goto onError;
  4878. while (1) {
  4879. Py_UCS4 ch = 0;
  4880. Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
  4881. if (e - q >= 4) {
  4882. int kind = writer.kind;
  4883. void *data = writer.data;
  4884. const unsigned char *last = e - 4;
  4885. Py_ssize_t pos = writer.pos;
  4886. if (le) {
  4887. do {
  4888. ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
  4889. if (ch > maxch)
  4890. break;
  4891. if (kind != PyUnicode_1BYTE_KIND &&
  4892. Py_UNICODE_IS_SURROGATE(ch))
  4893. break;
  4894. PyUnicode_WRITE(kind, data, pos++, ch);
  4895. q += 4;
  4896. } while (q <= last);
  4897. }
  4898. else {
  4899. do {
  4900. ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
  4901. if (ch > maxch)
  4902. break;
  4903. if (kind != PyUnicode_1BYTE_KIND &&
  4904. Py_UNICODE_IS_SURROGATE(ch))
  4905. break;
  4906. PyUnicode_WRITE(kind, data, pos++, ch);
  4907. q += 4;
  4908. } while (q <= last);
  4909. }
  4910. writer.pos = pos;
  4911. }
  4912. if (Py_UNICODE_IS_SURROGATE(ch)) {
  4913. errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
  4914. startinpos = ((const char *)q) - starts;
  4915. endinpos = startinpos + 4;
  4916. }
  4917. else if (ch <= maxch) {
  4918. if (q == e || consumed)
  4919. break;
  4920. /* remaining bytes at the end? (size should be divisible by 4) */
  4921. errmsg = "truncated data";
  4922. startinpos = ((const char *)q) - starts;
  4923. endinpos = ((const char *)e) - starts;
  4924. }
  4925. else {
  4926. if (ch < 0x110000) {
  4927. if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
  4928. goto onError;
  4929. q += 4;
  4930. continue;
  4931. }
  4932. errmsg = "code point not in range(0x110000)";
  4933. startinpos = ((const char *)q) - starts;
  4934. endinpos = startinpos + 4;
  4935. }
  4936. /* The remaining input chars are ignored if the callback
  4937. chooses to skip the input */
  4938. if (unicode_decode_call_errorhandler_writer(
  4939. errors, &errorHandler,
  4940. encoding, errmsg,
  4941. &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
  4942. &writer))
  4943. goto onError;
  4944. }
  4945. if (consumed)
  4946. *consumed = (const char *)q-starts;
  4947. Py_XDECREF(errorHandler);
  4948. Py_XDECREF(exc);
  4949. return _PyUnicodeWriter_Finish(&writer);
  4950. onError:
  4951. _PyUnicodeWriter_Dealloc(&writer);
  4952. Py_XDECREF(errorHandler);
  4953. Py_XDECREF(exc);
  4954. return NULL;
  4955. }
  4956. PyObject *
  4957. _PyUnicode_EncodeUTF32(PyObject *str,
  4958. const char *errors,
  4959. int byteorder)
  4960. {
  4961. int kind;
  4962. const void *data;
  4963. Py_ssize_t len;
  4964. PyObject *v;
  4965. uint32_t *out;
  4966. #if PY_LITTLE_ENDIAN
  4967. int native_ordering = byteorder <= 0;
  4968. #else
  4969. int native_ordering = byteorder >= 0;
  4970. #endif
  4971. const char *encoding;
  4972. Py_ssize_t nsize, pos;
  4973. PyObject *errorHandler = NULL;
  4974. PyObject *exc = NULL;
  4975. PyObject *rep = NULL;
  4976. if (!PyUnicode_Check(str)) {
  4977. PyErr_BadArgument();
  4978. return NULL;
  4979. }
  4980. kind = PyUnicode_KIND(str);
  4981. data = PyUnicode_DATA(str);
  4982. len = PyUnicode_GET_LENGTH(str);
  4983. if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
  4984. return PyErr_NoMemory();
  4985. nsize = len + (byteorder == 0);
  4986. v = PyBytes_FromStringAndSize(NULL, nsize * 4);
  4987. if (v == NULL)
  4988. return NULL;
  4989. /* output buffer is 4-bytes aligned */
  4990. assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
  4991. out = (uint32_t *)PyBytes_AS_STRING(v);
  4992. if (byteorder == 0)
  4993. *out++ = 0xFEFF;
  4994. if (len == 0)
  4995. goto done;
  4996. if (byteorder == -1)
  4997. encoding = "utf-32-le";
  4998. else if (byteorder == 1)
  4999. encoding = "utf-32-be";
  5000. else
  5001. encoding = "utf-32";
  5002. if (kind == PyUnicode_1BYTE_KIND) {
  5003. ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
  5004. goto done;
  5005. }
  5006. pos = 0;
  5007. while (pos < len) {
  5008. Py_ssize_t newpos, repsize, moreunits;
  5009. if (kind == PyUnicode_2BYTE_KIND) {
  5010. pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
  5011. &out, native_ordering);
  5012. }
  5013. else {
  5014. assert(kind == PyUnicode_4BYTE_KIND);
  5015. pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
  5016. &out, native_ordering);
  5017. }
  5018. if (pos == len)
  5019. break;
  5020. rep = unicode_encode_call_errorhandler(
  5021. errors, &errorHandler,
  5022. encoding, "surrogates not allowed",
  5023. str, &exc, pos, pos + 1, &newpos);
  5024. if (!rep)
  5025. goto error;
  5026. if (PyBytes_Check(rep)) {
  5027. repsize = PyBytes_GET_SIZE(rep);
  5028. if (repsize & 3) {
  5029. raise_encode_exception(&exc, encoding,
  5030. str, pos, pos + 1,
  5031. "surrogates not allowed");
  5032. goto error;
  5033. }
  5034. moreunits = repsize / 4;
  5035. }
  5036. else {
  5037. assert(PyUnicode_Check(rep));
  5038. moreunits = repsize = PyUnicode_GET_LENGTH(rep);
  5039. if (!PyUnicode_IS_ASCII(rep)) {
  5040. raise_encode_exception(&exc, encoding,
  5041. str, pos, pos + 1,
  5042. "surrogates not allowed");
  5043. goto error;
  5044. }
  5045. }
  5046. moreunits += pos - newpos;
  5047. pos = newpos;
  5048. /* four bytes are reserved for each surrogate */
  5049. if (moreunits > 0) {
  5050. Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
  5051. if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
  5052. /* integer overflow */
  5053. PyErr_NoMemory();
  5054. goto error;
  5055. }
  5056. if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * moreunits) < 0)
  5057. goto error;
  5058. out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
  5059. }
  5060. if (PyBytes_Check(rep)) {
  5061. memcpy(out, PyBytes_AS_STRING(rep), repsize);
  5062. out += repsize / 4;
  5063. } else /* rep is unicode */ {
  5064. assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
  5065. ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
  5066. &out, native_ordering);
  5067. }
  5068. Py_CLEAR(rep);
  5069. }
  5070. /* Cut back to size actually needed. This is necessary for, for example,
  5071. encoding of a string containing isolated surrogates and the 'ignore'
  5072. handler is used. */
  5073. nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
  5074. if (nsize != PyBytes_GET_SIZE(v))
  5075. _PyBytes_Resize(&v, nsize);
  5076. Py_XDECREF(errorHandler);
  5077. Py_XDECREF(exc);
  5078. done:
  5079. return v;
  5080. error:
  5081. Py_XDECREF(rep);
  5082. Py_XDECREF(errorHandler);
  5083. Py_XDECREF(exc);
  5084. Py_XDECREF(v);
  5085. return NULL;
  5086. }
  5087. PyObject *
  5088. PyUnicode_AsUTF32String(PyObject *unicode)
  5089. {
  5090. return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
  5091. }
  5092. /* --- UTF-16 Codec ------------------------------------------------------- */
  5093. PyObject *
  5094. PyUnicode_DecodeUTF16(const char *s,
  5095. Py_ssize_t size,
  5096. const char *errors,
  5097. int *byteorder)
  5098. {
  5099. return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
  5100. }
  5101. PyObject *
  5102. PyUnicode_DecodeUTF16Stateful(const char *s,
  5103. Py_ssize_t size,
  5104. const char *errors,
  5105. int *byteorder,
  5106. Py_ssize_t *consumed)
  5107. {
  5108. const char *starts = s;
  5109. Py_ssize_t startinpos;
  5110. Py_ssize_t endinpos;
  5111. _PyUnicodeWriter writer;
  5112. const unsigned char *q, *e;
  5113. int bo = 0; /* assume native ordering by default */
  5114. int native_ordering;
  5115. const char *errmsg = "";
  5116. PyObject *errorHandler = NULL;
  5117. PyObject *exc = NULL;
  5118. const char *encoding;
  5119. q = (const unsigned char *)s;
  5120. e = q + size;
  5121. if (byteorder)
  5122. bo = *byteorder;
  5123. /* Check for BOM marks (U+FEFF) in the input and adjust current
  5124. byte order setting accordingly. In native mode, the leading BOM
  5125. mark is skipped, in all other modes, it is copied to the output
  5126. stream as-is (giving a ZWNBSP character). */
  5127. if (bo == 0 && size >= 2) {
  5128. const Py_UCS4 bom = (q[1] << 8) | q[0];
  5129. if (bom == 0xFEFF) {
  5130. q += 2;
  5131. bo = -1;
  5132. }
  5133. else if (bom == 0xFFFE) {
  5134. q += 2;
  5135. bo = 1;
  5136. }
  5137. if (byteorder)
  5138. *byteorder = bo;
  5139. }
  5140. if (q == e) {
  5141. if (consumed)
  5142. *consumed = size;
  5143. _Py_RETURN_UNICODE_EMPTY();
  5144. }
  5145. #if PY_LITTLE_ENDIAN
  5146. native_ordering = bo <= 0;
  5147. encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
  5148. #else
  5149. native_ordering = bo >= 0;
  5150. encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
  5151. #endif
  5152. /* Note: size will always be longer than the resulting Unicode
  5153. character count normally. Error handler will take care of
  5154. resizing when needed. */
  5155. _PyUnicodeWriter_Init(&writer);
  5156. writer.min_length = (e - q + 1) / 2;
  5157. if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
  5158. goto onError;
  5159. while (1) {
  5160. Py_UCS4 ch = 0;
  5161. if (e - q >= 2) {
  5162. int kind = writer.kind;
  5163. if (kind == PyUnicode_1BYTE_KIND) {
  5164. if (PyUnicode_IS_ASCII(writer.buffer))
  5165. ch = asciilib_utf16_decode(&q, e,
  5166. (Py_UCS1*)writer.data, &writer.pos,
  5167. native_ordering);
  5168. else
  5169. ch = ucs1lib_utf16_decode(&q, e,
  5170. (Py_UCS1*)writer.data, &writer.pos,
  5171. native_ordering);
  5172. } else if (kind == PyUnicode_2BYTE_KIND) {
  5173. ch = ucs2lib_utf16_decode(&q, e,
  5174. (Py_UCS2*)writer.data, &writer.pos,
  5175. native_ordering);
  5176. } else {
  5177. assert(kind == PyUnicode_4BYTE_KIND);
  5178. ch = ucs4lib_utf16_decode(&q, e,
  5179. (Py_UCS4*)writer.data, &writer.pos,
  5180. native_ordering);
  5181. }
  5182. }
  5183. switch (ch)
  5184. {
  5185. case 0:
  5186. /* remaining byte at the end? (size should be even) */
  5187. if (q == e || consumed)
  5188. goto End;
  5189. errmsg = "truncated data";
  5190. startinpos = ((const char *)q) - starts;
  5191. endinpos = ((const char *)e) - starts;
  5192. break;
  5193. /* The remaining input chars are ignored if the callback
  5194. chooses to skip the input */
  5195. case 1:
  5196. q -= 2;
  5197. if (consumed)
  5198. goto End;
  5199. errmsg = "unexpected end of data";
  5200. startinpos = ((const char *)q) - starts;
  5201. endinpos = ((const char *)e) - starts;
  5202. break;
  5203. case 2:
  5204. errmsg = "illegal encoding";
  5205. startinpos = ((const char *)q) - 2 - starts;
  5206. endinpos = startinpos + 2;
  5207. break;
  5208. case 3:
  5209. errmsg = "illegal UTF-16 surrogate";
  5210. startinpos = ((const char *)q) - 4 - starts;
  5211. endinpos = startinpos + 2;
  5212. break;
  5213. default:
  5214. if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
  5215. goto onError;
  5216. continue;
  5217. }
  5218. if (unicode_decode_call_errorhandler_writer(
  5219. errors,
  5220. &errorHandler,
  5221. encoding, errmsg,
  5222. &starts,
  5223. (const char **)&e,
  5224. &startinpos,
  5225. &endinpos,
  5226. &exc,
  5227. (const char **)&q,
  5228. &writer))
  5229. goto onError;
  5230. }
  5231. End:
  5232. if (consumed)
  5233. *consumed = (const char *)q-starts;
  5234. Py_XDECREF(errorHandler);
  5235. Py_XDECREF(exc);
  5236. return _PyUnicodeWriter_Finish(&writer);
  5237. onError:
  5238. _PyUnicodeWriter_Dealloc(&writer);
  5239. Py_XDECREF(errorHandler);
  5240. Py_XDECREF(exc);
  5241. return NULL;
  5242. }
  5243. PyObject *
  5244. _PyUnicode_EncodeUTF16(PyObject *str,
  5245. const char *errors,
  5246. int byteorder)
  5247. {
  5248. int kind;
  5249. const void *data;
  5250. Py_ssize_t len;
  5251. PyObject *v;
  5252. unsigned short *out;
  5253. Py_ssize_t pairs;
  5254. #if PY_BIG_ENDIAN
  5255. int native_ordering = byteorder >= 0;
  5256. #else
  5257. int native_ordering = byteorder <= 0;
  5258. #endif
  5259. const char *encoding;
  5260. Py_ssize_t nsize, pos;
  5261. PyObject *errorHandler = NULL;
  5262. PyObject *exc = NULL;
  5263. PyObject *rep = NULL;
  5264. if (!PyUnicode_Check(str)) {
  5265. PyErr_BadArgument();
  5266. return NULL;
  5267. }
  5268. kind = PyUnicode_KIND(str);
  5269. data = PyUnicode_DATA(str);
  5270. len = PyUnicode_GET_LENGTH(str);
  5271. pairs = 0;
  5272. if (kind == PyUnicode_4BYTE_KIND) {
  5273. const Py_UCS4 *in = (const Py_UCS4 *)data;
  5274. const Py_UCS4 *end = in + len;
  5275. while (in < end) {
  5276. if (*in++ >= 0x10000) {
  5277. pairs++;
  5278. }
  5279. }
  5280. }
  5281. if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
  5282. return PyErr_NoMemory();
  5283. }
  5284. nsize = len + pairs + (byteorder == 0);
  5285. v = PyBytes_FromStringAndSize(NULL, nsize * 2);
  5286. if (v == NULL) {
  5287. return NULL;
  5288. }
  5289. /* output buffer is 2-bytes aligned */
  5290. assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
  5291. out = (unsigned short *)PyBytes_AS_STRING(v);
  5292. if (byteorder == 0) {
  5293. *out++ = 0xFEFF;
  5294. }
  5295. if (len == 0) {
  5296. goto done;
  5297. }
  5298. if (kind == PyUnicode_1BYTE_KIND) {
  5299. ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
  5300. goto done;
  5301. }
  5302. if (byteorder < 0) {
  5303. encoding = "utf-16-le";
  5304. }
  5305. else if (byteorder > 0) {
  5306. encoding = "utf-16-be";
  5307. }
  5308. else {
  5309. encoding = "utf-16";
  5310. }
  5311. pos = 0;
  5312. while (pos < len) {
  5313. Py_ssize_t newpos, repsize, moreunits;
  5314. if (kind == PyUnicode_2BYTE_KIND) {
  5315. pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
  5316. &out, native_ordering);
  5317. }
  5318. else {
  5319. assert(kind == PyUnicode_4BYTE_KIND);
  5320. pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
  5321. &out, native_ordering);
  5322. }
  5323. if (pos == len)
  5324. break;
  5325. rep = unicode_encode_call_errorhandler(
  5326. errors, &errorHandler,
  5327. encoding, "surrogates not allowed",
  5328. str, &exc, pos, pos + 1, &newpos);
  5329. if (!rep)
  5330. goto error;
  5331. if (PyBytes_Check(rep)) {
  5332. repsize = PyBytes_GET_SIZE(rep);
  5333. if (repsize & 1) {
  5334. raise_encode_exception(&exc, encoding,
  5335. str, pos, pos + 1,
  5336. "surrogates not allowed");
  5337. goto error;
  5338. }
  5339. moreunits = repsize / 2;
  5340. }
  5341. else {
  5342. assert(PyUnicode_Check(rep));
  5343. moreunits = repsize = PyUnicode_GET_LENGTH(rep);
  5344. if (!PyUnicode_IS_ASCII(rep)) {
  5345. raise_encode_exception(&exc, encoding,
  5346. str, pos, pos + 1,
  5347. "surrogates not allowed");
  5348. goto error;
  5349. }
  5350. }
  5351. moreunits += pos - newpos;
  5352. pos = newpos;
  5353. /* two bytes are reserved for each surrogate */
  5354. if (moreunits > 0) {
  5355. Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
  5356. if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
  5357. /* integer overflow */
  5358. PyErr_NoMemory();
  5359. goto error;
  5360. }
  5361. if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * moreunits) < 0)
  5362. goto error;
  5363. out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
  5364. }
  5365. if (PyBytes_Check(rep)) {
  5366. memcpy(out, PyBytes_AS_STRING(rep), repsize);
  5367. out += repsize / 2;
  5368. } else /* rep is unicode */ {
  5369. assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
  5370. ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
  5371. &out, native_ordering);
  5372. }
  5373. Py_CLEAR(rep);
  5374. }
  5375. /* Cut back to size actually needed. This is necessary for, for example,
  5376. encoding of a string containing isolated surrogates and the 'ignore' handler
  5377. is used. */
  5378. nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
  5379. if (nsize != PyBytes_GET_SIZE(v))
  5380. _PyBytes_Resize(&v, nsize);
  5381. Py_XDECREF(errorHandler);
  5382. Py_XDECREF(exc);
  5383. done:
  5384. return v;
  5385. error:
  5386. Py_XDECREF(rep);
  5387. Py_XDECREF(errorHandler);
  5388. Py_XDECREF(exc);
  5389. Py_XDECREF(v);
  5390. return NULL;
  5391. #undef STORECHAR
  5392. }
  5393. PyObject *
  5394. PyUnicode_AsUTF16String(PyObject *unicode)
  5395. {
  5396. return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
  5397. }
  5398. /* --- Unicode Escape Codec ----------------------------------------------- */
  5399. PyObject *
  5400. _PyUnicode_DecodeUnicodeEscapeInternal(const char *s,
  5401. Py_ssize_t size,
  5402. const char *errors,
  5403. Py_ssize_t *consumed,
  5404. const char **first_invalid_escape)
  5405. {
  5406. const char *starts = s;
  5407. _PyUnicodeWriter writer;
  5408. const char *end;
  5409. PyObject *errorHandler = NULL;
  5410. PyObject *exc = NULL;
  5411. _PyUnicode_Name_CAPI *ucnhash_capi;
  5412. PyInterpreterState *interp = _PyInterpreterState_Get();
  5413. // so we can remember if we've seen an invalid escape char or not
  5414. *first_invalid_escape = NULL;
  5415. if (size == 0) {
  5416. if (consumed) {
  5417. *consumed = 0;
  5418. }
  5419. _Py_RETURN_UNICODE_EMPTY();
  5420. }
  5421. /* Escaped strings will always be longer than the resulting
  5422. Unicode string, so we start with size here and then reduce the
  5423. length after conversion to the true value.
  5424. (but if the error callback returns a long replacement string
  5425. we'll have to allocate more space) */
  5426. _PyUnicodeWriter_Init(&writer);
  5427. writer.min_length = size;
  5428. if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
  5429. goto onError;
  5430. }
  5431. end = s + size;
  5432. while (s < end) {
  5433. unsigned char c = (unsigned char) *s++;
  5434. Py_UCS4 ch;
  5435. int count;
  5436. const char *message;
  5437. #define WRITE_ASCII_CHAR(ch) \
  5438. do { \
  5439. assert(ch <= 127); \
  5440. assert(writer.pos < writer.size); \
  5441. PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
  5442. } while(0)
  5443. #define WRITE_CHAR(ch) \
  5444. do { \
  5445. if (ch <= writer.maxchar) { \
  5446. assert(writer.pos < writer.size); \
  5447. PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
  5448. } \
  5449. else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
  5450. goto onError; \
  5451. } \
  5452. } while(0)
  5453. /* Non-escape characters are interpreted as Unicode ordinals */
  5454. if (c != '\\') {
  5455. WRITE_CHAR(c);
  5456. continue;
  5457. }
  5458. Py_ssize_t startinpos = s - starts - 1;
  5459. /* \ - Escapes */
  5460. if (s >= end) {
  5461. message = "\\ at end of string";
  5462. goto incomplete;
  5463. }
  5464. c = (unsigned char) *s++;
  5465. assert(writer.pos < writer.size);
  5466. switch (c) {
  5467. /* \x escapes */
  5468. case '\n': continue;
  5469. case '\\': WRITE_ASCII_CHAR('\\'); continue;
  5470. case '\'': WRITE_ASCII_CHAR('\''); continue;
  5471. case '\"': WRITE_ASCII_CHAR('\"'); continue;
  5472. case 'b': WRITE_ASCII_CHAR('\b'); continue;
  5473. /* FF */
  5474. case 'f': WRITE_ASCII_CHAR('\014'); continue;
  5475. case 't': WRITE_ASCII_CHAR('\t'); continue;
  5476. case 'n': WRITE_ASCII_CHAR('\n'); continue;
  5477. case 'r': WRITE_ASCII_CHAR('\r'); continue;
  5478. /* VT */
  5479. case 'v': WRITE_ASCII_CHAR('\013'); continue;
  5480. /* BEL, not classic C */
  5481. case 'a': WRITE_ASCII_CHAR('\007'); continue;
  5482. /* \OOO (octal) escapes */
  5483. case '0': case '1': case '2': case '3':
  5484. case '4': case '5': case '6': case '7':
  5485. ch = c - '0';
  5486. if (s < end && '0' <= *s && *s <= '7') {
  5487. ch = (ch<<3) + *s++ - '0';
  5488. if (s < end && '0' <= *s && *s <= '7') {
  5489. ch = (ch<<3) + *s++ - '0';
  5490. }
  5491. }
  5492. if (ch > 0377) {
  5493. if (*first_invalid_escape == NULL) {
  5494. *first_invalid_escape = s-3; /* Back up 3 chars, since we've
  5495. already incremented s. */
  5496. }
  5497. }
  5498. WRITE_CHAR(ch);
  5499. continue;
  5500. /* hex escapes */
  5501. /* \xXX */
  5502. case 'x':
  5503. count = 2;
  5504. message = "truncated \\xXX escape";
  5505. goto hexescape;
  5506. /* \uXXXX */
  5507. case 'u':
  5508. count = 4;
  5509. message = "truncated \\uXXXX escape";
  5510. goto hexescape;
  5511. /* \UXXXXXXXX */
  5512. case 'U':
  5513. count = 8;
  5514. message = "truncated \\UXXXXXXXX escape";
  5515. hexescape:
  5516. for (ch = 0; count; ++s, --count) {
  5517. if (s >= end) {
  5518. goto incomplete;
  5519. }
  5520. c = (unsigned char)*s;
  5521. ch <<= 4;
  5522. if (c >= '0' && c <= '9') {
  5523. ch += c - '0';
  5524. }
  5525. else if (c >= 'a' && c <= 'f') {
  5526. ch += c - ('a' - 10);
  5527. }
  5528. else if (c >= 'A' && c <= 'F') {
  5529. ch += c - ('A' - 10);
  5530. }
  5531. else {
  5532. goto error;
  5533. }
  5534. }
  5535. /* when we get here, ch is a 32-bit unicode character */
  5536. if (ch > MAX_UNICODE) {
  5537. message = "illegal Unicode character";
  5538. goto error;
  5539. }
  5540. WRITE_CHAR(ch);
  5541. continue;
  5542. /* \N{name} */
  5543. case 'N':
  5544. ucnhash_capi = interp->unicode.ucnhash_capi;
  5545. if (ucnhash_capi == NULL) {
  5546. /* load the unicode data module */
  5547. ucnhash_capi = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
  5548. PyUnicodeData_CAPSULE_NAME, 1);
  5549. if (ucnhash_capi == NULL) {
  5550. PyErr_SetString(
  5551. PyExc_UnicodeError,
  5552. "\\N escapes not supported (can't load unicodedata module)"
  5553. );
  5554. goto onError;
  5555. }
  5556. interp->unicode.ucnhash_capi = ucnhash_capi;
  5557. }
  5558. message = "malformed \\N character escape";
  5559. if (s >= end) {
  5560. goto incomplete;
  5561. }
  5562. if (*s == '{') {
  5563. const char *start = ++s;
  5564. size_t namelen;
  5565. /* look for the closing brace */
  5566. while (s < end && *s != '}')
  5567. s++;
  5568. if (s >= end) {
  5569. goto incomplete;
  5570. }
  5571. namelen = s - start;
  5572. if (namelen) {
  5573. /* found a name. look it up in the unicode database */
  5574. s++;
  5575. ch = 0xffffffff; /* in case 'getcode' messes up */
  5576. if (namelen <= INT_MAX &&
  5577. ucnhash_capi->getcode(start, (int)namelen,
  5578. &ch, 0)) {
  5579. assert(ch <= MAX_UNICODE);
  5580. WRITE_CHAR(ch);
  5581. continue;
  5582. }
  5583. message = "unknown Unicode character name";
  5584. }
  5585. }
  5586. goto error;
  5587. default:
  5588. if (*first_invalid_escape == NULL) {
  5589. *first_invalid_escape = s-1; /* Back up one char, since we've
  5590. already incremented s. */
  5591. }
  5592. WRITE_ASCII_CHAR('\\');
  5593. WRITE_CHAR(c);
  5594. continue;
  5595. }
  5596. incomplete:
  5597. if (consumed) {
  5598. *consumed = startinpos;
  5599. break;
  5600. }
  5601. error:;
  5602. Py_ssize_t endinpos = s-starts;
  5603. writer.min_length = end - s + writer.pos;
  5604. if (unicode_decode_call_errorhandler_writer(
  5605. errors, &errorHandler,
  5606. "unicodeescape", message,
  5607. &starts, &end, &startinpos, &endinpos, &exc, &s,
  5608. &writer)) {
  5609. goto onError;
  5610. }
  5611. assert(end - s <= writer.size - writer.pos);
  5612. #undef WRITE_ASCII_CHAR
  5613. #undef WRITE_CHAR
  5614. }
  5615. Py_XDECREF(errorHandler);
  5616. Py_XDECREF(exc);
  5617. return _PyUnicodeWriter_Finish(&writer);
  5618. onError:
  5619. _PyUnicodeWriter_Dealloc(&writer);
  5620. Py_XDECREF(errorHandler);
  5621. Py_XDECREF(exc);
  5622. return NULL;
  5623. }
  5624. PyObject *
  5625. _PyUnicode_DecodeUnicodeEscapeStateful(const char *s,
  5626. Py_ssize_t size,
  5627. const char *errors,
  5628. Py_ssize_t *consumed)
  5629. {
  5630. const char *first_invalid_escape;
  5631. PyObject *result = _PyUnicode_DecodeUnicodeEscapeInternal(s, size, errors,
  5632. consumed,
  5633. &first_invalid_escape);
  5634. if (result == NULL)
  5635. return NULL;
  5636. if (first_invalid_escape != NULL) {
  5637. unsigned char c = *first_invalid_escape;
  5638. if ('4' <= c && c <= '7') {
  5639. if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
  5640. "invalid octal escape sequence '\\%.3s'",
  5641. first_invalid_escape) < 0)
  5642. {
  5643. Py_DECREF(result);
  5644. return NULL;
  5645. }
  5646. }
  5647. else {
  5648. if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
  5649. "invalid escape sequence '\\%c'",
  5650. c) < 0)
  5651. {
  5652. Py_DECREF(result);
  5653. return NULL;
  5654. }
  5655. }
  5656. }
  5657. return result;
  5658. }
  5659. PyObject *
  5660. PyUnicode_DecodeUnicodeEscape(const char *s,
  5661. Py_ssize_t size,
  5662. const char *errors)
  5663. {
  5664. return _PyUnicode_DecodeUnicodeEscapeStateful(s, size, errors, NULL);
  5665. }
  5666. /* Return a Unicode-Escape string version of the Unicode object. */
  5667. PyObject *
  5668. PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
  5669. {
  5670. Py_ssize_t i, len;
  5671. PyObject *repr;
  5672. char *p;
  5673. int kind;
  5674. const void *data;
  5675. Py_ssize_t expandsize;
  5676. /* Initial allocation is based on the longest-possible character
  5677. escape.
  5678. For UCS1 strings it's '\xxx', 4 bytes per source character.
  5679. For UCS2 strings it's '\uxxxx', 6 bytes per source character.
  5680. For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
  5681. */
  5682. if (!PyUnicode_Check(unicode)) {
  5683. PyErr_BadArgument();
  5684. return NULL;
  5685. }
  5686. len = PyUnicode_GET_LENGTH(unicode);
  5687. if (len == 0) {
  5688. return PyBytes_FromStringAndSize(NULL, 0);
  5689. }
  5690. kind = PyUnicode_KIND(unicode);
  5691. data = PyUnicode_DATA(unicode);
  5692. /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
  5693. bytes, and 1 byte characters 4. */
  5694. expandsize = kind * 2 + 2;
  5695. if (len > PY_SSIZE_T_MAX / expandsize) {
  5696. return PyErr_NoMemory();
  5697. }
  5698. repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
  5699. if (repr == NULL) {
  5700. return NULL;
  5701. }
  5702. p = PyBytes_AS_STRING(repr);
  5703. for (i = 0; i < len; i++) {
  5704. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  5705. /* U+0000-U+00ff range */
  5706. if (ch < 0x100) {
  5707. if (ch >= ' ' && ch < 127) {
  5708. if (ch != '\\') {
  5709. /* Copy printable US ASCII as-is */
  5710. *p++ = (char) ch;
  5711. }
  5712. /* Escape backslashes */
  5713. else {
  5714. *p++ = '\\';
  5715. *p++ = '\\';
  5716. }
  5717. }
  5718. /* Map special whitespace to '\t', \n', '\r' */
  5719. else if (ch == '\t') {
  5720. *p++ = '\\';
  5721. *p++ = 't';
  5722. }
  5723. else if (ch == '\n') {
  5724. *p++ = '\\';
  5725. *p++ = 'n';
  5726. }
  5727. else if (ch == '\r') {
  5728. *p++ = '\\';
  5729. *p++ = 'r';
  5730. }
  5731. /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
  5732. else {
  5733. *p++ = '\\';
  5734. *p++ = 'x';
  5735. *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
  5736. *p++ = Py_hexdigits[ch & 0x000F];
  5737. }
  5738. }
  5739. /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
  5740. else if (ch < 0x10000) {
  5741. *p++ = '\\';
  5742. *p++ = 'u';
  5743. *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
  5744. *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
  5745. *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
  5746. *p++ = Py_hexdigits[ch & 0x000F];
  5747. }
  5748. /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
  5749. else {
  5750. /* Make sure that the first two digits are zero */
  5751. assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
  5752. *p++ = '\\';
  5753. *p++ = 'U';
  5754. *p++ = '0';
  5755. *p++ = '0';
  5756. *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
  5757. *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
  5758. *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
  5759. *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
  5760. *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
  5761. *p++ = Py_hexdigits[ch & 0x0000000F];
  5762. }
  5763. }
  5764. assert(p - PyBytes_AS_STRING(repr) > 0);
  5765. if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
  5766. return NULL;
  5767. }
  5768. return repr;
  5769. }
  5770. /* --- Raw Unicode Escape Codec ------------------------------------------- */
  5771. PyObject *
  5772. _PyUnicode_DecodeRawUnicodeEscapeStateful(const char *s,
  5773. Py_ssize_t size,
  5774. const char *errors,
  5775. Py_ssize_t *consumed)
  5776. {
  5777. const char *starts = s;
  5778. _PyUnicodeWriter writer;
  5779. const char *end;
  5780. PyObject *errorHandler = NULL;
  5781. PyObject *exc = NULL;
  5782. if (size == 0) {
  5783. if (consumed) {
  5784. *consumed = 0;
  5785. }
  5786. _Py_RETURN_UNICODE_EMPTY();
  5787. }
  5788. /* Escaped strings will always be longer than the resulting
  5789. Unicode string, so we start with size here and then reduce the
  5790. length after conversion to the true value. (But decoding error
  5791. handler might have to resize the string) */
  5792. _PyUnicodeWriter_Init(&writer);
  5793. writer.min_length = size;
  5794. if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
  5795. goto onError;
  5796. }
  5797. end = s + size;
  5798. while (s < end) {
  5799. unsigned char c = (unsigned char) *s++;
  5800. Py_UCS4 ch;
  5801. int count;
  5802. const char *message;
  5803. #define WRITE_CHAR(ch) \
  5804. do { \
  5805. if (ch <= writer.maxchar) { \
  5806. assert(writer.pos < writer.size); \
  5807. PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
  5808. } \
  5809. else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
  5810. goto onError; \
  5811. } \
  5812. } while(0)
  5813. /* Non-escape characters are interpreted as Unicode ordinals */
  5814. if (c != '\\' || (s >= end && !consumed)) {
  5815. WRITE_CHAR(c);
  5816. continue;
  5817. }
  5818. Py_ssize_t startinpos = s - starts - 1;
  5819. /* \ - Escapes */
  5820. if (s >= end) {
  5821. assert(consumed);
  5822. // Set message to silent compiler warning.
  5823. // Actually it is never used.
  5824. message = "\\ at end of string";
  5825. goto incomplete;
  5826. }
  5827. c = (unsigned char) *s++;
  5828. if (c == 'u') {
  5829. count = 4;
  5830. message = "truncated \\uXXXX escape";
  5831. }
  5832. else if (c == 'U') {
  5833. count = 8;
  5834. message = "truncated \\UXXXXXXXX escape";
  5835. }
  5836. else {
  5837. assert(writer.pos < writer.size);
  5838. PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
  5839. WRITE_CHAR(c);
  5840. continue;
  5841. }
  5842. /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
  5843. for (ch = 0; count; ++s, --count) {
  5844. if (s >= end) {
  5845. goto incomplete;
  5846. }
  5847. c = (unsigned char)*s;
  5848. ch <<= 4;
  5849. if (c >= '0' && c <= '9') {
  5850. ch += c - '0';
  5851. }
  5852. else if (c >= 'a' && c <= 'f') {
  5853. ch += c - ('a' - 10);
  5854. }
  5855. else if (c >= 'A' && c <= 'F') {
  5856. ch += c - ('A' - 10);
  5857. }
  5858. else {
  5859. goto error;
  5860. }
  5861. }
  5862. if (ch > MAX_UNICODE) {
  5863. message = "\\Uxxxxxxxx out of range";
  5864. goto error;
  5865. }
  5866. WRITE_CHAR(ch);
  5867. continue;
  5868. incomplete:
  5869. if (consumed) {
  5870. *consumed = startinpos;
  5871. break;
  5872. }
  5873. error:;
  5874. Py_ssize_t endinpos = s-starts;
  5875. writer.min_length = end - s + writer.pos;
  5876. if (unicode_decode_call_errorhandler_writer(
  5877. errors, &errorHandler,
  5878. "rawunicodeescape", message,
  5879. &starts, &end, &startinpos, &endinpos, &exc, &s,
  5880. &writer)) {
  5881. goto onError;
  5882. }
  5883. assert(end - s <= writer.size - writer.pos);
  5884. #undef WRITE_CHAR
  5885. }
  5886. Py_XDECREF(errorHandler);
  5887. Py_XDECREF(exc);
  5888. return _PyUnicodeWriter_Finish(&writer);
  5889. onError:
  5890. _PyUnicodeWriter_Dealloc(&writer);
  5891. Py_XDECREF(errorHandler);
  5892. Py_XDECREF(exc);
  5893. return NULL;
  5894. }
  5895. PyObject *
  5896. PyUnicode_DecodeRawUnicodeEscape(const char *s,
  5897. Py_ssize_t size,
  5898. const char *errors)
  5899. {
  5900. return _PyUnicode_DecodeRawUnicodeEscapeStateful(s, size, errors, NULL);
  5901. }
  5902. PyObject *
  5903. PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
  5904. {
  5905. PyObject *repr;
  5906. char *p;
  5907. Py_ssize_t expandsize, pos;
  5908. int kind;
  5909. const void *data;
  5910. Py_ssize_t len;
  5911. if (!PyUnicode_Check(unicode)) {
  5912. PyErr_BadArgument();
  5913. return NULL;
  5914. }
  5915. kind = PyUnicode_KIND(unicode);
  5916. data = PyUnicode_DATA(unicode);
  5917. len = PyUnicode_GET_LENGTH(unicode);
  5918. if (kind == PyUnicode_1BYTE_KIND) {
  5919. return PyBytes_FromStringAndSize(data, len);
  5920. }
  5921. /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
  5922. bytes, and 1 byte characters 4. */
  5923. expandsize = kind * 2 + 2;
  5924. if (len > PY_SSIZE_T_MAX / expandsize) {
  5925. return PyErr_NoMemory();
  5926. }
  5927. repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
  5928. if (repr == NULL) {
  5929. return NULL;
  5930. }
  5931. if (len == 0) {
  5932. return repr;
  5933. }
  5934. p = PyBytes_AS_STRING(repr);
  5935. for (pos = 0; pos < len; pos++) {
  5936. Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
  5937. /* U+0000-U+00ff range: Copy 8-bit characters as-is */
  5938. if (ch < 0x100) {
  5939. *p++ = (char) ch;
  5940. }
  5941. /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
  5942. else if (ch < 0x10000) {
  5943. *p++ = '\\';
  5944. *p++ = 'u';
  5945. *p++ = Py_hexdigits[(ch >> 12) & 0xf];
  5946. *p++ = Py_hexdigits[(ch >> 8) & 0xf];
  5947. *p++ = Py_hexdigits[(ch >> 4) & 0xf];
  5948. *p++ = Py_hexdigits[ch & 15];
  5949. }
  5950. /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
  5951. else {
  5952. assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
  5953. *p++ = '\\';
  5954. *p++ = 'U';
  5955. *p++ = '0';
  5956. *p++ = '0';
  5957. *p++ = Py_hexdigits[(ch >> 20) & 0xf];
  5958. *p++ = Py_hexdigits[(ch >> 16) & 0xf];
  5959. *p++ = Py_hexdigits[(ch >> 12) & 0xf];
  5960. *p++ = Py_hexdigits[(ch >> 8) & 0xf];
  5961. *p++ = Py_hexdigits[(ch >> 4) & 0xf];
  5962. *p++ = Py_hexdigits[ch & 15];
  5963. }
  5964. }
  5965. assert(p > PyBytes_AS_STRING(repr));
  5966. if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
  5967. return NULL;
  5968. }
  5969. return repr;
  5970. }
  5971. /* --- Latin-1 Codec ------------------------------------------------------ */
  5972. PyObject *
  5973. PyUnicode_DecodeLatin1(const char *s,
  5974. Py_ssize_t size,
  5975. const char *errors)
  5976. {
  5977. /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
  5978. return _PyUnicode_FromUCS1((const unsigned char*)s, size);
  5979. }
  5980. /* create or adjust a UnicodeEncodeError */
  5981. static void
  5982. make_encode_exception(PyObject **exceptionObject,
  5983. const char *encoding,
  5984. PyObject *unicode,
  5985. Py_ssize_t startpos, Py_ssize_t endpos,
  5986. const char *reason)
  5987. {
  5988. if (*exceptionObject == NULL) {
  5989. *exceptionObject = PyObject_CallFunction(
  5990. PyExc_UnicodeEncodeError, "sOnns",
  5991. encoding, unicode, startpos, endpos, reason);
  5992. }
  5993. else {
  5994. if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
  5995. goto onError;
  5996. if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
  5997. goto onError;
  5998. if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
  5999. goto onError;
  6000. return;
  6001. onError:
  6002. Py_CLEAR(*exceptionObject);
  6003. }
  6004. }
  6005. /* raises a UnicodeEncodeError */
  6006. static void
  6007. raise_encode_exception(PyObject **exceptionObject,
  6008. const char *encoding,
  6009. PyObject *unicode,
  6010. Py_ssize_t startpos, Py_ssize_t endpos,
  6011. const char *reason)
  6012. {
  6013. make_encode_exception(exceptionObject,
  6014. encoding, unicode, startpos, endpos, reason);
  6015. if (*exceptionObject != NULL)
  6016. PyCodec_StrictErrors(*exceptionObject);
  6017. }
  6018. /* error handling callback helper:
  6019. build arguments, call the callback and check the arguments,
  6020. put the result into newpos and return the replacement string, which
  6021. has to be freed by the caller */
  6022. static PyObject *
  6023. unicode_encode_call_errorhandler(const char *errors,
  6024. PyObject **errorHandler,
  6025. const char *encoding, const char *reason,
  6026. PyObject *unicode, PyObject **exceptionObject,
  6027. Py_ssize_t startpos, Py_ssize_t endpos,
  6028. Py_ssize_t *newpos)
  6029. {
  6030. static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
  6031. Py_ssize_t len;
  6032. PyObject *restuple;
  6033. PyObject *resunicode;
  6034. if (*errorHandler == NULL) {
  6035. *errorHandler = PyCodec_LookupError(errors);
  6036. if (*errorHandler == NULL)
  6037. return NULL;
  6038. }
  6039. len = PyUnicode_GET_LENGTH(unicode);
  6040. make_encode_exception(exceptionObject,
  6041. encoding, unicode, startpos, endpos, reason);
  6042. if (*exceptionObject == NULL)
  6043. return NULL;
  6044. restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
  6045. if (restuple == NULL)
  6046. return NULL;
  6047. if (!PyTuple_Check(restuple)) {
  6048. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  6049. Py_DECREF(restuple);
  6050. return NULL;
  6051. }
  6052. if (!PyArg_ParseTuple(restuple, argparse,
  6053. &resunicode, newpos)) {
  6054. Py_DECREF(restuple);
  6055. return NULL;
  6056. }
  6057. if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
  6058. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  6059. Py_DECREF(restuple);
  6060. return NULL;
  6061. }
  6062. if (*newpos<0)
  6063. *newpos = len + *newpos;
  6064. if (*newpos<0 || *newpos>len) {
  6065. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
  6066. Py_DECREF(restuple);
  6067. return NULL;
  6068. }
  6069. Py_INCREF(resunicode);
  6070. Py_DECREF(restuple);
  6071. return resunicode;
  6072. }
  6073. static PyObject *
  6074. unicode_encode_ucs1(PyObject *unicode,
  6075. const char *errors,
  6076. const Py_UCS4 limit)
  6077. {
  6078. /* input state */
  6079. Py_ssize_t pos=0, size;
  6080. int kind;
  6081. const void *data;
  6082. /* pointer into the output */
  6083. char *str;
  6084. const char *encoding = (limit == 256) ? "latin-1" : "ascii";
  6085. const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
  6086. PyObject *error_handler_obj = NULL;
  6087. PyObject *exc = NULL;
  6088. _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
  6089. PyObject *rep = NULL;
  6090. /* output object */
  6091. _PyBytesWriter writer;
  6092. size = PyUnicode_GET_LENGTH(unicode);
  6093. kind = PyUnicode_KIND(unicode);
  6094. data = PyUnicode_DATA(unicode);
  6095. /* allocate enough for a simple encoding without
  6096. replacements, if we need more, we'll resize */
  6097. if (size == 0)
  6098. return PyBytes_FromStringAndSize(NULL, 0);
  6099. _PyBytesWriter_Init(&writer);
  6100. str = _PyBytesWriter_Alloc(&writer, size);
  6101. if (str == NULL)
  6102. return NULL;
  6103. while (pos < size) {
  6104. Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
  6105. /* can we encode this? */
  6106. if (ch < limit) {
  6107. /* no overflow check, because we know that the space is enough */
  6108. *str++ = (char)ch;
  6109. ++pos;
  6110. }
  6111. else {
  6112. Py_ssize_t newpos, i;
  6113. /* startpos for collecting unencodable chars */
  6114. Py_ssize_t collstart = pos;
  6115. Py_ssize_t collend = collstart + 1;
  6116. /* find all unecodable characters */
  6117. while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
  6118. ++collend;
  6119. /* Only overallocate the buffer if it's not the last write */
  6120. writer.overallocate = (collend < size);
  6121. /* cache callback name lookup (if not done yet, i.e. it's the first error) */
  6122. if (error_handler == _Py_ERROR_UNKNOWN)
  6123. error_handler = _Py_GetErrorHandler(errors);
  6124. switch (error_handler) {
  6125. case _Py_ERROR_STRICT:
  6126. raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
  6127. goto onError;
  6128. case _Py_ERROR_REPLACE:
  6129. memset(str, '?', collend - collstart);
  6130. str += (collend - collstart);
  6131. /* fall through */
  6132. case _Py_ERROR_IGNORE:
  6133. pos = collend;
  6134. break;
  6135. case _Py_ERROR_BACKSLASHREPLACE:
  6136. /* subtract preallocated bytes */
  6137. writer.min_size -= (collend - collstart);
  6138. str = backslashreplace(&writer, str,
  6139. unicode, collstart, collend);
  6140. if (str == NULL)
  6141. goto onError;
  6142. pos = collend;
  6143. break;
  6144. case _Py_ERROR_XMLCHARREFREPLACE:
  6145. /* subtract preallocated bytes */
  6146. writer.min_size -= (collend - collstart);
  6147. str = xmlcharrefreplace(&writer, str,
  6148. unicode, collstart, collend);
  6149. if (str == NULL)
  6150. goto onError;
  6151. pos = collend;
  6152. break;
  6153. case _Py_ERROR_SURROGATEESCAPE:
  6154. for (i = collstart; i < collend; ++i) {
  6155. ch = PyUnicode_READ(kind, data, i);
  6156. if (ch < 0xdc80 || 0xdcff < ch) {
  6157. /* Not a UTF-8b surrogate */
  6158. break;
  6159. }
  6160. *str++ = (char)(ch - 0xdc00);
  6161. ++pos;
  6162. }
  6163. if (i >= collend)
  6164. break;
  6165. collstart = pos;
  6166. assert(collstart != collend);
  6167. /* fall through */
  6168. default:
  6169. rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
  6170. encoding, reason, unicode, &exc,
  6171. collstart, collend, &newpos);
  6172. if (rep == NULL)
  6173. goto onError;
  6174. if (newpos < collstart) {
  6175. writer.overallocate = 1;
  6176. str = _PyBytesWriter_Prepare(&writer, str,
  6177. collstart - newpos);
  6178. if (str == NULL)
  6179. goto onError;
  6180. }
  6181. else {
  6182. /* subtract preallocated bytes */
  6183. writer.min_size -= newpos - collstart;
  6184. /* Only overallocate the buffer if it's not the last write */
  6185. writer.overallocate = (newpos < size);
  6186. }
  6187. if (PyBytes_Check(rep)) {
  6188. /* Directly copy bytes result to output. */
  6189. str = _PyBytesWriter_WriteBytes(&writer, str,
  6190. PyBytes_AS_STRING(rep),
  6191. PyBytes_GET_SIZE(rep));
  6192. }
  6193. else {
  6194. assert(PyUnicode_Check(rep));
  6195. if (limit == 256 ?
  6196. PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
  6197. !PyUnicode_IS_ASCII(rep))
  6198. {
  6199. /* Not all characters are smaller than limit */
  6200. raise_encode_exception(&exc, encoding, unicode,
  6201. collstart, collend, reason);
  6202. goto onError;
  6203. }
  6204. assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
  6205. str = _PyBytesWriter_WriteBytes(&writer, str,
  6206. PyUnicode_DATA(rep),
  6207. PyUnicode_GET_LENGTH(rep));
  6208. }
  6209. if (str == NULL)
  6210. goto onError;
  6211. pos = newpos;
  6212. Py_CLEAR(rep);
  6213. }
  6214. /* If overallocation was disabled, ensure that it was the last
  6215. write. Otherwise, we missed an optimization */
  6216. assert(writer.overallocate || pos == size);
  6217. }
  6218. }
  6219. Py_XDECREF(error_handler_obj);
  6220. Py_XDECREF(exc);
  6221. return _PyBytesWriter_Finish(&writer, str);
  6222. onError:
  6223. Py_XDECREF(rep);
  6224. _PyBytesWriter_Dealloc(&writer);
  6225. Py_XDECREF(error_handler_obj);
  6226. Py_XDECREF(exc);
  6227. return NULL;
  6228. }
  6229. PyObject *
  6230. _PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
  6231. {
  6232. if (!PyUnicode_Check(unicode)) {
  6233. PyErr_BadArgument();
  6234. return NULL;
  6235. }
  6236. /* Fast path: if it is a one-byte string, construct
  6237. bytes object directly. */
  6238. if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
  6239. return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
  6240. PyUnicode_GET_LENGTH(unicode));
  6241. /* Non-Latin-1 characters present. Defer to above function to
  6242. raise the exception. */
  6243. return unicode_encode_ucs1(unicode, errors, 256);
  6244. }
  6245. PyObject*
  6246. PyUnicode_AsLatin1String(PyObject *unicode)
  6247. {
  6248. return _PyUnicode_AsLatin1String(unicode, NULL);
  6249. }
  6250. /* --- 7-bit ASCII Codec -------------------------------------------------- */
  6251. PyObject *
  6252. PyUnicode_DecodeASCII(const char *s,
  6253. Py_ssize_t size,
  6254. const char *errors)
  6255. {
  6256. const char *starts = s;
  6257. const char *e = s + size;
  6258. PyObject *error_handler_obj = NULL;
  6259. PyObject *exc = NULL;
  6260. _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
  6261. if (size == 0)
  6262. _Py_RETURN_UNICODE_EMPTY();
  6263. /* ASCII is equivalent to the first 128 ordinals in Unicode. */
  6264. if (size == 1 && (unsigned char)s[0] < 128) {
  6265. return get_latin1_char((unsigned char)s[0]);
  6266. }
  6267. // Shortcut for simple case
  6268. PyObject *u = PyUnicode_New(size, 127);
  6269. if (u == NULL) {
  6270. return NULL;
  6271. }
  6272. Py_ssize_t outpos = ascii_decode(s, e, PyUnicode_1BYTE_DATA(u));
  6273. if (outpos == size) {
  6274. return u;
  6275. }
  6276. _PyUnicodeWriter writer;
  6277. _PyUnicodeWriter_InitWithBuffer(&writer, u);
  6278. writer.pos = outpos;
  6279. s += outpos;
  6280. int kind = writer.kind;
  6281. void *data = writer.data;
  6282. Py_ssize_t startinpos, endinpos;
  6283. while (s < e) {
  6284. unsigned char c = (unsigned char)*s;
  6285. if (c < 128) {
  6286. PyUnicode_WRITE(kind, data, writer.pos, c);
  6287. writer.pos++;
  6288. ++s;
  6289. continue;
  6290. }
  6291. /* byte outsize range 0x00..0x7f: call the error handler */
  6292. if (error_handler == _Py_ERROR_UNKNOWN)
  6293. error_handler = _Py_GetErrorHandler(errors);
  6294. switch (error_handler)
  6295. {
  6296. case _Py_ERROR_REPLACE:
  6297. case _Py_ERROR_SURROGATEESCAPE:
  6298. /* Fast-path: the error handler only writes one character,
  6299. but we may switch to UCS2 at the first write */
  6300. if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
  6301. goto onError;
  6302. kind = writer.kind;
  6303. data = writer.data;
  6304. if (error_handler == _Py_ERROR_REPLACE)
  6305. PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
  6306. else
  6307. PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
  6308. writer.pos++;
  6309. ++s;
  6310. break;
  6311. case _Py_ERROR_IGNORE:
  6312. ++s;
  6313. break;
  6314. default:
  6315. startinpos = s-starts;
  6316. endinpos = startinpos + 1;
  6317. if (unicode_decode_call_errorhandler_writer(
  6318. errors, &error_handler_obj,
  6319. "ascii", "ordinal not in range(128)",
  6320. &starts, &e, &startinpos, &endinpos, &exc, &s,
  6321. &writer))
  6322. goto onError;
  6323. kind = writer.kind;
  6324. data = writer.data;
  6325. }
  6326. }
  6327. Py_XDECREF(error_handler_obj);
  6328. Py_XDECREF(exc);
  6329. return _PyUnicodeWriter_Finish(&writer);
  6330. onError:
  6331. _PyUnicodeWriter_Dealloc(&writer);
  6332. Py_XDECREF(error_handler_obj);
  6333. Py_XDECREF(exc);
  6334. return NULL;
  6335. }
  6336. PyObject *
  6337. _PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
  6338. {
  6339. if (!PyUnicode_Check(unicode)) {
  6340. PyErr_BadArgument();
  6341. return NULL;
  6342. }
  6343. /* Fast path: if it is an ASCII-only string, construct bytes object
  6344. directly. Else defer to above function to raise the exception. */
  6345. if (PyUnicode_IS_ASCII(unicode))
  6346. return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
  6347. PyUnicode_GET_LENGTH(unicode));
  6348. return unicode_encode_ucs1(unicode, errors, 128);
  6349. }
  6350. PyObject *
  6351. PyUnicode_AsASCIIString(PyObject *unicode)
  6352. {
  6353. return _PyUnicode_AsASCIIString(unicode, NULL);
  6354. }
  6355. #ifdef MS_WINDOWS
  6356. /* --- MBCS codecs for Windows -------------------------------------------- */
  6357. #if SIZEOF_INT < SIZEOF_SIZE_T
  6358. #define NEED_RETRY
  6359. #endif
  6360. /* INT_MAX is the theoretical largest chunk (or INT_MAX / 2 when
  6361. transcoding from UTF-16), but INT_MAX / 4 performs better in
  6362. both cases also and avoids partial characters overrunning the
  6363. length limit in MultiByteToWideChar on Windows */
  6364. #define DECODING_CHUNK_SIZE (INT_MAX/4)
  6365. #ifndef WC_ERR_INVALID_CHARS
  6366. # define WC_ERR_INVALID_CHARS 0x0080
  6367. #endif
  6368. static const char*
  6369. code_page_name(UINT code_page, PyObject **obj)
  6370. {
  6371. *obj = NULL;
  6372. if (code_page == CP_ACP)
  6373. return "mbcs";
  6374. if (code_page == CP_UTF7)
  6375. return "CP_UTF7";
  6376. if (code_page == CP_UTF8)
  6377. return "CP_UTF8";
  6378. *obj = PyBytes_FromFormat("cp%u", code_page);
  6379. if (*obj == NULL)
  6380. return NULL;
  6381. return PyBytes_AS_STRING(*obj);
  6382. }
  6383. static DWORD
  6384. decode_code_page_flags(UINT code_page)
  6385. {
  6386. if (code_page == CP_UTF7) {
  6387. /* The CP_UTF7 decoder only supports flags=0 */
  6388. return 0;
  6389. }
  6390. else
  6391. return MB_ERR_INVALID_CHARS;
  6392. }
  6393. /*
  6394. * Decode a byte string from a Windows code page into unicode object in strict
  6395. * mode.
  6396. *
  6397. * Returns consumed size if succeed, returns -2 on decode error, or raise an
  6398. * OSError and returns -1 on other error.
  6399. */
  6400. static int
  6401. decode_code_page_strict(UINT code_page,
  6402. wchar_t **buf,
  6403. Py_ssize_t *bufsize,
  6404. const char *in,
  6405. int insize)
  6406. {
  6407. DWORD flags = MB_ERR_INVALID_CHARS;
  6408. wchar_t *out;
  6409. DWORD outsize;
  6410. /* First get the size of the result */
  6411. assert(insize > 0);
  6412. while ((outsize = MultiByteToWideChar(code_page, flags,
  6413. in, insize, NULL, 0)) <= 0)
  6414. {
  6415. if (!flags || GetLastError() != ERROR_INVALID_FLAGS) {
  6416. goto error;
  6417. }
  6418. /* For some code pages (e.g. UTF-7) flags must be set to 0. */
  6419. flags = 0;
  6420. }
  6421. /* Extend a wchar_t* buffer */
  6422. Py_ssize_t n = *bufsize; /* Get the current length */
  6423. if (widechar_resize(buf, bufsize, n + outsize) < 0) {
  6424. return -1;
  6425. }
  6426. out = *buf + n;
  6427. /* Do the conversion */
  6428. outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
  6429. if (outsize <= 0)
  6430. goto error;
  6431. return insize;
  6432. error:
  6433. if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
  6434. return -2;
  6435. PyErr_SetFromWindowsErr(0);
  6436. return -1;
  6437. }
  6438. /*
  6439. * Decode a byte string from a code page into unicode object with an error
  6440. * handler.
  6441. *
  6442. * Returns consumed size if succeed, or raise an OSError or
  6443. * UnicodeDecodeError exception and returns -1 on error.
  6444. */
  6445. static int
  6446. decode_code_page_errors(UINT code_page,
  6447. wchar_t **buf,
  6448. Py_ssize_t *bufsize,
  6449. const char *in, const int size,
  6450. const char *errors, int final)
  6451. {
  6452. const char *startin = in;
  6453. const char *endin = in + size;
  6454. DWORD flags = MB_ERR_INVALID_CHARS;
  6455. /* Ideally, we should get reason from FormatMessage. This is the Windows
  6456. 2000 English version of the message. */
  6457. const char *reason = "No mapping for the Unicode character exists "
  6458. "in the target code page.";
  6459. /* each step cannot decode more than 1 character, but a character can be
  6460. represented as a surrogate pair */
  6461. wchar_t buffer[2], *out;
  6462. int insize;
  6463. Py_ssize_t outsize;
  6464. PyObject *errorHandler = NULL;
  6465. PyObject *exc = NULL;
  6466. PyObject *encoding_obj = NULL;
  6467. const char *encoding;
  6468. DWORD err;
  6469. int ret = -1;
  6470. assert(size > 0);
  6471. encoding = code_page_name(code_page, &encoding_obj);
  6472. if (encoding == NULL)
  6473. return -1;
  6474. if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
  6475. /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
  6476. UnicodeDecodeError. */
  6477. make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
  6478. if (exc != NULL) {
  6479. PyCodec_StrictErrors(exc);
  6480. Py_CLEAR(exc);
  6481. }
  6482. goto error;
  6483. }
  6484. /* Extend a wchar_t* buffer */
  6485. Py_ssize_t n = *bufsize; /* Get the current length */
  6486. if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
  6487. PyErr_NoMemory();
  6488. goto error;
  6489. }
  6490. if (widechar_resize(buf, bufsize, n + size * Py_ARRAY_LENGTH(buffer)) < 0) {
  6491. goto error;
  6492. }
  6493. out = *buf + n;
  6494. /* Decode the byte string character per character */
  6495. while (in < endin)
  6496. {
  6497. /* Decode a character */
  6498. insize = 1;
  6499. do
  6500. {
  6501. outsize = MultiByteToWideChar(code_page, flags,
  6502. in, insize,
  6503. buffer, Py_ARRAY_LENGTH(buffer));
  6504. if (outsize > 0)
  6505. break;
  6506. err = GetLastError();
  6507. if (err == ERROR_INVALID_FLAGS && flags) {
  6508. /* For some code pages (e.g. UTF-7) flags must be set to 0. */
  6509. flags = 0;
  6510. continue;
  6511. }
  6512. if (err != ERROR_NO_UNICODE_TRANSLATION
  6513. && err != ERROR_INSUFFICIENT_BUFFER)
  6514. {
  6515. PyErr_SetFromWindowsErr(err);
  6516. goto error;
  6517. }
  6518. insize++;
  6519. }
  6520. /* 4=maximum length of a UTF-8 sequence */
  6521. while (insize <= 4 && (in + insize) <= endin);
  6522. if (outsize <= 0) {
  6523. Py_ssize_t startinpos, endinpos, outpos;
  6524. /* last character in partial decode? */
  6525. if (in + insize >= endin && !final)
  6526. break;
  6527. startinpos = in - startin;
  6528. endinpos = startinpos + 1;
  6529. outpos = out - *buf;
  6530. if (unicode_decode_call_errorhandler_wchar(
  6531. errors, &errorHandler,
  6532. encoding, reason,
  6533. &startin, &endin, &startinpos, &endinpos, &exc, &in,
  6534. buf, bufsize, &outpos))
  6535. {
  6536. goto error;
  6537. }
  6538. out = *buf + outpos;
  6539. }
  6540. else {
  6541. in += insize;
  6542. memcpy(out, buffer, outsize * sizeof(wchar_t));
  6543. out += outsize;
  6544. }
  6545. }
  6546. /* Shrink the buffer */
  6547. assert(out - *buf <= *bufsize);
  6548. *bufsize = out - *buf;
  6549. /* (in - startin) <= size and size is an int */
  6550. ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
  6551. error:
  6552. Py_XDECREF(encoding_obj);
  6553. Py_XDECREF(errorHandler);
  6554. Py_XDECREF(exc);
  6555. return ret;
  6556. }
  6557. static PyObject *
  6558. decode_code_page_stateful(int code_page,
  6559. const char *s, Py_ssize_t size,
  6560. const char *errors, Py_ssize_t *consumed)
  6561. {
  6562. wchar_t *buf = NULL;
  6563. Py_ssize_t bufsize = 0;
  6564. int chunk_size, final, converted, done;
  6565. if (code_page < 0) {
  6566. PyErr_SetString(PyExc_ValueError, "invalid code page number");
  6567. return NULL;
  6568. }
  6569. if (size < 0) {
  6570. PyErr_BadInternalCall();
  6571. return NULL;
  6572. }
  6573. if (consumed)
  6574. *consumed = 0;
  6575. do
  6576. {
  6577. #ifdef NEED_RETRY
  6578. if (size > DECODING_CHUNK_SIZE) {
  6579. chunk_size = DECODING_CHUNK_SIZE;
  6580. final = 0;
  6581. done = 0;
  6582. }
  6583. else
  6584. #endif
  6585. {
  6586. chunk_size = (int)size;
  6587. final = (consumed == NULL);
  6588. done = 1;
  6589. }
  6590. if (chunk_size == 0 && done) {
  6591. if (buf != NULL)
  6592. break;
  6593. _Py_RETURN_UNICODE_EMPTY();
  6594. }
  6595. converted = decode_code_page_strict(code_page, &buf, &bufsize,
  6596. s, chunk_size);
  6597. if (converted == -2)
  6598. converted = decode_code_page_errors(code_page, &buf, &bufsize,
  6599. s, chunk_size,
  6600. errors, final);
  6601. assert(converted != 0 || done);
  6602. if (converted < 0) {
  6603. PyMem_Free(buf);
  6604. return NULL;
  6605. }
  6606. if (consumed)
  6607. *consumed += converted;
  6608. s += converted;
  6609. size -= converted;
  6610. } while (!done);
  6611. PyObject *v = PyUnicode_FromWideChar(buf, bufsize);
  6612. PyMem_Free(buf);
  6613. return v;
  6614. }
  6615. PyObject *
  6616. PyUnicode_DecodeCodePageStateful(int code_page,
  6617. const char *s,
  6618. Py_ssize_t size,
  6619. const char *errors,
  6620. Py_ssize_t *consumed)
  6621. {
  6622. return decode_code_page_stateful(code_page, s, size, errors, consumed);
  6623. }
  6624. PyObject *
  6625. PyUnicode_DecodeMBCSStateful(const char *s,
  6626. Py_ssize_t size,
  6627. const char *errors,
  6628. Py_ssize_t *consumed)
  6629. {
  6630. return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
  6631. }
  6632. PyObject *
  6633. PyUnicode_DecodeMBCS(const char *s,
  6634. Py_ssize_t size,
  6635. const char *errors)
  6636. {
  6637. return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
  6638. }
  6639. static DWORD
  6640. encode_code_page_flags(UINT code_page, const char *errors)
  6641. {
  6642. if (code_page == CP_UTF8) {
  6643. return WC_ERR_INVALID_CHARS;
  6644. }
  6645. else if (code_page == CP_UTF7) {
  6646. /* CP_UTF7 only supports flags=0 */
  6647. return 0;
  6648. }
  6649. else {
  6650. if (errors != NULL && strcmp(errors, "replace") == 0)
  6651. return 0;
  6652. else
  6653. return WC_NO_BEST_FIT_CHARS;
  6654. }
  6655. }
  6656. /*
  6657. * Encode a Unicode string to a Windows code page into a byte string in strict
  6658. * mode.
  6659. *
  6660. * Returns consumed characters if succeed, returns -2 on encode error, or raise
  6661. * an OSError and returns -1 on other error.
  6662. */
  6663. static int
  6664. encode_code_page_strict(UINT code_page, PyObject **outbytes,
  6665. PyObject *unicode, Py_ssize_t offset, int len,
  6666. const char* errors)
  6667. {
  6668. BOOL usedDefaultChar = FALSE;
  6669. BOOL *pusedDefaultChar = &usedDefaultChar;
  6670. int outsize;
  6671. wchar_t *p;
  6672. Py_ssize_t size;
  6673. const DWORD flags = encode_code_page_flags(code_page, NULL);
  6674. char *out;
  6675. /* Create a substring so that we can get the UTF-16 representation
  6676. of just the slice under consideration. */
  6677. PyObject *substring;
  6678. int ret = -1;
  6679. assert(len > 0);
  6680. if (code_page != CP_UTF8 && code_page != CP_UTF7)
  6681. pusedDefaultChar = &usedDefaultChar;
  6682. else
  6683. pusedDefaultChar = NULL;
  6684. substring = PyUnicode_Substring(unicode, offset, offset+len);
  6685. if (substring == NULL)
  6686. return -1;
  6687. p = PyUnicode_AsWideCharString(substring, &size);
  6688. Py_CLEAR(substring);
  6689. if (p == NULL) {
  6690. return -1;
  6691. }
  6692. assert(size <= INT_MAX);
  6693. /* First get the size of the result */
  6694. outsize = WideCharToMultiByte(code_page, flags,
  6695. p, (int)size,
  6696. NULL, 0,
  6697. NULL, pusedDefaultChar);
  6698. if (outsize <= 0)
  6699. goto error;
  6700. /* If we used a default char, then we failed! */
  6701. if (pusedDefaultChar && *pusedDefaultChar) {
  6702. ret = -2;
  6703. goto done;
  6704. }
  6705. if (*outbytes == NULL) {
  6706. /* Create string object */
  6707. *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
  6708. if (*outbytes == NULL) {
  6709. goto done;
  6710. }
  6711. out = PyBytes_AS_STRING(*outbytes);
  6712. }
  6713. else {
  6714. /* Extend string object */
  6715. const Py_ssize_t n = PyBytes_Size(*outbytes);
  6716. if (outsize > PY_SSIZE_T_MAX - n) {
  6717. PyErr_NoMemory();
  6718. goto done;
  6719. }
  6720. if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
  6721. goto done;
  6722. }
  6723. out = PyBytes_AS_STRING(*outbytes) + n;
  6724. }
  6725. /* Do the conversion */
  6726. outsize = WideCharToMultiByte(code_page, flags,
  6727. p, (int)size,
  6728. out, outsize,
  6729. NULL, pusedDefaultChar);
  6730. if (outsize <= 0)
  6731. goto error;
  6732. if (pusedDefaultChar && *pusedDefaultChar) {
  6733. ret = -2;
  6734. goto done;
  6735. }
  6736. ret = 0;
  6737. done:
  6738. PyMem_Free(p);
  6739. return ret;
  6740. error:
  6741. if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
  6742. ret = -2;
  6743. goto done;
  6744. }
  6745. PyErr_SetFromWindowsErr(0);
  6746. goto done;
  6747. }
  6748. /*
  6749. * Encode a Unicode string to a Windows code page into a byte string using an
  6750. * error handler.
  6751. *
  6752. * Returns consumed characters if succeed, or raise an OSError and returns
  6753. * -1 on other error.
  6754. */
  6755. static int
  6756. encode_code_page_errors(UINT code_page, PyObject **outbytes,
  6757. PyObject *unicode, Py_ssize_t unicode_offset,
  6758. Py_ssize_t insize, const char* errors)
  6759. {
  6760. const DWORD flags = encode_code_page_flags(code_page, errors);
  6761. Py_ssize_t pos = unicode_offset;
  6762. Py_ssize_t endin = unicode_offset + insize;
  6763. /* Ideally, we should get reason from FormatMessage. This is the Windows
  6764. 2000 English version of the message. */
  6765. const char *reason = "invalid character";
  6766. /* 4=maximum length of a UTF-8 sequence */
  6767. char buffer[4];
  6768. BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
  6769. Py_ssize_t outsize;
  6770. char *out;
  6771. PyObject *errorHandler = NULL;
  6772. PyObject *exc = NULL;
  6773. PyObject *encoding_obj = NULL;
  6774. const char *encoding;
  6775. Py_ssize_t newpos, newoutsize;
  6776. PyObject *rep;
  6777. int ret = -1;
  6778. assert(insize > 0);
  6779. encoding = code_page_name(code_page, &encoding_obj);
  6780. if (encoding == NULL)
  6781. return -1;
  6782. if (errors == NULL || strcmp(errors, "strict") == 0) {
  6783. /* The last error was ERROR_NO_UNICODE_TRANSLATION,
  6784. then we raise a UnicodeEncodeError. */
  6785. make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
  6786. if (exc != NULL) {
  6787. PyCodec_StrictErrors(exc);
  6788. Py_DECREF(exc);
  6789. }
  6790. Py_XDECREF(encoding_obj);
  6791. return -1;
  6792. }
  6793. if (code_page != CP_UTF8 && code_page != CP_UTF7)
  6794. pusedDefaultChar = &usedDefaultChar;
  6795. else
  6796. pusedDefaultChar = NULL;
  6797. if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
  6798. PyErr_NoMemory();
  6799. goto error;
  6800. }
  6801. outsize = insize * Py_ARRAY_LENGTH(buffer);
  6802. if (*outbytes == NULL) {
  6803. /* Create string object */
  6804. *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
  6805. if (*outbytes == NULL)
  6806. goto error;
  6807. out = PyBytes_AS_STRING(*outbytes);
  6808. }
  6809. else {
  6810. /* Extend string object */
  6811. Py_ssize_t n = PyBytes_Size(*outbytes);
  6812. if (n > PY_SSIZE_T_MAX - outsize) {
  6813. PyErr_NoMemory();
  6814. goto error;
  6815. }
  6816. if (_PyBytes_Resize(outbytes, n + outsize) < 0)
  6817. goto error;
  6818. out = PyBytes_AS_STRING(*outbytes) + n;
  6819. }
  6820. /* Encode the string character per character */
  6821. while (pos < endin)
  6822. {
  6823. Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
  6824. wchar_t chars[2];
  6825. int charsize;
  6826. if (ch < 0x10000) {
  6827. chars[0] = (wchar_t)ch;
  6828. charsize = 1;
  6829. }
  6830. else {
  6831. chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
  6832. chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
  6833. charsize = 2;
  6834. }
  6835. outsize = WideCharToMultiByte(code_page, flags,
  6836. chars, charsize,
  6837. buffer, Py_ARRAY_LENGTH(buffer),
  6838. NULL, pusedDefaultChar);
  6839. if (outsize > 0) {
  6840. if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
  6841. {
  6842. pos++;
  6843. memcpy(out, buffer, outsize);
  6844. out += outsize;
  6845. continue;
  6846. }
  6847. }
  6848. else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
  6849. PyErr_SetFromWindowsErr(0);
  6850. goto error;
  6851. }
  6852. rep = unicode_encode_call_errorhandler(
  6853. errors, &errorHandler, encoding, reason,
  6854. unicode, &exc,
  6855. pos, pos + 1, &newpos);
  6856. if (rep == NULL)
  6857. goto error;
  6858. Py_ssize_t morebytes = pos - newpos;
  6859. if (PyBytes_Check(rep)) {
  6860. outsize = PyBytes_GET_SIZE(rep);
  6861. morebytes += outsize;
  6862. if (morebytes > 0) {
  6863. Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
  6864. newoutsize = PyBytes_GET_SIZE(*outbytes) + morebytes;
  6865. if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
  6866. Py_DECREF(rep);
  6867. goto error;
  6868. }
  6869. out = PyBytes_AS_STRING(*outbytes) + offset;
  6870. }
  6871. memcpy(out, PyBytes_AS_STRING(rep), outsize);
  6872. out += outsize;
  6873. }
  6874. else {
  6875. Py_ssize_t i;
  6876. int kind;
  6877. const void *data;
  6878. outsize = PyUnicode_GET_LENGTH(rep);
  6879. morebytes += outsize;
  6880. if (morebytes > 0) {
  6881. Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
  6882. newoutsize = PyBytes_GET_SIZE(*outbytes) + morebytes;
  6883. if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
  6884. Py_DECREF(rep);
  6885. goto error;
  6886. }
  6887. out = PyBytes_AS_STRING(*outbytes) + offset;
  6888. }
  6889. kind = PyUnicode_KIND(rep);
  6890. data = PyUnicode_DATA(rep);
  6891. for (i=0; i < outsize; i++) {
  6892. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  6893. if (ch > 127) {
  6894. raise_encode_exception(&exc,
  6895. encoding, unicode,
  6896. pos, pos + 1,
  6897. "unable to encode error handler result to ASCII");
  6898. Py_DECREF(rep);
  6899. goto error;
  6900. }
  6901. *out = (unsigned char)ch;
  6902. out++;
  6903. }
  6904. }
  6905. pos = newpos;
  6906. Py_DECREF(rep);
  6907. }
  6908. /* write a NUL byte */
  6909. *out = 0;
  6910. outsize = out - PyBytes_AS_STRING(*outbytes);
  6911. assert(outsize <= PyBytes_GET_SIZE(*outbytes));
  6912. if (_PyBytes_Resize(outbytes, outsize) < 0)
  6913. goto error;
  6914. ret = 0;
  6915. error:
  6916. Py_XDECREF(encoding_obj);
  6917. Py_XDECREF(errorHandler);
  6918. Py_XDECREF(exc);
  6919. return ret;
  6920. }
  6921. static PyObject *
  6922. encode_code_page(int code_page,
  6923. PyObject *unicode,
  6924. const char *errors)
  6925. {
  6926. Py_ssize_t len;
  6927. PyObject *outbytes = NULL;
  6928. Py_ssize_t offset;
  6929. int chunk_len, ret, done;
  6930. if (!PyUnicode_Check(unicode)) {
  6931. PyErr_BadArgument();
  6932. return NULL;
  6933. }
  6934. len = PyUnicode_GET_LENGTH(unicode);
  6935. if (code_page < 0) {
  6936. PyErr_SetString(PyExc_ValueError, "invalid code page number");
  6937. return NULL;
  6938. }
  6939. if (len == 0)
  6940. return PyBytes_FromStringAndSize(NULL, 0);
  6941. offset = 0;
  6942. do
  6943. {
  6944. #ifdef NEED_RETRY
  6945. if (len > DECODING_CHUNK_SIZE) {
  6946. chunk_len = DECODING_CHUNK_SIZE;
  6947. done = 0;
  6948. }
  6949. else
  6950. #endif
  6951. {
  6952. chunk_len = (int)len;
  6953. done = 1;
  6954. }
  6955. ret = encode_code_page_strict(code_page, &outbytes,
  6956. unicode, offset, chunk_len,
  6957. errors);
  6958. if (ret == -2)
  6959. ret = encode_code_page_errors(code_page, &outbytes,
  6960. unicode, offset,
  6961. chunk_len, errors);
  6962. if (ret < 0) {
  6963. Py_XDECREF(outbytes);
  6964. return NULL;
  6965. }
  6966. offset += chunk_len;
  6967. len -= chunk_len;
  6968. } while (!done);
  6969. return outbytes;
  6970. }
  6971. PyObject *
  6972. PyUnicode_EncodeCodePage(int code_page,
  6973. PyObject *unicode,
  6974. const char *errors)
  6975. {
  6976. return encode_code_page(code_page, unicode, errors);
  6977. }
  6978. PyObject *
  6979. PyUnicode_AsMBCSString(PyObject *unicode)
  6980. {
  6981. return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
  6982. }
  6983. #undef NEED_RETRY
  6984. #endif /* MS_WINDOWS */
  6985. /* --- Character Mapping Codec -------------------------------------------- */
  6986. static int
  6987. charmap_decode_string(const char *s,
  6988. Py_ssize_t size,
  6989. PyObject *mapping,
  6990. const char *errors,
  6991. _PyUnicodeWriter *writer)
  6992. {
  6993. const char *starts = s;
  6994. const char *e;
  6995. Py_ssize_t startinpos, endinpos;
  6996. PyObject *errorHandler = NULL, *exc = NULL;
  6997. Py_ssize_t maplen;
  6998. int mapkind;
  6999. const void *mapdata;
  7000. Py_UCS4 x;
  7001. unsigned char ch;
  7002. maplen = PyUnicode_GET_LENGTH(mapping);
  7003. mapdata = PyUnicode_DATA(mapping);
  7004. mapkind = PyUnicode_KIND(mapping);
  7005. e = s + size;
  7006. if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
  7007. /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
  7008. * is disabled in encoding aliases, latin1 is preferred because
  7009. * its implementation is faster. */
  7010. const Py_UCS1 *mapdata_ucs1 = (const Py_UCS1 *)mapdata;
  7011. Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
  7012. Py_UCS4 maxchar = writer->maxchar;
  7013. assert (writer->kind == PyUnicode_1BYTE_KIND);
  7014. while (s < e) {
  7015. ch = *s;
  7016. x = mapdata_ucs1[ch];
  7017. if (x > maxchar) {
  7018. if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
  7019. goto onError;
  7020. maxchar = writer->maxchar;
  7021. outdata = (Py_UCS1 *)writer->data;
  7022. }
  7023. outdata[writer->pos] = x;
  7024. writer->pos++;
  7025. ++s;
  7026. }
  7027. return 0;
  7028. }
  7029. while (s < e) {
  7030. if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
  7031. int outkind = writer->kind;
  7032. const Py_UCS2 *mapdata_ucs2 = (const Py_UCS2 *)mapdata;
  7033. if (outkind == PyUnicode_1BYTE_KIND) {
  7034. Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
  7035. Py_UCS4 maxchar = writer->maxchar;
  7036. while (s < e) {
  7037. ch = *s;
  7038. x = mapdata_ucs2[ch];
  7039. if (x > maxchar)
  7040. goto Error;
  7041. outdata[writer->pos] = x;
  7042. writer->pos++;
  7043. ++s;
  7044. }
  7045. break;
  7046. }
  7047. else if (outkind == PyUnicode_2BYTE_KIND) {
  7048. Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
  7049. while (s < e) {
  7050. ch = *s;
  7051. x = mapdata_ucs2[ch];
  7052. if (x == 0xFFFE)
  7053. goto Error;
  7054. outdata[writer->pos] = x;
  7055. writer->pos++;
  7056. ++s;
  7057. }
  7058. break;
  7059. }
  7060. }
  7061. ch = *s;
  7062. if (ch < maplen)
  7063. x = PyUnicode_READ(mapkind, mapdata, ch);
  7064. else
  7065. x = 0xfffe; /* invalid value */
  7066. Error:
  7067. if (x == 0xfffe)
  7068. {
  7069. /* undefined mapping */
  7070. startinpos = s-starts;
  7071. endinpos = startinpos+1;
  7072. if (unicode_decode_call_errorhandler_writer(
  7073. errors, &errorHandler,
  7074. "charmap", "character maps to <undefined>",
  7075. &starts, &e, &startinpos, &endinpos, &exc, &s,
  7076. writer)) {
  7077. goto onError;
  7078. }
  7079. continue;
  7080. }
  7081. if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
  7082. goto onError;
  7083. ++s;
  7084. }
  7085. Py_XDECREF(errorHandler);
  7086. Py_XDECREF(exc);
  7087. return 0;
  7088. onError:
  7089. Py_XDECREF(errorHandler);
  7090. Py_XDECREF(exc);
  7091. return -1;
  7092. }
  7093. static int
  7094. charmap_decode_mapping(const char *s,
  7095. Py_ssize_t size,
  7096. PyObject *mapping,
  7097. const char *errors,
  7098. _PyUnicodeWriter *writer)
  7099. {
  7100. const char *starts = s;
  7101. const char *e;
  7102. Py_ssize_t startinpos, endinpos;
  7103. PyObject *errorHandler = NULL, *exc = NULL;
  7104. unsigned char ch;
  7105. PyObject *key, *item = NULL;
  7106. e = s + size;
  7107. while (s < e) {
  7108. ch = *s;
  7109. /* Get mapping (char ordinal -> integer, Unicode char or None) */
  7110. key = PyLong_FromLong((long)ch);
  7111. if (key == NULL)
  7112. goto onError;
  7113. item = PyObject_GetItem(mapping, key);
  7114. Py_DECREF(key);
  7115. if (item == NULL) {
  7116. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  7117. /* No mapping found means: mapping is undefined. */
  7118. PyErr_Clear();
  7119. goto Undefined;
  7120. } else
  7121. goto onError;
  7122. }
  7123. /* Apply mapping */
  7124. if (item == Py_None)
  7125. goto Undefined;
  7126. if (PyLong_Check(item)) {
  7127. long value = PyLong_AS_LONG(item);
  7128. if (value == 0xFFFE)
  7129. goto Undefined;
  7130. if (value < 0 || value > MAX_UNICODE) {
  7131. PyErr_Format(PyExc_TypeError,
  7132. "character mapping must be in range(0x%x)",
  7133. (unsigned long)MAX_UNICODE + 1);
  7134. goto onError;
  7135. }
  7136. if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
  7137. goto onError;
  7138. }
  7139. else if (PyUnicode_Check(item)) {
  7140. if (PyUnicode_GET_LENGTH(item) == 1) {
  7141. Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
  7142. if (value == 0xFFFE)
  7143. goto Undefined;
  7144. if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
  7145. goto onError;
  7146. }
  7147. else {
  7148. writer->overallocate = 1;
  7149. if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
  7150. goto onError;
  7151. }
  7152. }
  7153. else {
  7154. /* wrong return value */
  7155. PyErr_SetString(PyExc_TypeError,
  7156. "character mapping must return integer, None or str");
  7157. goto onError;
  7158. }
  7159. Py_CLEAR(item);
  7160. ++s;
  7161. continue;
  7162. Undefined:
  7163. /* undefined mapping */
  7164. Py_CLEAR(item);
  7165. startinpos = s-starts;
  7166. endinpos = startinpos+1;
  7167. if (unicode_decode_call_errorhandler_writer(
  7168. errors, &errorHandler,
  7169. "charmap", "character maps to <undefined>",
  7170. &starts, &e, &startinpos, &endinpos, &exc, &s,
  7171. writer)) {
  7172. goto onError;
  7173. }
  7174. }
  7175. Py_XDECREF(errorHandler);
  7176. Py_XDECREF(exc);
  7177. return 0;
  7178. onError:
  7179. Py_XDECREF(item);
  7180. Py_XDECREF(errorHandler);
  7181. Py_XDECREF(exc);
  7182. return -1;
  7183. }
  7184. PyObject *
  7185. PyUnicode_DecodeCharmap(const char *s,
  7186. Py_ssize_t size,
  7187. PyObject *mapping,
  7188. const char *errors)
  7189. {
  7190. _PyUnicodeWriter writer;
  7191. /* Default to Latin-1 */
  7192. if (mapping == NULL)
  7193. return PyUnicode_DecodeLatin1(s, size, errors);
  7194. if (size == 0)
  7195. _Py_RETURN_UNICODE_EMPTY();
  7196. _PyUnicodeWriter_Init(&writer);
  7197. writer.min_length = size;
  7198. if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
  7199. goto onError;
  7200. if (PyUnicode_CheckExact(mapping)) {
  7201. if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
  7202. goto onError;
  7203. }
  7204. else {
  7205. if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
  7206. goto onError;
  7207. }
  7208. return _PyUnicodeWriter_Finish(&writer);
  7209. onError:
  7210. _PyUnicodeWriter_Dealloc(&writer);
  7211. return NULL;
  7212. }
  7213. /* Charmap encoding: the lookup table */
  7214. /*[clinic input]
  7215. class EncodingMap "struct encoding_map *" "&EncodingMapType"
  7216. [clinic start generated code]*/
  7217. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=14e46bbb6c522d22]*/
  7218. struct encoding_map {
  7219. PyObject_HEAD
  7220. unsigned char level1[32];
  7221. int count2, count3;
  7222. unsigned char level23[1];
  7223. };
  7224. /*[clinic input]
  7225. EncodingMap.size
  7226. Return the size (in bytes) of this object.
  7227. [clinic start generated code]*/
  7228. static PyObject *
  7229. EncodingMap_size_impl(struct encoding_map *self)
  7230. /*[clinic end generated code: output=c4c969e4c99342a4 input=004ff13f26bb5366]*/
  7231. {
  7232. return PyLong_FromLong((sizeof(*self) - 1) + 16*self->count2 +
  7233. 128*self->count3);
  7234. }
  7235. static PyMethodDef encoding_map_methods[] = {
  7236. ENCODINGMAP_SIZE_METHODDEF
  7237. {NULL, NULL}
  7238. };
  7239. static PyTypeObject EncodingMapType = {
  7240. PyVarObject_HEAD_INIT(NULL, 0)
  7241. .tp_name = "EncodingMap",
  7242. .tp_basicsize = sizeof(struct encoding_map),
  7243. /* methods */
  7244. .tp_flags = Py_TPFLAGS_DEFAULT,
  7245. .tp_methods = encoding_map_methods,
  7246. };
  7247. PyObject*
  7248. PyUnicode_BuildEncodingMap(PyObject* string)
  7249. {
  7250. PyObject *result;
  7251. struct encoding_map *mresult;
  7252. int i;
  7253. int need_dict = 0;
  7254. unsigned char level1[32];
  7255. unsigned char level2[512];
  7256. unsigned char *mlevel1, *mlevel2, *mlevel3;
  7257. int count2 = 0, count3 = 0;
  7258. int kind;
  7259. const void *data;
  7260. Py_ssize_t length;
  7261. Py_UCS4 ch;
  7262. if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
  7263. PyErr_BadArgument();
  7264. return NULL;
  7265. }
  7266. kind = PyUnicode_KIND(string);
  7267. data = PyUnicode_DATA(string);
  7268. length = PyUnicode_GET_LENGTH(string);
  7269. length = Py_MIN(length, 256);
  7270. memset(level1, 0xFF, sizeof level1);
  7271. memset(level2, 0xFF, sizeof level2);
  7272. /* If there isn't a one-to-one mapping of NULL to \0,
  7273. or if there are non-BMP characters, we need to use
  7274. a mapping dictionary. */
  7275. if (PyUnicode_READ(kind, data, 0) != 0)
  7276. need_dict = 1;
  7277. for (i = 1; i < length; i++) {
  7278. int l1, l2;
  7279. ch = PyUnicode_READ(kind, data, i);
  7280. if (ch == 0 || ch > 0xFFFF) {
  7281. need_dict = 1;
  7282. break;
  7283. }
  7284. if (ch == 0xFFFE)
  7285. /* unmapped character */
  7286. continue;
  7287. l1 = ch >> 11;
  7288. l2 = ch >> 7;
  7289. if (level1[l1] == 0xFF)
  7290. level1[l1] = count2++;
  7291. if (level2[l2] == 0xFF)
  7292. level2[l2] = count3++;
  7293. }
  7294. if (count2 >= 0xFF || count3 >= 0xFF)
  7295. need_dict = 1;
  7296. if (need_dict) {
  7297. PyObject *result = PyDict_New();
  7298. if (!result)
  7299. return NULL;
  7300. for (i = 0; i < length; i++) {
  7301. Py_UCS4 c = PyUnicode_READ(kind, data, i);
  7302. PyObject *key = PyLong_FromLong(c);
  7303. if (key == NULL) {
  7304. Py_DECREF(result);
  7305. return NULL;
  7306. }
  7307. PyObject *value = PyLong_FromLong(i);
  7308. if (value == NULL) {
  7309. Py_DECREF(key);
  7310. Py_DECREF(result);
  7311. return NULL;
  7312. }
  7313. int rc = PyDict_SetItem(result, key, value);
  7314. Py_DECREF(key);
  7315. Py_DECREF(value);
  7316. if (rc < 0) {
  7317. Py_DECREF(result);
  7318. return NULL;
  7319. }
  7320. }
  7321. return result;
  7322. }
  7323. /* Create a three-level trie */
  7324. result = PyObject_Malloc(sizeof(struct encoding_map) +
  7325. 16*count2 + 128*count3 - 1);
  7326. if (!result) {
  7327. return PyErr_NoMemory();
  7328. }
  7329. _PyObject_Init(result, &EncodingMapType);
  7330. mresult = (struct encoding_map*)result;
  7331. mresult->count2 = count2;
  7332. mresult->count3 = count3;
  7333. mlevel1 = mresult->level1;
  7334. mlevel2 = mresult->level23;
  7335. mlevel3 = mresult->level23 + 16*count2;
  7336. memcpy(mlevel1, level1, 32);
  7337. memset(mlevel2, 0xFF, 16*count2);
  7338. memset(mlevel3, 0, 128*count3);
  7339. count3 = 0;
  7340. for (i = 1; i < length; i++) {
  7341. int o1, o2, o3, i2, i3;
  7342. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  7343. if (ch == 0xFFFE)
  7344. /* unmapped character */
  7345. continue;
  7346. o1 = ch>>11;
  7347. o2 = (ch>>7) & 0xF;
  7348. i2 = 16*mlevel1[o1] + o2;
  7349. if (mlevel2[i2] == 0xFF)
  7350. mlevel2[i2] = count3++;
  7351. o3 = ch & 0x7F;
  7352. i3 = 128*mlevel2[i2] + o3;
  7353. mlevel3[i3] = i;
  7354. }
  7355. return result;
  7356. }
  7357. static int
  7358. encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
  7359. {
  7360. struct encoding_map *map = (struct encoding_map*)mapping;
  7361. int l1 = c>>11;
  7362. int l2 = (c>>7) & 0xF;
  7363. int l3 = c & 0x7F;
  7364. int i;
  7365. if (c > 0xFFFF)
  7366. return -1;
  7367. if (c == 0)
  7368. return 0;
  7369. /* level 1*/
  7370. i = map->level1[l1];
  7371. if (i == 0xFF) {
  7372. return -1;
  7373. }
  7374. /* level 2*/
  7375. i = map->level23[16*i+l2];
  7376. if (i == 0xFF) {
  7377. return -1;
  7378. }
  7379. /* level 3 */
  7380. i = map->level23[16*map->count2 + 128*i + l3];
  7381. if (i == 0) {
  7382. return -1;
  7383. }
  7384. return i;
  7385. }
  7386. /* Lookup the character ch in the mapping. If the character
  7387. can't be found, Py_None is returned (or NULL, if another
  7388. error occurred). */
  7389. static PyObject *
  7390. charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
  7391. {
  7392. PyObject *w = PyLong_FromLong((long)c);
  7393. PyObject *x;
  7394. if (w == NULL)
  7395. return NULL;
  7396. x = PyObject_GetItem(mapping, w);
  7397. Py_DECREF(w);
  7398. if (x == NULL) {
  7399. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  7400. /* No mapping found means: mapping is undefined. */
  7401. PyErr_Clear();
  7402. Py_RETURN_NONE;
  7403. } else
  7404. return NULL;
  7405. }
  7406. else if (x == Py_None)
  7407. return x;
  7408. else if (PyLong_Check(x)) {
  7409. long value = PyLong_AS_LONG(x);
  7410. if (value < 0 || value > 255) {
  7411. PyErr_SetString(PyExc_TypeError,
  7412. "character mapping must be in range(256)");
  7413. Py_DECREF(x);
  7414. return NULL;
  7415. }
  7416. return x;
  7417. }
  7418. else if (PyBytes_Check(x))
  7419. return x;
  7420. else {
  7421. /* wrong return value */
  7422. PyErr_Format(PyExc_TypeError,
  7423. "character mapping must return integer, bytes or None, not %.400s",
  7424. Py_TYPE(x)->tp_name);
  7425. Py_DECREF(x);
  7426. return NULL;
  7427. }
  7428. }
  7429. static int
  7430. charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
  7431. {
  7432. Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
  7433. /* exponentially overallocate to minimize reallocations */
  7434. if (requiredsize < 2*outsize)
  7435. requiredsize = 2*outsize;
  7436. if (_PyBytes_Resize(outobj, requiredsize))
  7437. return -1;
  7438. return 0;
  7439. }
  7440. typedef enum charmapencode_result {
  7441. enc_SUCCESS, enc_FAILED, enc_EXCEPTION
  7442. } charmapencode_result;
  7443. /* lookup the character, put the result in the output string and adjust
  7444. various state variables. Resize the output bytes object if not enough
  7445. space is available. Return a new reference to the object that
  7446. was put in the output buffer, or Py_None, if the mapping was undefined
  7447. (in which case no character was written) or NULL, if a
  7448. reallocation error occurred. The caller must decref the result */
  7449. static charmapencode_result
  7450. charmapencode_output(Py_UCS4 c, PyObject *mapping,
  7451. PyObject **outobj, Py_ssize_t *outpos)
  7452. {
  7453. PyObject *rep;
  7454. char *outstart;
  7455. Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
  7456. if (Py_IS_TYPE(mapping, &EncodingMapType)) {
  7457. int res = encoding_map_lookup(c, mapping);
  7458. Py_ssize_t requiredsize = *outpos+1;
  7459. if (res == -1)
  7460. return enc_FAILED;
  7461. if (outsize<requiredsize)
  7462. if (charmapencode_resize(outobj, outpos, requiredsize))
  7463. return enc_EXCEPTION;
  7464. outstart = PyBytes_AS_STRING(*outobj);
  7465. outstart[(*outpos)++] = (char)res;
  7466. return enc_SUCCESS;
  7467. }
  7468. rep = charmapencode_lookup(c, mapping);
  7469. if (rep==NULL)
  7470. return enc_EXCEPTION;
  7471. else if (rep==Py_None) {
  7472. Py_DECREF(rep);
  7473. return enc_FAILED;
  7474. } else {
  7475. if (PyLong_Check(rep)) {
  7476. Py_ssize_t requiredsize = *outpos+1;
  7477. if (outsize<requiredsize)
  7478. if (charmapencode_resize(outobj, outpos, requiredsize)) {
  7479. Py_DECREF(rep);
  7480. return enc_EXCEPTION;
  7481. }
  7482. outstart = PyBytes_AS_STRING(*outobj);
  7483. outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
  7484. }
  7485. else {
  7486. const char *repchars = PyBytes_AS_STRING(rep);
  7487. Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
  7488. Py_ssize_t requiredsize = *outpos+repsize;
  7489. if (outsize<requiredsize)
  7490. if (charmapencode_resize(outobj, outpos, requiredsize)) {
  7491. Py_DECREF(rep);
  7492. return enc_EXCEPTION;
  7493. }
  7494. outstart = PyBytes_AS_STRING(*outobj);
  7495. memcpy(outstart + *outpos, repchars, repsize);
  7496. *outpos += repsize;
  7497. }
  7498. }
  7499. Py_DECREF(rep);
  7500. return enc_SUCCESS;
  7501. }
  7502. /* handle an error in PyUnicode_EncodeCharmap
  7503. Return 0 on success, -1 on error */
  7504. static int
  7505. charmap_encoding_error(
  7506. PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
  7507. PyObject **exceptionObject,
  7508. _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
  7509. PyObject **res, Py_ssize_t *respos)
  7510. {
  7511. PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
  7512. Py_ssize_t size, repsize;
  7513. Py_ssize_t newpos;
  7514. int kind;
  7515. const void *data;
  7516. Py_ssize_t index;
  7517. /* startpos for collecting unencodable chars */
  7518. Py_ssize_t collstartpos = *inpos;
  7519. Py_ssize_t collendpos = *inpos+1;
  7520. Py_ssize_t collpos;
  7521. const char *encoding = "charmap";
  7522. const char *reason = "character maps to <undefined>";
  7523. charmapencode_result x;
  7524. Py_UCS4 ch;
  7525. int val;
  7526. size = PyUnicode_GET_LENGTH(unicode);
  7527. /* find all unencodable characters */
  7528. while (collendpos < size) {
  7529. PyObject *rep;
  7530. if (Py_IS_TYPE(mapping, &EncodingMapType)) {
  7531. ch = PyUnicode_READ_CHAR(unicode, collendpos);
  7532. val = encoding_map_lookup(ch, mapping);
  7533. if (val != -1)
  7534. break;
  7535. ++collendpos;
  7536. continue;
  7537. }
  7538. ch = PyUnicode_READ_CHAR(unicode, collendpos);
  7539. rep = charmapencode_lookup(ch, mapping);
  7540. if (rep==NULL)
  7541. return -1;
  7542. else if (rep!=Py_None) {
  7543. Py_DECREF(rep);
  7544. break;
  7545. }
  7546. Py_DECREF(rep);
  7547. ++collendpos;
  7548. }
  7549. /* cache callback name lookup
  7550. * (if not done yet, i.e. it's the first error) */
  7551. if (*error_handler == _Py_ERROR_UNKNOWN)
  7552. *error_handler = _Py_GetErrorHandler(errors);
  7553. switch (*error_handler) {
  7554. case _Py_ERROR_STRICT:
  7555. raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
  7556. return -1;
  7557. case _Py_ERROR_REPLACE:
  7558. for (collpos = collstartpos; collpos<collendpos; ++collpos) {
  7559. x = charmapencode_output('?', mapping, res, respos);
  7560. if (x==enc_EXCEPTION) {
  7561. return -1;
  7562. }
  7563. else if (x==enc_FAILED) {
  7564. raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
  7565. return -1;
  7566. }
  7567. }
  7568. /* fall through */
  7569. case _Py_ERROR_IGNORE:
  7570. *inpos = collendpos;
  7571. break;
  7572. case _Py_ERROR_XMLCHARREFREPLACE:
  7573. /* generate replacement (temporarily (mis)uses p) */
  7574. for (collpos = collstartpos; collpos < collendpos; ++collpos) {
  7575. char buffer[2+29+1+1];
  7576. char *cp;
  7577. sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
  7578. for (cp = buffer; *cp; ++cp) {
  7579. x = charmapencode_output(*cp, mapping, res, respos);
  7580. if (x==enc_EXCEPTION)
  7581. return -1;
  7582. else if (x==enc_FAILED) {
  7583. raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
  7584. return -1;
  7585. }
  7586. }
  7587. }
  7588. *inpos = collendpos;
  7589. break;
  7590. default:
  7591. repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
  7592. encoding, reason, unicode, exceptionObject,
  7593. collstartpos, collendpos, &newpos);
  7594. if (repunicode == NULL)
  7595. return -1;
  7596. if (PyBytes_Check(repunicode)) {
  7597. /* Directly copy bytes result to output. */
  7598. Py_ssize_t outsize = PyBytes_Size(*res);
  7599. Py_ssize_t requiredsize;
  7600. repsize = PyBytes_Size(repunicode);
  7601. requiredsize = *respos + repsize;
  7602. if (requiredsize > outsize)
  7603. /* Make room for all additional bytes. */
  7604. if (charmapencode_resize(res, respos, requiredsize)) {
  7605. Py_DECREF(repunicode);
  7606. return -1;
  7607. }
  7608. memcpy(PyBytes_AsString(*res) + *respos,
  7609. PyBytes_AsString(repunicode), repsize);
  7610. *respos += repsize;
  7611. *inpos = newpos;
  7612. Py_DECREF(repunicode);
  7613. break;
  7614. }
  7615. /* generate replacement */
  7616. repsize = PyUnicode_GET_LENGTH(repunicode);
  7617. data = PyUnicode_DATA(repunicode);
  7618. kind = PyUnicode_KIND(repunicode);
  7619. for (index = 0; index < repsize; index++) {
  7620. Py_UCS4 repch = PyUnicode_READ(kind, data, index);
  7621. x = charmapencode_output(repch, mapping, res, respos);
  7622. if (x==enc_EXCEPTION) {
  7623. Py_DECREF(repunicode);
  7624. return -1;
  7625. }
  7626. else if (x==enc_FAILED) {
  7627. Py_DECREF(repunicode);
  7628. raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
  7629. return -1;
  7630. }
  7631. }
  7632. *inpos = newpos;
  7633. Py_DECREF(repunicode);
  7634. }
  7635. return 0;
  7636. }
  7637. PyObject *
  7638. _PyUnicode_EncodeCharmap(PyObject *unicode,
  7639. PyObject *mapping,
  7640. const char *errors)
  7641. {
  7642. /* output object */
  7643. PyObject *res = NULL;
  7644. /* current input position */
  7645. Py_ssize_t inpos = 0;
  7646. Py_ssize_t size;
  7647. /* current output position */
  7648. Py_ssize_t respos = 0;
  7649. PyObject *error_handler_obj = NULL;
  7650. PyObject *exc = NULL;
  7651. _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
  7652. const void *data;
  7653. int kind;
  7654. size = PyUnicode_GET_LENGTH(unicode);
  7655. data = PyUnicode_DATA(unicode);
  7656. kind = PyUnicode_KIND(unicode);
  7657. /* Default to Latin-1 */
  7658. if (mapping == NULL)
  7659. return unicode_encode_ucs1(unicode, errors, 256);
  7660. /* allocate enough for a simple encoding without
  7661. replacements, if we need more, we'll resize */
  7662. res = PyBytes_FromStringAndSize(NULL, size);
  7663. if (res == NULL)
  7664. goto onError;
  7665. if (size == 0)
  7666. return res;
  7667. while (inpos<size) {
  7668. Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
  7669. /* try to encode it */
  7670. charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
  7671. if (x==enc_EXCEPTION) /* error */
  7672. goto onError;
  7673. if (x==enc_FAILED) { /* unencodable character */
  7674. if (charmap_encoding_error(unicode, &inpos, mapping,
  7675. &exc,
  7676. &error_handler, &error_handler_obj, errors,
  7677. &res, &respos)) {
  7678. goto onError;
  7679. }
  7680. }
  7681. else
  7682. /* done with this character => adjust input position */
  7683. ++inpos;
  7684. }
  7685. /* Resize if we allocated to much */
  7686. if (respos<PyBytes_GET_SIZE(res))
  7687. if (_PyBytes_Resize(&res, respos) < 0)
  7688. goto onError;
  7689. Py_XDECREF(exc);
  7690. Py_XDECREF(error_handler_obj);
  7691. return res;
  7692. onError:
  7693. Py_XDECREF(res);
  7694. Py_XDECREF(exc);
  7695. Py_XDECREF(error_handler_obj);
  7696. return NULL;
  7697. }
  7698. PyObject *
  7699. PyUnicode_AsCharmapString(PyObject *unicode,
  7700. PyObject *mapping)
  7701. {
  7702. if (!PyUnicode_Check(unicode) || mapping == NULL) {
  7703. PyErr_BadArgument();
  7704. return NULL;
  7705. }
  7706. return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
  7707. }
  7708. /* create or adjust a UnicodeTranslateError */
  7709. static void
  7710. make_translate_exception(PyObject **exceptionObject,
  7711. PyObject *unicode,
  7712. Py_ssize_t startpos, Py_ssize_t endpos,
  7713. const char *reason)
  7714. {
  7715. if (*exceptionObject == NULL) {
  7716. *exceptionObject = _PyUnicodeTranslateError_Create(
  7717. unicode, startpos, endpos, reason);
  7718. }
  7719. else {
  7720. if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
  7721. goto onError;
  7722. if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
  7723. goto onError;
  7724. if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
  7725. goto onError;
  7726. return;
  7727. onError:
  7728. Py_CLEAR(*exceptionObject);
  7729. }
  7730. }
  7731. /* error handling callback helper:
  7732. build arguments, call the callback and check the arguments,
  7733. put the result into newpos and return the replacement string, which
  7734. has to be freed by the caller */
  7735. static PyObject *
  7736. unicode_translate_call_errorhandler(const char *errors,
  7737. PyObject **errorHandler,
  7738. const char *reason,
  7739. PyObject *unicode, PyObject **exceptionObject,
  7740. Py_ssize_t startpos, Py_ssize_t endpos,
  7741. Py_ssize_t *newpos)
  7742. {
  7743. static const char *argparse = "Un;translating error handler must return (str, int) tuple";
  7744. Py_ssize_t i_newpos;
  7745. PyObject *restuple;
  7746. PyObject *resunicode;
  7747. if (*errorHandler == NULL) {
  7748. *errorHandler = PyCodec_LookupError(errors);
  7749. if (*errorHandler == NULL)
  7750. return NULL;
  7751. }
  7752. make_translate_exception(exceptionObject,
  7753. unicode, startpos, endpos, reason);
  7754. if (*exceptionObject == NULL)
  7755. return NULL;
  7756. restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
  7757. if (restuple == NULL)
  7758. return NULL;
  7759. if (!PyTuple_Check(restuple)) {
  7760. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  7761. Py_DECREF(restuple);
  7762. return NULL;
  7763. }
  7764. if (!PyArg_ParseTuple(restuple, argparse,
  7765. &resunicode, &i_newpos)) {
  7766. Py_DECREF(restuple);
  7767. return NULL;
  7768. }
  7769. if (i_newpos<0)
  7770. *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
  7771. else
  7772. *newpos = i_newpos;
  7773. if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
  7774. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
  7775. Py_DECREF(restuple);
  7776. return NULL;
  7777. }
  7778. Py_INCREF(resunicode);
  7779. Py_DECREF(restuple);
  7780. return resunicode;
  7781. }
  7782. /* Lookup the character ch in the mapping and put the result in result,
  7783. which must be decrefed by the caller.
  7784. Return 0 on success, -1 on error */
  7785. static int
  7786. charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
  7787. {
  7788. PyObject *w = PyLong_FromLong((long)c);
  7789. PyObject *x;
  7790. if (w == NULL)
  7791. return -1;
  7792. x = PyObject_GetItem(mapping, w);
  7793. Py_DECREF(w);
  7794. if (x == NULL) {
  7795. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  7796. /* No mapping found means: use 1:1 mapping. */
  7797. PyErr_Clear();
  7798. *result = NULL;
  7799. return 0;
  7800. } else
  7801. return -1;
  7802. }
  7803. else if (x == Py_None) {
  7804. *result = x;
  7805. return 0;
  7806. }
  7807. else if (PyLong_Check(x)) {
  7808. long value = PyLong_AS_LONG(x);
  7809. if (value < 0 || value > MAX_UNICODE) {
  7810. PyErr_Format(PyExc_ValueError,
  7811. "character mapping must be in range(0x%x)",
  7812. MAX_UNICODE+1);
  7813. Py_DECREF(x);
  7814. return -1;
  7815. }
  7816. *result = x;
  7817. return 0;
  7818. }
  7819. else if (PyUnicode_Check(x)) {
  7820. *result = x;
  7821. return 0;
  7822. }
  7823. else {
  7824. /* wrong return value */
  7825. PyErr_SetString(PyExc_TypeError,
  7826. "character mapping must return integer, None or str");
  7827. Py_DECREF(x);
  7828. return -1;
  7829. }
  7830. }
  7831. /* lookup the character, write the result into the writer.
  7832. Return 1 if the result was written into the writer, return 0 if the mapping
  7833. was undefined, raise an exception return -1 on error. */
  7834. static int
  7835. charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
  7836. _PyUnicodeWriter *writer)
  7837. {
  7838. PyObject *item;
  7839. if (charmaptranslate_lookup(ch, mapping, &item))
  7840. return -1;
  7841. if (item == NULL) {
  7842. /* not found => default to 1:1 mapping */
  7843. if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
  7844. return -1;
  7845. }
  7846. return 1;
  7847. }
  7848. if (item == Py_None) {
  7849. Py_DECREF(item);
  7850. return 0;
  7851. }
  7852. if (PyLong_Check(item)) {
  7853. long ch = (Py_UCS4)PyLong_AS_LONG(item);
  7854. /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
  7855. used it */
  7856. if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
  7857. Py_DECREF(item);
  7858. return -1;
  7859. }
  7860. Py_DECREF(item);
  7861. return 1;
  7862. }
  7863. if (!PyUnicode_Check(item)) {
  7864. Py_DECREF(item);
  7865. return -1;
  7866. }
  7867. if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
  7868. Py_DECREF(item);
  7869. return -1;
  7870. }
  7871. Py_DECREF(item);
  7872. return 1;
  7873. }
  7874. static int
  7875. unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
  7876. Py_UCS1 *translate)
  7877. {
  7878. PyObject *item = NULL;
  7879. int ret = 0;
  7880. if (charmaptranslate_lookup(ch, mapping, &item)) {
  7881. return -1;
  7882. }
  7883. if (item == Py_None) {
  7884. /* deletion */
  7885. translate[ch] = 0xfe;
  7886. }
  7887. else if (item == NULL) {
  7888. /* not found => default to 1:1 mapping */
  7889. translate[ch] = ch;
  7890. return 1;
  7891. }
  7892. else if (PyLong_Check(item)) {
  7893. long replace = PyLong_AS_LONG(item);
  7894. /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
  7895. used it */
  7896. if (127 < replace) {
  7897. /* invalid character or character outside ASCII:
  7898. skip the fast translate */
  7899. goto exit;
  7900. }
  7901. translate[ch] = (Py_UCS1)replace;
  7902. }
  7903. else if (PyUnicode_Check(item)) {
  7904. Py_UCS4 replace;
  7905. if (PyUnicode_GET_LENGTH(item) != 1)
  7906. goto exit;
  7907. replace = PyUnicode_READ_CHAR(item, 0);
  7908. if (replace > 127)
  7909. goto exit;
  7910. translate[ch] = (Py_UCS1)replace;
  7911. }
  7912. else {
  7913. /* not None, NULL, long or unicode */
  7914. goto exit;
  7915. }
  7916. ret = 1;
  7917. exit:
  7918. Py_DECREF(item);
  7919. return ret;
  7920. }
  7921. /* Fast path for ascii => ascii translation. Return 1 if the whole string
  7922. was translated into writer, return 0 if the input string was partially
  7923. translated into writer, raise an exception and return -1 on error. */
  7924. static int
  7925. unicode_fast_translate(PyObject *input, PyObject *mapping,
  7926. _PyUnicodeWriter *writer, int ignore,
  7927. Py_ssize_t *input_pos)
  7928. {
  7929. Py_UCS1 ascii_table[128], ch, ch2;
  7930. Py_ssize_t len;
  7931. const Py_UCS1 *in, *end;
  7932. Py_UCS1 *out;
  7933. int res = 0;
  7934. len = PyUnicode_GET_LENGTH(input);
  7935. memset(ascii_table, 0xff, 128);
  7936. in = PyUnicode_1BYTE_DATA(input);
  7937. end = in + len;
  7938. assert(PyUnicode_IS_ASCII(writer->buffer));
  7939. assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
  7940. out = PyUnicode_1BYTE_DATA(writer->buffer);
  7941. for (; in < end; in++) {
  7942. ch = *in;
  7943. ch2 = ascii_table[ch];
  7944. if (ch2 == 0xff) {
  7945. int translate = unicode_fast_translate_lookup(mapping, ch,
  7946. ascii_table);
  7947. if (translate < 0)
  7948. return -1;
  7949. if (translate == 0)
  7950. goto exit;
  7951. ch2 = ascii_table[ch];
  7952. }
  7953. if (ch2 == 0xfe) {
  7954. if (ignore)
  7955. continue;
  7956. goto exit;
  7957. }
  7958. assert(ch2 < 128);
  7959. *out = ch2;
  7960. out++;
  7961. }
  7962. res = 1;
  7963. exit:
  7964. writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
  7965. *input_pos = in - PyUnicode_1BYTE_DATA(input);
  7966. return res;
  7967. }
  7968. static PyObject *
  7969. _PyUnicode_TranslateCharmap(PyObject *input,
  7970. PyObject *mapping,
  7971. const char *errors)
  7972. {
  7973. /* input object */
  7974. const void *data;
  7975. Py_ssize_t size, i;
  7976. int kind;
  7977. /* output buffer */
  7978. _PyUnicodeWriter writer;
  7979. /* error handler */
  7980. const char *reason = "character maps to <undefined>";
  7981. PyObject *errorHandler = NULL;
  7982. PyObject *exc = NULL;
  7983. int ignore;
  7984. int res;
  7985. if (mapping == NULL) {
  7986. PyErr_BadArgument();
  7987. return NULL;
  7988. }
  7989. data = PyUnicode_DATA(input);
  7990. kind = PyUnicode_KIND(input);
  7991. size = PyUnicode_GET_LENGTH(input);
  7992. if (size == 0)
  7993. return PyUnicode_FromObject(input);
  7994. /* allocate enough for a simple 1:1 translation without
  7995. replacements, if we need more, we'll resize */
  7996. _PyUnicodeWriter_Init(&writer);
  7997. if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
  7998. goto onError;
  7999. ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
  8000. if (PyUnicode_IS_ASCII(input)) {
  8001. res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
  8002. if (res < 0) {
  8003. _PyUnicodeWriter_Dealloc(&writer);
  8004. return NULL;
  8005. }
  8006. if (res == 1)
  8007. return _PyUnicodeWriter_Finish(&writer);
  8008. }
  8009. else {
  8010. i = 0;
  8011. }
  8012. while (i<size) {
  8013. /* try to encode it */
  8014. int translate;
  8015. PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
  8016. Py_ssize_t newpos;
  8017. /* startpos for collecting untranslatable chars */
  8018. Py_ssize_t collstart;
  8019. Py_ssize_t collend;
  8020. Py_UCS4 ch;
  8021. ch = PyUnicode_READ(kind, data, i);
  8022. translate = charmaptranslate_output(ch, mapping, &writer);
  8023. if (translate < 0)
  8024. goto onError;
  8025. if (translate != 0) {
  8026. /* it worked => adjust input pointer */
  8027. ++i;
  8028. continue;
  8029. }
  8030. /* untranslatable character */
  8031. collstart = i;
  8032. collend = i+1;
  8033. /* find all untranslatable characters */
  8034. while (collend < size) {
  8035. PyObject *x;
  8036. ch = PyUnicode_READ(kind, data, collend);
  8037. if (charmaptranslate_lookup(ch, mapping, &x))
  8038. goto onError;
  8039. Py_XDECREF(x);
  8040. if (x != Py_None)
  8041. break;
  8042. ++collend;
  8043. }
  8044. if (ignore) {
  8045. i = collend;
  8046. }
  8047. else {
  8048. repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
  8049. reason, input, &exc,
  8050. collstart, collend, &newpos);
  8051. if (repunicode == NULL)
  8052. goto onError;
  8053. if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
  8054. Py_DECREF(repunicode);
  8055. goto onError;
  8056. }
  8057. Py_DECREF(repunicode);
  8058. i = newpos;
  8059. }
  8060. }
  8061. Py_XDECREF(exc);
  8062. Py_XDECREF(errorHandler);
  8063. return _PyUnicodeWriter_Finish(&writer);
  8064. onError:
  8065. _PyUnicodeWriter_Dealloc(&writer);
  8066. Py_XDECREF(exc);
  8067. Py_XDECREF(errorHandler);
  8068. return NULL;
  8069. }
  8070. PyObject *
  8071. PyUnicode_Translate(PyObject *str,
  8072. PyObject *mapping,
  8073. const char *errors)
  8074. {
  8075. if (ensure_unicode(str) < 0)
  8076. return NULL;
  8077. return _PyUnicode_TranslateCharmap(str, mapping, errors);
  8078. }
  8079. PyObject *
  8080. _PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
  8081. {
  8082. if (!PyUnicode_Check(unicode)) {
  8083. PyErr_BadInternalCall();
  8084. return NULL;
  8085. }
  8086. if (PyUnicode_IS_ASCII(unicode)) {
  8087. /* If the string is already ASCII, just return the same string */
  8088. return Py_NewRef(unicode);
  8089. }
  8090. Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
  8091. PyObject *result = PyUnicode_New(len, 127);
  8092. if (result == NULL) {
  8093. return NULL;
  8094. }
  8095. Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
  8096. int kind = PyUnicode_KIND(unicode);
  8097. const void *data = PyUnicode_DATA(unicode);
  8098. Py_ssize_t i;
  8099. for (i = 0; i < len; ++i) {
  8100. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  8101. if (ch < 127) {
  8102. out[i] = ch;
  8103. }
  8104. else if (Py_UNICODE_ISSPACE(ch)) {
  8105. out[i] = ' ';
  8106. }
  8107. else {
  8108. int decimal = Py_UNICODE_TODECIMAL(ch);
  8109. if (decimal < 0) {
  8110. out[i] = '?';
  8111. out[i+1] = '\0';
  8112. _PyUnicode_LENGTH(result) = i + 1;
  8113. break;
  8114. }
  8115. out[i] = '0' + decimal;
  8116. }
  8117. }
  8118. assert(_PyUnicode_CheckConsistency(result, 1));
  8119. return result;
  8120. }
  8121. /* --- Helpers ------------------------------------------------------------ */
  8122. /* helper macro to fixup start/end slice values */
  8123. #define ADJUST_INDICES(start, end, len) \
  8124. if (end > len) \
  8125. end = len; \
  8126. else if (end < 0) { \
  8127. end += len; \
  8128. if (end < 0) \
  8129. end = 0; \
  8130. } \
  8131. if (start < 0) { \
  8132. start += len; \
  8133. if (start < 0) \
  8134. start = 0; \
  8135. }
  8136. static Py_ssize_t
  8137. any_find_slice(PyObject* s1, PyObject* s2,
  8138. Py_ssize_t start,
  8139. Py_ssize_t end,
  8140. int direction)
  8141. {
  8142. int kind1, kind2;
  8143. const void *buf1, *buf2;
  8144. Py_ssize_t len1, len2, result;
  8145. kind1 = PyUnicode_KIND(s1);
  8146. kind2 = PyUnicode_KIND(s2);
  8147. if (kind1 < kind2)
  8148. return -1;
  8149. len1 = PyUnicode_GET_LENGTH(s1);
  8150. len2 = PyUnicode_GET_LENGTH(s2);
  8151. ADJUST_INDICES(start, end, len1);
  8152. if (end - start < len2)
  8153. return -1;
  8154. buf1 = PyUnicode_DATA(s1);
  8155. buf2 = PyUnicode_DATA(s2);
  8156. if (len2 == 1) {
  8157. Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
  8158. result = findchar((const char *)buf1 + kind1*start,
  8159. kind1, end - start, ch, direction);
  8160. if (result == -1)
  8161. return -1;
  8162. else
  8163. return start + result;
  8164. }
  8165. if (kind2 != kind1) {
  8166. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  8167. if (!buf2)
  8168. return -2;
  8169. }
  8170. if (direction > 0) {
  8171. switch (kind1) {
  8172. case PyUnicode_1BYTE_KIND:
  8173. if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
  8174. result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
  8175. else
  8176. result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
  8177. break;
  8178. case PyUnicode_2BYTE_KIND:
  8179. result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
  8180. break;
  8181. case PyUnicode_4BYTE_KIND:
  8182. result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
  8183. break;
  8184. default:
  8185. Py_UNREACHABLE();
  8186. }
  8187. }
  8188. else {
  8189. switch (kind1) {
  8190. case PyUnicode_1BYTE_KIND:
  8191. if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
  8192. result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
  8193. else
  8194. result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
  8195. break;
  8196. case PyUnicode_2BYTE_KIND:
  8197. result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
  8198. break;
  8199. case PyUnicode_4BYTE_KIND:
  8200. result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
  8201. break;
  8202. default:
  8203. Py_UNREACHABLE();
  8204. }
  8205. }
  8206. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(s2)));
  8207. if (kind2 != kind1)
  8208. PyMem_Free((void *)buf2);
  8209. return result;
  8210. }
  8211. /* _PyUnicode_InsertThousandsGrouping() helper functions */
  8212. #include "stringlib/localeutil.h"
  8213. /**
  8214. * InsertThousandsGrouping:
  8215. * @writer: Unicode writer.
  8216. * @n_buffer: Number of characters in @buffer.
  8217. * @digits: Digits we're reading from. If count is non-NULL, this is unused.
  8218. * @d_pos: Start of digits string.
  8219. * @n_digits: The number of digits in the string, in which we want
  8220. * to put the grouping chars.
  8221. * @min_width: The minimum width of the digits in the output string.
  8222. * Output will be zero-padded on the left to fill.
  8223. * @grouping: see definition in localeconv().
  8224. * @thousands_sep: see definition in localeconv().
  8225. *
  8226. * There are 2 modes: counting and filling. If @writer is NULL,
  8227. * we are in counting mode, else filling mode.
  8228. * If counting, the required buffer size is returned.
  8229. * If filling, we know the buffer will be large enough, so we don't
  8230. * need to pass in the buffer size.
  8231. * Inserts thousand grouping characters (as defined by grouping and
  8232. * thousands_sep) into @writer.
  8233. *
  8234. * Return value: -1 on error, number of characters otherwise.
  8235. **/
  8236. Py_ssize_t
  8237. _PyUnicode_InsertThousandsGrouping(
  8238. _PyUnicodeWriter *writer,
  8239. Py_ssize_t n_buffer,
  8240. PyObject *digits,
  8241. Py_ssize_t d_pos,
  8242. Py_ssize_t n_digits,
  8243. Py_ssize_t min_width,
  8244. const char *grouping,
  8245. PyObject *thousands_sep,
  8246. Py_UCS4 *maxchar)
  8247. {
  8248. min_width = Py_MAX(0, min_width);
  8249. if (writer) {
  8250. assert(digits != NULL);
  8251. assert(maxchar == NULL);
  8252. }
  8253. else {
  8254. assert(digits == NULL);
  8255. assert(maxchar != NULL);
  8256. }
  8257. assert(0 <= d_pos);
  8258. assert(0 <= n_digits);
  8259. assert(grouping != NULL);
  8260. Py_ssize_t count = 0;
  8261. Py_ssize_t n_zeros;
  8262. int loop_broken = 0;
  8263. int use_separator = 0; /* First time through, don't append the
  8264. separator. They only go between
  8265. groups. */
  8266. Py_ssize_t buffer_pos;
  8267. Py_ssize_t digits_pos;
  8268. Py_ssize_t len;
  8269. Py_ssize_t n_chars;
  8270. Py_ssize_t remaining = n_digits; /* Number of chars remaining to
  8271. be looked at */
  8272. /* A generator that returns all of the grouping widths, until it
  8273. returns 0. */
  8274. GroupGenerator groupgen;
  8275. GroupGenerator_init(&groupgen, grouping);
  8276. const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
  8277. /* if digits are not grouped, thousands separator
  8278. should be an empty string */
  8279. assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
  8280. digits_pos = d_pos + n_digits;
  8281. if (writer) {
  8282. buffer_pos = writer->pos + n_buffer;
  8283. assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
  8284. assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
  8285. }
  8286. else {
  8287. buffer_pos = n_buffer;
  8288. }
  8289. if (!writer) {
  8290. *maxchar = 127;
  8291. }
  8292. while ((len = GroupGenerator_next(&groupgen)) > 0) {
  8293. len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1));
  8294. n_zeros = Py_MAX(0, len - remaining);
  8295. n_chars = Py_MAX(0, Py_MIN(remaining, len));
  8296. /* Use n_zero zero's and n_chars chars */
  8297. /* Count only, don't do anything. */
  8298. count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
  8299. /* Copy into the writer. */
  8300. InsertThousandsGrouping_fill(writer, &buffer_pos,
  8301. digits, &digits_pos,
  8302. n_chars, n_zeros,
  8303. use_separator ? thousands_sep : NULL,
  8304. thousands_sep_len, maxchar);
  8305. /* Use a separator next time. */
  8306. use_separator = 1;
  8307. remaining -= n_chars;
  8308. min_width -= len;
  8309. if (remaining <= 0 && min_width <= 0) {
  8310. loop_broken = 1;
  8311. break;
  8312. }
  8313. min_width -= thousands_sep_len;
  8314. }
  8315. if (!loop_broken) {
  8316. /* We left the loop without using a break statement. */
  8317. len = Py_MAX(Py_MAX(remaining, min_width), 1);
  8318. n_zeros = Py_MAX(0, len - remaining);
  8319. n_chars = Py_MAX(0, Py_MIN(remaining, len));
  8320. /* Use n_zero zero's and n_chars chars */
  8321. count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
  8322. /* Copy into the writer. */
  8323. InsertThousandsGrouping_fill(writer, &buffer_pos,
  8324. digits, &digits_pos,
  8325. n_chars, n_zeros,
  8326. use_separator ? thousands_sep : NULL,
  8327. thousands_sep_len, maxchar);
  8328. }
  8329. return count;
  8330. }
  8331. static Py_ssize_t
  8332. unicode_count_impl(PyObject *str,
  8333. PyObject *substr,
  8334. Py_ssize_t start,
  8335. Py_ssize_t end)
  8336. {
  8337. assert(PyUnicode_Check(str));
  8338. assert(PyUnicode_Check(substr));
  8339. Py_ssize_t result;
  8340. int kind1, kind2;
  8341. const void *buf1 = NULL, *buf2 = NULL;
  8342. Py_ssize_t len1, len2;
  8343. kind1 = PyUnicode_KIND(str);
  8344. kind2 = PyUnicode_KIND(substr);
  8345. if (kind1 < kind2)
  8346. return 0;
  8347. len1 = PyUnicode_GET_LENGTH(str);
  8348. len2 = PyUnicode_GET_LENGTH(substr);
  8349. ADJUST_INDICES(start, end, len1);
  8350. if (end - start < len2)
  8351. return 0;
  8352. buf1 = PyUnicode_DATA(str);
  8353. buf2 = PyUnicode_DATA(substr);
  8354. if (kind2 != kind1) {
  8355. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  8356. if (!buf2)
  8357. goto onError;
  8358. }
  8359. // We don't reuse `anylib_count` here because of the explicit casts.
  8360. switch (kind1) {
  8361. case PyUnicode_1BYTE_KIND:
  8362. result = ucs1lib_count(
  8363. ((const Py_UCS1*)buf1) + start, end - start,
  8364. buf2, len2, PY_SSIZE_T_MAX
  8365. );
  8366. break;
  8367. case PyUnicode_2BYTE_KIND:
  8368. result = ucs2lib_count(
  8369. ((const Py_UCS2*)buf1) + start, end - start,
  8370. buf2, len2, PY_SSIZE_T_MAX
  8371. );
  8372. break;
  8373. case PyUnicode_4BYTE_KIND:
  8374. result = ucs4lib_count(
  8375. ((const Py_UCS4*)buf1) + start, end - start,
  8376. buf2, len2, PY_SSIZE_T_MAX
  8377. );
  8378. break;
  8379. default:
  8380. Py_UNREACHABLE();
  8381. }
  8382. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
  8383. if (kind2 != kind1)
  8384. PyMem_Free((void *)buf2);
  8385. return result;
  8386. onError:
  8387. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
  8388. if (kind2 != kind1)
  8389. PyMem_Free((void *)buf2);
  8390. return -1;
  8391. }
  8392. Py_ssize_t
  8393. PyUnicode_Count(PyObject *str,
  8394. PyObject *substr,
  8395. Py_ssize_t start,
  8396. Py_ssize_t end)
  8397. {
  8398. if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
  8399. return -1;
  8400. return unicode_count_impl(str, substr, start, end);
  8401. }
  8402. Py_ssize_t
  8403. PyUnicode_Find(PyObject *str,
  8404. PyObject *substr,
  8405. Py_ssize_t start,
  8406. Py_ssize_t end,
  8407. int direction)
  8408. {
  8409. if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
  8410. return -2;
  8411. return any_find_slice(str, substr, start, end, direction);
  8412. }
  8413. Py_ssize_t
  8414. PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
  8415. Py_ssize_t start, Py_ssize_t end,
  8416. int direction)
  8417. {
  8418. int kind;
  8419. Py_ssize_t len, result;
  8420. len = PyUnicode_GET_LENGTH(str);
  8421. ADJUST_INDICES(start, end, len);
  8422. if (end - start < 1)
  8423. return -1;
  8424. kind = PyUnicode_KIND(str);
  8425. result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
  8426. kind, end-start, ch, direction);
  8427. if (result == -1)
  8428. return -1;
  8429. else
  8430. return start + result;
  8431. }
  8432. static int
  8433. tailmatch(PyObject *self,
  8434. PyObject *substring,
  8435. Py_ssize_t start,
  8436. Py_ssize_t end,
  8437. int direction)
  8438. {
  8439. int kind_self;
  8440. int kind_sub;
  8441. const void *data_self;
  8442. const void *data_sub;
  8443. Py_ssize_t offset;
  8444. Py_ssize_t i;
  8445. Py_ssize_t end_sub;
  8446. ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
  8447. end -= PyUnicode_GET_LENGTH(substring);
  8448. if (end < start)
  8449. return 0;
  8450. if (PyUnicode_GET_LENGTH(substring) == 0)
  8451. return 1;
  8452. kind_self = PyUnicode_KIND(self);
  8453. data_self = PyUnicode_DATA(self);
  8454. kind_sub = PyUnicode_KIND(substring);
  8455. data_sub = PyUnicode_DATA(substring);
  8456. end_sub = PyUnicode_GET_LENGTH(substring) - 1;
  8457. if (direction > 0)
  8458. offset = end;
  8459. else
  8460. offset = start;
  8461. if (PyUnicode_READ(kind_self, data_self, offset) ==
  8462. PyUnicode_READ(kind_sub, data_sub, 0) &&
  8463. PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
  8464. PyUnicode_READ(kind_sub, data_sub, end_sub)) {
  8465. /* If both are of the same kind, memcmp is sufficient */
  8466. if (kind_self == kind_sub) {
  8467. return ! memcmp((char *)data_self +
  8468. (offset * PyUnicode_KIND(substring)),
  8469. data_sub,
  8470. PyUnicode_GET_LENGTH(substring) *
  8471. PyUnicode_KIND(substring));
  8472. }
  8473. /* otherwise we have to compare each character by first accessing it */
  8474. else {
  8475. /* We do not need to compare 0 and len(substring)-1 because
  8476. the if statement above ensured already that they are equal
  8477. when we end up here. */
  8478. for (i = 1; i < end_sub; ++i) {
  8479. if (PyUnicode_READ(kind_self, data_self, offset + i) !=
  8480. PyUnicode_READ(kind_sub, data_sub, i))
  8481. return 0;
  8482. }
  8483. return 1;
  8484. }
  8485. }
  8486. return 0;
  8487. }
  8488. Py_ssize_t
  8489. PyUnicode_Tailmatch(PyObject *str,
  8490. PyObject *substr,
  8491. Py_ssize_t start,
  8492. Py_ssize_t end,
  8493. int direction)
  8494. {
  8495. if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
  8496. return -1;
  8497. return tailmatch(str, substr, start, end, direction);
  8498. }
  8499. static PyObject *
  8500. ascii_upper_or_lower(PyObject *self, int lower)
  8501. {
  8502. Py_ssize_t len = PyUnicode_GET_LENGTH(self);
  8503. const char *data = PyUnicode_DATA(self);
  8504. char *resdata;
  8505. PyObject *res;
  8506. res = PyUnicode_New(len, 127);
  8507. if (res == NULL)
  8508. return NULL;
  8509. resdata = PyUnicode_DATA(res);
  8510. if (lower)
  8511. _Py_bytes_lower(resdata, data, len);
  8512. else
  8513. _Py_bytes_upper(resdata, data, len);
  8514. return res;
  8515. }
  8516. static Py_UCS4
  8517. handle_capital_sigma(int kind, const void *data, Py_ssize_t length, Py_ssize_t i)
  8518. {
  8519. Py_ssize_t j;
  8520. int final_sigma;
  8521. Py_UCS4 c = 0; /* initialize to prevent gcc warning */
  8522. /* U+03A3 is in the Final_Sigma context when, it is found like this:
  8523. \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
  8524. where ! is a negation and \p{xxx} is a character with property xxx.
  8525. */
  8526. for (j = i - 1; j >= 0; j--) {
  8527. c = PyUnicode_READ(kind, data, j);
  8528. if (!_PyUnicode_IsCaseIgnorable(c))
  8529. break;
  8530. }
  8531. final_sigma = j >= 0 && _PyUnicode_IsCased(c);
  8532. if (final_sigma) {
  8533. for (j = i + 1; j < length; j++) {
  8534. c = PyUnicode_READ(kind, data, j);
  8535. if (!_PyUnicode_IsCaseIgnorable(c))
  8536. break;
  8537. }
  8538. final_sigma = j == length || !_PyUnicode_IsCased(c);
  8539. }
  8540. return (final_sigma) ? 0x3C2 : 0x3C3;
  8541. }
  8542. static int
  8543. lower_ucs4(int kind, const void *data, Py_ssize_t length, Py_ssize_t i,
  8544. Py_UCS4 c, Py_UCS4 *mapped)
  8545. {
  8546. /* Obscure special case. */
  8547. if (c == 0x3A3) {
  8548. mapped[0] = handle_capital_sigma(kind, data, length, i);
  8549. return 1;
  8550. }
  8551. return _PyUnicode_ToLowerFull(c, mapped);
  8552. }
  8553. static Py_ssize_t
  8554. do_capitalize(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8555. {
  8556. Py_ssize_t i, k = 0;
  8557. int n_res, j;
  8558. Py_UCS4 c, mapped[3];
  8559. c = PyUnicode_READ(kind, data, 0);
  8560. n_res = _PyUnicode_ToTitleFull(c, mapped);
  8561. for (j = 0; j < n_res; j++) {
  8562. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8563. res[k++] = mapped[j];
  8564. }
  8565. for (i = 1; i < length; i++) {
  8566. c = PyUnicode_READ(kind, data, i);
  8567. n_res = lower_ucs4(kind, data, length, i, c, mapped);
  8568. for (j = 0; j < n_res; j++) {
  8569. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8570. res[k++] = mapped[j];
  8571. }
  8572. }
  8573. return k;
  8574. }
  8575. static Py_ssize_t
  8576. do_swapcase(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
  8577. Py_ssize_t i, k = 0;
  8578. for (i = 0; i < length; i++) {
  8579. Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
  8580. int n_res, j;
  8581. if (Py_UNICODE_ISUPPER(c)) {
  8582. n_res = lower_ucs4(kind, data, length, i, c, mapped);
  8583. }
  8584. else if (Py_UNICODE_ISLOWER(c)) {
  8585. n_res = _PyUnicode_ToUpperFull(c, mapped);
  8586. }
  8587. else {
  8588. n_res = 1;
  8589. mapped[0] = c;
  8590. }
  8591. for (j = 0; j < n_res; j++) {
  8592. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8593. res[k++] = mapped[j];
  8594. }
  8595. }
  8596. return k;
  8597. }
  8598. static Py_ssize_t
  8599. do_upper_or_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res,
  8600. Py_UCS4 *maxchar, int lower)
  8601. {
  8602. Py_ssize_t i, k = 0;
  8603. for (i = 0; i < length; i++) {
  8604. Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
  8605. int n_res, j;
  8606. if (lower)
  8607. n_res = lower_ucs4(kind, data, length, i, c, mapped);
  8608. else
  8609. n_res = _PyUnicode_ToUpperFull(c, mapped);
  8610. for (j = 0; j < n_res; j++) {
  8611. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8612. res[k++] = mapped[j];
  8613. }
  8614. }
  8615. return k;
  8616. }
  8617. static Py_ssize_t
  8618. do_upper(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8619. {
  8620. return do_upper_or_lower(kind, data, length, res, maxchar, 0);
  8621. }
  8622. static Py_ssize_t
  8623. do_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8624. {
  8625. return do_upper_or_lower(kind, data, length, res, maxchar, 1);
  8626. }
  8627. static Py_ssize_t
  8628. do_casefold(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8629. {
  8630. Py_ssize_t i, k = 0;
  8631. for (i = 0; i < length; i++) {
  8632. Py_UCS4 c = PyUnicode_READ(kind, data, i);
  8633. Py_UCS4 mapped[3];
  8634. int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
  8635. for (j = 0; j < n_res; j++) {
  8636. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8637. res[k++] = mapped[j];
  8638. }
  8639. }
  8640. return k;
  8641. }
  8642. static Py_ssize_t
  8643. do_title(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8644. {
  8645. Py_ssize_t i, k = 0;
  8646. int previous_is_cased;
  8647. previous_is_cased = 0;
  8648. for (i = 0; i < length; i++) {
  8649. const Py_UCS4 c = PyUnicode_READ(kind, data, i);
  8650. Py_UCS4 mapped[3];
  8651. int n_res, j;
  8652. if (previous_is_cased)
  8653. n_res = lower_ucs4(kind, data, length, i, c, mapped);
  8654. else
  8655. n_res = _PyUnicode_ToTitleFull(c, mapped);
  8656. for (j = 0; j < n_res; j++) {
  8657. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8658. res[k++] = mapped[j];
  8659. }
  8660. previous_is_cased = _PyUnicode_IsCased(c);
  8661. }
  8662. return k;
  8663. }
  8664. static PyObject *
  8665. case_operation(PyObject *self,
  8666. Py_ssize_t (*perform)(int, const void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
  8667. {
  8668. PyObject *res = NULL;
  8669. Py_ssize_t length, newlength = 0;
  8670. int kind, outkind;
  8671. const void *data;
  8672. void *outdata;
  8673. Py_UCS4 maxchar = 0, *tmp, *tmpend;
  8674. kind = PyUnicode_KIND(self);
  8675. data = PyUnicode_DATA(self);
  8676. length = PyUnicode_GET_LENGTH(self);
  8677. if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
  8678. PyErr_SetString(PyExc_OverflowError, "string is too long");
  8679. return NULL;
  8680. }
  8681. tmp = PyMem_Malloc(sizeof(Py_UCS4) * 3 * length);
  8682. if (tmp == NULL)
  8683. return PyErr_NoMemory();
  8684. newlength = perform(kind, data, length, tmp, &maxchar);
  8685. res = PyUnicode_New(newlength, maxchar);
  8686. if (res == NULL)
  8687. goto leave;
  8688. tmpend = tmp + newlength;
  8689. outdata = PyUnicode_DATA(res);
  8690. outkind = PyUnicode_KIND(res);
  8691. switch (outkind) {
  8692. case PyUnicode_1BYTE_KIND:
  8693. _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
  8694. break;
  8695. case PyUnicode_2BYTE_KIND:
  8696. _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
  8697. break;
  8698. case PyUnicode_4BYTE_KIND:
  8699. memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
  8700. break;
  8701. default:
  8702. Py_UNREACHABLE();
  8703. }
  8704. leave:
  8705. PyMem_Free(tmp);
  8706. return res;
  8707. }
  8708. PyObject *
  8709. PyUnicode_Join(PyObject *separator, PyObject *seq)
  8710. {
  8711. PyObject *res;
  8712. PyObject *fseq;
  8713. Py_ssize_t seqlen;
  8714. PyObject **items;
  8715. fseq = PySequence_Fast(seq, "can only join an iterable");
  8716. if (fseq == NULL) {
  8717. return NULL;
  8718. }
  8719. /* NOTE: the following code can't call back into Python code,
  8720. * so we are sure that fseq won't be mutated.
  8721. */
  8722. items = PySequence_Fast_ITEMS(fseq);
  8723. seqlen = PySequence_Fast_GET_SIZE(fseq);
  8724. res = _PyUnicode_JoinArray(separator, items, seqlen);
  8725. Py_DECREF(fseq);
  8726. return res;
  8727. }
  8728. PyObject *
  8729. _PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
  8730. {
  8731. PyObject *res = NULL; /* the result */
  8732. PyObject *sep = NULL;
  8733. Py_ssize_t seplen;
  8734. PyObject *item;
  8735. Py_ssize_t sz, i, res_offset;
  8736. Py_UCS4 maxchar;
  8737. Py_UCS4 item_maxchar;
  8738. int use_memcpy;
  8739. unsigned char *res_data = NULL, *sep_data = NULL;
  8740. PyObject *last_obj;
  8741. int kind = 0;
  8742. /* If empty sequence, return u"". */
  8743. if (seqlen == 0) {
  8744. _Py_RETURN_UNICODE_EMPTY();
  8745. }
  8746. /* If singleton sequence with an exact Unicode, return that. */
  8747. last_obj = NULL;
  8748. if (seqlen == 1) {
  8749. if (PyUnicode_CheckExact(items[0])) {
  8750. res = items[0];
  8751. return Py_NewRef(res);
  8752. }
  8753. seplen = 0;
  8754. maxchar = 0;
  8755. }
  8756. else {
  8757. /* Set up sep and seplen */
  8758. if (separator == NULL) {
  8759. /* fall back to a blank space separator */
  8760. sep = PyUnicode_FromOrdinal(' ');
  8761. if (!sep)
  8762. goto onError;
  8763. seplen = 1;
  8764. maxchar = 32;
  8765. }
  8766. else {
  8767. if (!PyUnicode_Check(separator)) {
  8768. PyErr_Format(PyExc_TypeError,
  8769. "separator: expected str instance,"
  8770. " %.80s found",
  8771. Py_TYPE(separator)->tp_name);
  8772. goto onError;
  8773. }
  8774. sep = separator;
  8775. seplen = PyUnicode_GET_LENGTH(separator);
  8776. maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
  8777. /* inc refcount to keep this code path symmetric with the
  8778. above case of a blank separator */
  8779. Py_INCREF(sep);
  8780. }
  8781. last_obj = sep;
  8782. }
  8783. /* There are at least two things to join, or else we have a subclass
  8784. * of str in the sequence.
  8785. * Do a pre-pass to figure out the total amount of space we'll
  8786. * need (sz), and see whether all argument are strings.
  8787. */
  8788. sz = 0;
  8789. #ifdef Py_DEBUG
  8790. use_memcpy = 0;
  8791. #else
  8792. use_memcpy = 1;
  8793. #endif
  8794. for (i = 0; i < seqlen; i++) {
  8795. size_t add_sz;
  8796. item = items[i];
  8797. if (!PyUnicode_Check(item)) {
  8798. PyErr_Format(PyExc_TypeError,
  8799. "sequence item %zd: expected str instance,"
  8800. " %.80s found",
  8801. i, Py_TYPE(item)->tp_name);
  8802. goto onError;
  8803. }
  8804. add_sz = PyUnicode_GET_LENGTH(item);
  8805. item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
  8806. maxchar = Py_MAX(maxchar, item_maxchar);
  8807. if (i != 0) {
  8808. add_sz += seplen;
  8809. }
  8810. if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
  8811. PyErr_SetString(PyExc_OverflowError,
  8812. "join() result is too long for a Python string");
  8813. goto onError;
  8814. }
  8815. sz += add_sz;
  8816. if (use_memcpy && last_obj != NULL) {
  8817. if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
  8818. use_memcpy = 0;
  8819. }
  8820. last_obj = item;
  8821. }
  8822. res = PyUnicode_New(sz, maxchar);
  8823. if (res == NULL)
  8824. goto onError;
  8825. /* Catenate everything. */
  8826. #ifdef Py_DEBUG
  8827. use_memcpy = 0;
  8828. #else
  8829. if (use_memcpy) {
  8830. res_data = PyUnicode_1BYTE_DATA(res);
  8831. kind = PyUnicode_KIND(res);
  8832. if (seplen != 0)
  8833. sep_data = PyUnicode_1BYTE_DATA(sep);
  8834. }
  8835. #endif
  8836. if (use_memcpy) {
  8837. for (i = 0; i < seqlen; ++i) {
  8838. Py_ssize_t itemlen;
  8839. item = items[i];
  8840. /* Copy item, and maybe the separator. */
  8841. if (i && seplen != 0) {
  8842. memcpy(res_data,
  8843. sep_data,
  8844. kind * seplen);
  8845. res_data += kind * seplen;
  8846. }
  8847. itemlen = PyUnicode_GET_LENGTH(item);
  8848. if (itemlen != 0) {
  8849. memcpy(res_data,
  8850. PyUnicode_DATA(item),
  8851. kind * itemlen);
  8852. res_data += kind * itemlen;
  8853. }
  8854. }
  8855. assert(res_data == PyUnicode_1BYTE_DATA(res)
  8856. + kind * PyUnicode_GET_LENGTH(res));
  8857. }
  8858. else {
  8859. for (i = 0, res_offset = 0; i < seqlen; ++i) {
  8860. Py_ssize_t itemlen;
  8861. item = items[i];
  8862. /* Copy item, and maybe the separator. */
  8863. if (i && seplen != 0) {
  8864. _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
  8865. res_offset += seplen;
  8866. }
  8867. itemlen = PyUnicode_GET_LENGTH(item);
  8868. if (itemlen != 0) {
  8869. _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
  8870. res_offset += itemlen;
  8871. }
  8872. }
  8873. assert(res_offset == PyUnicode_GET_LENGTH(res));
  8874. }
  8875. Py_XDECREF(sep);
  8876. assert(_PyUnicode_CheckConsistency(res, 1));
  8877. return res;
  8878. onError:
  8879. Py_XDECREF(sep);
  8880. Py_XDECREF(res);
  8881. return NULL;
  8882. }
  8883. void
  8884. _PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
  8885. Py_UCS4 fill_char)
  8886. {
  8887. const int kind = PyUnicode_KIND(unicode);
  8888. void *data = PyUnicode_DATA(unicode);
  8889. assert(unicode_modifiable(unicode));
  8890. assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
  8891. assert(start >= 0);
  8892. assert(start + length <= PyUnicode_GET_LENGTH(unicode));
  8893. unicode_fill(kind, data, fill_char, start, length);
  8894. }
  8895. Py_ssize_t
  8896. PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
  8897. Py_UCS4 fill_char)
  8898. {
  8899. Py_ssize_t maxlen;
  8900. if (!PyUnicode_Check(unicode)) {
  8901. PyErr_BadInternalCall();
  8902. return -1;
  8903. }
  8904. if (unicode_check_modifiable(unicode))
  8905. return -1;
  8906. if (start < 0) {
  8907. PyErr_SetString(PyExc_IndexError, "string index out of range");
  8908. return -1;
  8909. }
  8910. if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
  8911. PyErr_SetString(PyExc_ValueError,
  8912. "fill character is bigger than "
  8913. "the string maximum character");
  8914. return -1;
  8915. }
  8916. maxlen = PyUnicode_GET_LENGTH(unicode) - start;
  8917. length = Py_MIN(maxlen, length);
  8918. if (length <= 0)
  8919. return 0;
  8920. _PyUnicode_FastFill(unicode, start, length, fill_char);
  8921. return length;
  8922. }
  8923. static PyObject *
  8924. pad(PyObject *self,
  8925. Py_ssize_t left,
  8926. Py_ssize_t right,
  8927. Py_UCS4 fill)
  8928. {
  8929. PyObject *u;
  8930. Py_UCS4 maxchar;
  8931. int kind;
  8932. void *data;
  8933. if (left < 0)
  8934. left = 0;
  8935. if (right < 0)
  8936. right = 0;
  8937. if (left == 0 && right == 0)
  8938. return unicode_result_unchanged(self);
  8939. if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
  8940. right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
  8941. PyErr_SetString(PyExc_OverflowError, "padded string is too long");
  8942. return NULL;
  8943. }
  8944. maxchar = PyUnicode_MAX_CHAR_VALUE(self);
  8945. maxchar = Py_MAX(maxchar, fill);
  8946. u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
  8947. if (!u)
  8948. return NULL;
  8949. kind = PyUnicode_KIND(u);
  8950. data = PyUnicode_DATA(u);
  8951. if (left)
  8952. unicode_fill(kind, data, fill, 0, left);
  8953. if (right)
  8954. unicode_fill(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
  8955. _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
  8956. assert(_PyUnicode_CheckConsistency(u, 1));
  8957. return u;
  8958. }
  8959. PyObject *
  8960. PyUnicode_Splitlines(PyObject *string, int keepends)
  8961. {
  8962. PyObject *list;
  8963. if (ensure_unicode(string) < 0)
  8964. return NULL;
  8965. switch (PyUnicode_KIND(string)) {
  8966. case PyUnicode_1BYTE_KIND:
  8967. if (PyUnicode_IS_ASCII(string))
  8968. list = asciilib_splitlines(
  8969. string, PyUnicode_1BYTE_DATA(string),
  8970. PyUnicode_GET_LENGTH(string), keepends);
  8971. else
  8972. list = ucs1lib_splitlines(
  8973. string, PyUnicode_1BYTE_DATA(string),
  8974. PyUnicode_GET_LENGTH(string), keepends);
  8975. break;
  8976. case PyUnicode_2BYTE_KIND:
  8977. list = ucs2lib_splitlines(
  8978. string, PyUnicode_2BYTE_DATA(string),
  8979. PyUnicode_GET_LENGTH(string), keepends);
  8980. break;
  8981. case PyUnicode_4BYTE_KIND:
  8982. list = ucs4lib_splitlines(
  8983. string, PyUnicode_4BYTE_DATA(string),
  8984. PyUnicode_GET_LENGTH(string), keepends);
  8985. break;
  8986. default:
  8987. Py_UNREACHABLE();
  8988. }
  8989. return list;
  8990. }
  8991. static PyObject *
  8992. split(PyObject *self,
  8993. PyObject *substring,
  8994. Py_ssize_t maxcount)
  8995. {
  8996. int kind1, kind2;
  8997. const void *buf1, *buf2;
  8998. Py_ssize_t len1, len2;
  8999. PyObject* out;
  9000. len1 = PyUnicode_GET_LENGTH(self);
  9001. kind1 = PyUnicode_KIND(self);
  9002. if (substring == NULL) {
  9003. if (maxcount < 0) {
  9004. maxcount = (len1 - 1) / 2 + 1;
  9005. }
  9006. switch (kind1) {
  9007. case PyUnicode_1BYTE_KIND:
  9008. if (PyUnicode_IS_ASCII(self))
  9009. return asciilib_split_whitespace(
  9010. self, PyUnicode_1BYTE_DATA(self),
  9011. len1, maxcount
  9012. );
  9013. else
  9014. return ucs1lib_split_whitespace(
  9015. self, PyUnicode_1BYTE_DATA(self),
  9016. len1, maxcount
  9017. );
  9018. case PyUnicode_2BYTE_KIND:
  9019. return ucs2lib_split_whitespace(
  9020. self, PyUnicode_2BYTE_DATA(self),
  9021. len1, maxcount
  9022. );
  9023. case PyUnicode_4BYTE_KIND:
  9024. return ucs4lib_split_whitespace(
  9025. self, PyUnicode_4BYTE_DATA(self),
  9026. len1, maxcount
  9027. );
  9028. default:
  9029. Py_UNREACHABLE();
  9030. }
  9031. }
  9032. kind2 = PyUnicode_KIND(substring);
  9033. len2 = PyUnicode_GET_LENGTH(substring);
  9034. if (maxcount < 0) {
  9035. // if len2 == 0, it will raise ValueError.
  9036. maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
  9037. // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
  9038. maxcount = maxcount < 0 ? len1 : maxcount;
  9039. }
  9040. if (kind1 < kind2 || len1 < len2) {
  9041. out = PyList_New(1);
  9042. if (out == NULL)
  9043. return NULL;
  9044. PyList_SET_ITEM(out, 0, Py_NewRef(self));
  9045. return out;
  9046. }
  9047. buf1 = PyUnicode_DATA(self);
  9048. buf2 = PyUnicode_DATA(substring);
  9049. if (kind2 != kind1) {
  9050. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  9051. if (!buf2)
  9052. return NULL;
  9053. }
  9054. switch (kind1) {
  9055. case PyUnicode_1BYTE_KIND:
  9056. if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
  9057. out = asciilib_split(
  9058. self, buf1, len1, buf2, len2, maxcount);
  9059. else
  9060. out = ucs1lib_split(
  9061. self, buf1, len1, buf2, len2, maxcount);
  9062. break;
  9063. case PyUnicode_2BYTE_KIND:
  9064. out = ucs2lib_split(
  9065. self, buf1, len1, buf2, len2, maxcount);
  9066. break;
  9067. case PyUnicode_4BYTE_KIND:
  9068. out = ucs4lib_split(
  9069. self, buf1, len1, buf2, len2, maxcount);
  9070. break;
  9071. default:
  9072. out = NULL;
  9073. }
  9074. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
  9075. if (kind2 != kind1)
  9076. PyMem_Free((void *)buf2);
  9077. return out;
  9078. }
  9079. static PyObject *
  9080. rsplit(PyObject *self,
  9081. PyObject *substring,
  9082. Py_ssize_t maxcount)
  9083. {
  9084. int kind1, kind2;
  9085. const void *buf1, *buf2;
  9086. Py_ssize_t len1, len2;
  9087. PyObject* out;
  9088. len1 = PyUnicode_GET_LENGTH(self);
  9089. kind1 = PyUnicode_KIND(self);
  9090. if (substring == NULL) {
  9091. if (maxcount < 0) {
  9092. maxcount = (len1 - 1) / 2 + 1;
  9093. }
  9094. switch (kind1) {
  9095. case PyUnicode_1BYTE_KIND:
  9096. if (PyUnicode_IS_ASCII(self))
  9097. return asciilib_rsplit_whitespace(
  9098. self, PyUnicode_1BYTE_DATA(self),
  9099. len1, maxcount
  9100. );
  9101. else
  9102. return ucs1lib_rsplit_whitespace(
  9103. self, PyUnicode_1BYTE_DATA(self),
  9104. len1, maxcount
  9105. );
  9106. case PyUnicode_2BYTE_KIND:
  9107. return ucs2lib_rsplit_whitespace(
  9108. self, PyUnicode_2BYTE_DATA(self),
  9109. len1, maxcount
  9110. );
  9111. case PyUnicode_4BYTE_KIND:
  9112. return ucs4lib_rsplit_whitespace(
  9113. self, PyUnicode_4BYTE_DATA(self),
  9114. len1, maxcount
  9115. );
  9116. default:
  9117. Py_UNREACHABLE();
  9118. }
  9119. }
  9120. kind2 = PyUnicode_KIND(substring);
  9121. len2 = PyUnicode_GET_LENGTH(substring);
  9122. if (maxcount < 0) {
  9123. // if len2 == 0, it will raise ValueError.
  9124. maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
  9125. // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
  9126. maxcount = maxcount < 0 ? len1 : maxcount;
  9127. }
  9128. if (kind1 < kind2 || len1 < len2) {
  9129. out = PyList_New(1);
  9130. if (out == NULL)
  9131. return NULL;
  9132. PyList_SET_ITEM(out, 0, Py_NewRef(self));
  9133. return out;
  9134. }
  9135. buf1 = PyUnicode_DATA(self);
  9136. buf2 = PyUnicode_DATA(substring);
  9137. if (kind2 != kind1) {
  9138. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  9139. if (!buf2)
  9140. return NULL;
  9141. }
  9142. switch (kind1) {
  9143. case PyUnicode_1BYTE_KIND:
  9144. if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
  9145. out = asciilib_rsplit(
  9146. self, buf1, len1, buf2, len2, maxcount);
  9147. else
  9148. out = ucs1lib_rsplit(
  9149. self, buf1, len1, buf2, len2, maxcount);
  9150. break;
  9151. case PyUnicode_2BYTE_KIND:
  9152. out = ucs2lib_rsplit(
  9153. self, buf1, len1, buf2, len2, maxcount);
  9154. break;
  9155. case PyUnicode_4BYTE_KIND:
  9156. out = ucs4lib_rsplit(
  9157. self, buf1, len1, buf2, len2, maxcount);
  9158. break;
  9159. default:
  9160. out = NULL;
  9161. }
  9162. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
  9163. if (kind2 != kind1)
  9164. PyMem_Free((void *)buf2);
  9165. return out;
  9166. }
  9167. static Py_ssize_t
  9168. anylib_find(int kind, PyObject *str1, const void *buf1, Py_ssize_t len1,
  9169. PyObject *str2, const void *buf2, Py_ssize_t len2, Py_ssize_t offset)
  9170. {
  9171. switch (kind) {
  9172. case PyUnicode_1BYTE_KIND:
  9173. if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
  9174. return asciilib_find(buf1, len1, buf2, len2, offset);
  9175. else
  9176. return ucs1lib_find(buf1, len1, buf2, len2, offset);
  9177. case PyUnicode_2BYTE_KIND:
  9178. return ucs2lib_find(buf1, len1, buf2, len2, offset);
  9179. case PyUnicode_4BYTE_KIND:
  9180. return ucs4lib_find(buf1, len1, buf2, len2, offset);
  9181. }
  9182. Py_UNREACHABLE();
  9183. }
  9184. static Py_ssize_t
  9185. anylib_count(int kind, PyObject *sstr, const void* sbuf, Py_ssize_t slen,
  9186. PyObject *str1, const void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
  9187. {
  9188. switch (kind) {
  9189. case PyUnicode_1BYTE_KIND:
  9190. return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
  9191. case PyUnicode_2BYTE_KIND:
  9192. return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
  9193. case PyUnicode_4BYTE_KIND:
  9194. return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
  9195. }
  9196. Py_UNREACHABLE();
  9197. }
  9198. static void
  9199. replace_1char_inplace(PyObject *u, Py_ssize_t pos,
  9200. Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
  9201. {
  9202. int kind = PyUnicode_KIND(u);
  9203. void *data = PyUnicode_DATA(u);
  9204. Py_ssize_t len = PyUnicode_GET_LENGTH(u);
  9205. if (kind == PyUnicode_1BYTE_KIND) {
  9206. ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
  9207. (Py_UCS1 *)data + len,
  9208. u1, u2, maxcount);
  9209. }
  9210. else if (kind == PyUnicode_2BYTE_KIND) {
  9211. ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
  9212. (Py_UCS2 *)data + len,
  9213. u1, u2, maxcount);
  9214. }
  9215. else {
  9216. assert(kind == PyUnicode_4BYTE_KIND);
  9217. ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
  9218. (Py_UCS4 *)data + len,
  9219. u1, u2, maxcount);
  9220. }
  9221. }
  9222. static PyObject *
  9223. replace(PyObject *self, PyObject *str1,
  9224. PyObject *str2, Py_ssize_t maxcount)
  9225. {
  9226. PyObject *u;
  9227. const char *sbuf = PyUnicode_DATA(self);
  9228. const void *buf1 = PyUnicode_DATA(str1);
  9229. const void *buf2 = PyUnicode_DATA(str2);
  9230. int srelease = 0, release1 = 0, release2 = 0;
  9231. int skind = PyUnicode_KIND(self);
  9232. int kind1 = PyUnicode_KIND(str1);
  9233. int kind2 = PyUnicode_KIND(str2);
  9234. Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
  9235. Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
  9236. Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
  9237. int mayshrink;
  9238. Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
  9239. if (slen < len1)
  9240. goto nothing;
  9241. if (maxcount < 0)
  9242. maxcount = PY_SSIZE_T_MAX;
  9243. else if (maxcount == 0)
  9244. goto nothing;
  9245. if (str1 == str2)
  9246. goto nothing;
  9247. maxchar = PyUnicode_MAX_CHAR_VALUE(self);
  9248. maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
  9249. if (maxchar < maxchar_str1)
  9250. /* substring too wide to be present */
  9251. goto nothing;
  9252. maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
  9253. /* Replacing str1 with str2 may cause a maxchar reduction in the
  9254. result string. */
  9255. mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
  9256. maxchar = Py_MAX(maxchar, maxchar_str2);
  9257. if (len1 == len2) {
  9258. /* same length */
  9259. if (len1 == 0)
  9260. goto nothing;
  9261. if (len1 == 1) {
  9262. /* replace characters */
  9263. Py_UCS4 u1, u2;
  9264. Py_ssize_t pos;
  9265. u1 = PyUnicode_READ(kind1, buf1, 0);
  9266. pos = findchar(sbuf, skind, slen, u1, 1);
  9267. if (pos < 0)
  9268. goto nothing;
  9269. u2 = PyUnicode_READ(kind2, buf2, 0);
  9270. u = PyUnicode_New(slen, maxchar);
  9271. if (!u)
  9272. goto error;
  9273. _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
  9274. replace_1char_inplace(u, pos, u1, u2, maxcount);
  9275. }
  9276. else {
  9277. int rkind = skind;
  9278. char *res;
  9279. Py_ssize_t i;
  9280. if (kind1 < rkind) {
  9281. /* widen substring */
  9282. buf1 = unicode_askind(kind1, buf1, len1, rkind);
  9283. if (!buf1) goto error;
  9284. release1 = 1;
  9285. }
  9286. i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
  9287. if (i < 0)
  9288. goto nothing;
  9289. if (rkind > kind2) {
  9290. /* widen replacement */
  9291. buf2 = unicode_askind(kind2, buf2, len2, rkind);
  9292. if (!buf2) goto error;
  9293. release2 = 1;
  9294. }
  9295. else if (rkind < kind2) {
  9296. /* widen self and buf1 */
  9297. rkind = kind2;
  9298. if (release1) {
  9299. assert(buf1 != PyUnicode_DATA(str1));
  9300. PyMem_Free((void *)buf1);
  9301. buf1 = PyUnicode_DATA(str1);
  9302. release1 = 0;
  9303. }
  9304. sbuf = unicode_askind(skind, sbuf, slen, rkind);
  9305. if (!sbuf) goto error;
  9306. srelease = 1;
  9307. buf1 = unicode_askind(kind1, buf1, len1, rkind);
  9308. if (!buf1) goto error;
  9309. release1 = 1;
  9310. }
  9311. u = PyUnicode_New(slen, maxchar);
  9312. if (!u)
  9313. goto error;
  9314. assert(PyUnicode_KIND(u) == rkind);
  9315. res = PyUnicode_DATA(u);
  9316. memcpy(res, sbuf, rkind * slen);
  9317. /* change everything in-place, starting with this one */
  9318. memcpy(res + rkind * i,
  9319. buf2,
  9320. rkind * len2);
  9321. i += len1;
  9322. while ( --maxcount > 0) {
  9323. i = anylib_find(rkind, self,
  9324. sbuf+rkind*i, slen-i,
  9325. str1, buf1, len1, i);
  9326. if (i == -1)
  9327. break;
  9328. memcpy(res + rkind * i,
  9329. buf2,
  9330. rkind * len2);
  9331. i += len1;
  9332. }
  9333. }
  9334. }
  9335. else {
  9336. Py_ssize_t n, i, j, ires;
  9337. Py_ssize_t new_size;
  9338. int rkind = skind;
  9339. char *res;
  9340. if (kind1 < rkind) {
  9341. /* widen substring */
  9342. buf1 = unicode_askind(kind1, buf1, len1, rkind);
  9343. if (!buf1) goto error;
  9344. release1 = 1;
  9345. }
  9346. n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
  9347. if (n == 0)
  9348. goto nothing;
  9349. if (kind2 < rkind) {
  9350. /* widen replacement */
  9351. buf2 = unicode_askind(kind2, buf2, len2, rkind);
  9352. if (!buf2) goto error;
  9353. release2 = 1;
  9354. }
  9355. else if (kind2 > rkind) {
  9356. /* widen self and buf1 */
  9357. rkind = kind2;
  9358. sbuf = unicode_askind(skind, sbuf, slen, rkind);
  9359. if (!sbuf) goto error;
  9360. srelease = 1;
  9361. if (release1) {
  9362. assert(buf1 != PyUnicode_DATA(str1));
  9363. PyMem_Free((void *)buf1);
  9364. buf1 = PyUnicode_DATA(str1);
  9365. release1 = 0;
  9366. }
  9367. buf1 = unicode_askind(kind1, buf1, len1, rkind);
  9368. if (!buf1) goto error;
  9369. release1 = 1;
  9370. }
  9371. /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
  9372. PyUnicode_GET_LENGTH(str1)); */
  9373. if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
  9374. PyErr_SetString(PyExc_OverflowError,
  9375. "replace string is too long");
  9376. goto error;
  9377. }
  9378. new_size = slen + n * (len2 - len1);
  9379. if (new_size == 0) {
  9380. u = unicode_new_empty();
  9381. goto done;
  9382. }
  9383. if (new_size > (PY_SSIZE_T_MAX / rkind)) {
  9384. PyErr_SetString(PyExc_OverflowError,
  9385. "replace string is too long");
  9386. goto error;
  9387. }
  9388. u = PyUnicode_New(new_size, maxchar);
  9389. if (!u)
  9390. goto error;
  9391. assert(PyUnicode_KIND(u) == rkind);
  9392. res = PyUnicode_DATA(u);
  9393. ires = i = 0;
  9394. if (len1 > 0) {
  9395. while (n-- > 0) {
  9396. /* look for next match */
  9397. j = anylib_find(rkind, self,
  9398. sbuf + rkind * i, slen-i,
  9399. str1, buf1, len1, i);
  9400. if (j == -1)
  9401. break;
  9402. else if (j > i) {
  9403. /* copy unchanged part [i:j] */
  9404. memcpy(res + rkind * ires,
  9405. sbuf + rkind * i,
  9406. rkind * (j-i));
  9407. ires += j - i;
  9408. }
  9409. /* copy substitution string */
  9410. if (len2 > 0) {
  9411. memcpy(res + rkind * ires,
  9412. buf2,
  9413. rkind * len2);
  9414. ires += len2;
  9415. }
  9416. i = j + len1;
  9417. }
  9418. if (i < slen)
  9419. /* copy tail [i:] */
  9420. memcpy(res + rkind * ires,
  9421. sbuf + rkind * i,
  9422. rkind * (slen-i));
  9423. }
  9424. else {
  9425. /* interleave */
  9426. while (n > 0) {
  9427. memcpy(res + rkind * ires,
  9428. buf2,
  9429. rkind * len2);
  9430. ires += len2;
  9431. if (--n <= 0)
  9432. break;
  9433. memcpy(res + rkind * ires,
  9434. sbuf + rkind * i,
  9435. rkind);
  9436. ires++;
  9437. i++;
  9438. }
  9439. memcpy(res + rkind * ires,
  9440. sbuf + rkind * i,
  9441. rkind * (slen-i));
  9442. }
  9443. }
  9444. if (mayshrink) {
  9445. unicode_adjust_maxchar(&u);
  9446. if (u == NULL)
  9447. goto error;
  9448. }
  9449. done:
  9450. assert(srelease == (sbuf != PyUnicode_DATA(self)));
  9451. assert(release1 == (buf1 != PyUnicode_DATA(str1)));
  9452. assert(release2 == (buf2 != PyUnicode_DATA(str2)));
  9453. if (srelease)
  9454. PyMem_Free((void *)sbuf);
  9455. if (release1)
  9456. PyMem_Free((void *)buf1);
  9457. if (release2)
  9458. PyMem_Free((void *)buf2);
  9459. assert(_PyUnicode_CheckConsistency(u, 1));
  9460. return u;
  9461. nothing:
  9462. /* nothing to replace; return original string (when possible) */
  9463. assert(srelease == (sbuf != PyUnicode_DATA(self)));
  9464. assert(release1 == (buf1 != PyUnicode_DATA(str1)));
  9465. assert(release2 == (buf2 != PyUnicode_DATA(str2)));
  9466. if (srelease)
  9467. PyMem_Free((void *)sbuf);
  9468. if (release1)
  9469. PyMem_Free((void *)buf1);
  9470. if (release2)
  9471. PyMem_Free((void *)buf2);
  9472. return unicode_result_unchanged(self);
  9473. error:
  9474. assert(srelease == (sbuf != PyUnicode_DATA(self)));
  9475. assert(release1 == (buf1 != PyUnicode_DATA(str1)));
  9476. assert(release2 == (buf2 != PyUnicode_DATA(str2)));
  9477. if (srelease)
  9478. PyMem_Free((void *)sbuf);
  9479. if (release1)
  9480. PyMem_Free((void *)buf1);
  9481. if (release2)
  9482. PyMem_Free((void *)buf2);
  9483. return NULL;
  9484. }
  9485. /* --- Unicode Object Methods --------------------------------------------- */
  9486. /*[clinic input]
  9487. str.title as unicode_title
  9488. Return a version of the string where each word is titlecased.
  9489. More specifically, words start with uppercased characters and all remaining
  9490. cased characters have lower case.
  9491. [clinic start generated code]*/
  9492. static PyObject *
  9493. unicode_title_impl(PyObject *self)
  9494. /*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
  9495. {
  9496. return case_operation(self, do_title);
  9497. }
  9498. /*[clinic input]
  9499. str.capitalize as unicode_capitalize
  9500. Return a capitalized version of the string.
  9501. More specifically, make the first character have upper case and the rest lower
  9502. case.
  9503. [clinic start generated code]*/
  9504. static PyObject *
  9505. unicode_capitalize_impl(PyObject *self)
  9506. /*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
  9507. {
  9508. if (PyUnicode_GET_LENGTH(self) == 0)
  9509. return unicode_result_unchanged(self);
  9510. return case_operation(self, do_capitalize);
  9511. }
  9512. /*[clinic input]
  9513. str.casefold as unicode_casefold
  9514. Return a version of the string suitable for caseless comparisons.
  9515. [clinic start generated code]*/
  9516. static PyObject *
  9517. unicode_casefold_impl(PyObject *self)
  9518. /*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
  9519. {
  9520. if (PyUnicode_IS_ASCII(self))
  9521. return ascii_upper_or_lower(self, 1);
  9522. return case_operation(self, do_casefold);
  9523. }
  9524. /* Argument converter. Accepts a single Unicode character. */
  9525. static int
  9526. convert_uc(PyObject *obj, void *addr)
  9527. {
  9528. Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
  9529. if (!PyUnicode_Check(obj)) {
  9530. PyErr_Format(PyExc_TypeError,
  9531. "The fill character must be a unicode character, "
  9532. "not %.100s", Py_TYPE(obj)->tp_name);
  9533. return 0;
  9534. }
  9535. if (PyUnicode_GET_LENGTH(obj) != 1) {
  9536. PyErr_SetString(PyExc_TypeError,
  9537. "The fill character must be exactly one character long");
  9538. return 0;
  9539. }
  9540. *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
  9541. return 1;
  9542. }
  9543. /*[clinic input]
  9544. str.center as unicode_center
  9545. width: Py_ssize_t
  9546. fillchar: Py_UCS4 = ' '
  9547. /
  9548. Return a centered string of length width.
  9549. Padding is done using the specified fill character (default is a space).
  9550. [clinic start generated code]*/
  9551. static PyObject *
  9552. unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
  9553. /*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
  9554. {
  9555. Py_ssize_t marg, left;
  9556. if (PyUnicode_GET_LENGTH(self) >= width)
  9557. return unicode_result_unchanged(self);
  9558. marg = width - PyUnicode_GET_LENGTH(self);
  9559. left = marg / 2 + (marg & width & 1);
  9560. return pad(self, left, marg - left, fillchar);
  9561. }
  9562. /* This function assumes that str1 and str2 are readied by the caller. */
  9563. static int
  9564. unicode_compare(PyObject *str1, PyObject *str2)
  9565. {
  9566. #define COMPARE(TYPE1, TYPE2) \
  9567. do { \
  9568. TYPE1* p1 = (TYPE1 *)data1; \
  9569. TYPE2* p2 = (TYPE2 *)data2; \
  9570. TYPE1* end = p1 + len; \
  9571. Py_UCS4 c1, c2; \
  9572. for (; p1 != end; p1++, p2++) { \
  9573. c1 = *p1; \
  9574. c2 = *p2; \
  9575. if (c1 != c2) \
  9576. return (c1 < c2) ? -1 : 1; \
  9577. } \
  9578. } \
  9579. while (0)
  9580. int kind1, kind2;
  9581. const void *data1, *data2;
  9582. Py_ssize_t len1, len2, len;
  9583. kind1 = PyUnicode_KIND(str1);
  9584. kind2 = PyUnicode_KIND(str2);
  9585. data1 = PyUnicode_DATA(str1);
  9586. data2 = PyUnicode_DATA(str2);
  9587. len1 = PyUnicode_GET_LENGTH(str1);
  9588. len2 = PyUnicode_GET_LENGTH(str2);
  9589. len = Py_MIN(len1, len2);
  9590. switch(kind1) {
  9591. case PyUnicode_1BYTE_KIND:
  9592. {
  9593. switch(kind2) {
  9594. case PyUnicode_1BYTE_KIND:
  9595. {
  9596. int cmp = memcmp(data1, data2, len);
  9597. /* normalize result of memcmp() into the range [-1; 1] */
  9598. if (cmp < 0)
  9599. return -1;
  9600. if (cmp > 0)
  9601. return 1;
  9602. break;
  9603. }
  9604. case PyUnicode_2BYTE_KIND:
  9605. COMPARE(Py_UCS1, Py_UCS2);
  9606. break;
  9607. case PyUnicode_4BYTE_KIND:
  9608. COMPARE(Py_UCS1, Py_UCS4);
  9609. break;
  9610. default:
  9611. Py_UNREACHABLE();
  9612. }
  9613. break;
  9614. }
  9615. case PyUnicode_2BYTE_KIND:
  9616. {
  9617. switch(kind2) {
  9618. case PyUnicode_1BYTE_KIND:
  9619. COMPARE(Py_UCS2, Py_UCS1);
  9620. break;
  9621. case PyUnicode_2BYTE_KIND:
  9622. {
  9623. COMPARE(Py_UCS2, Py_UCS2);
  9624. break;
  9625. }
  9626. case PyUnicode_4BYTE_KIND:
  9627. COMPARE(Py_UCS2, Py_UCS4);
  9628. break;
  9629. default:
  9630. Py_UNREACHABLE();
  9631. }
  9632. break;
  9633. }
  9634. case PyUnicode_4BYTE_KIND:
  9635. {
  9636. switch(kind2) {
  9637. case PyUnicode_1BYTE_KIND:
  9638. COMPARE(Py_UCS4, Py_UCS1);
  9639. break;
  9640. case PyUnicode_2BYTE_KIND:
  9641. COMPARE(Py_UCS4, Py_UCS2);
  9642. break;
  9643. case PyUnicode_4BYTE_KIND:
  9644. {
  9645. #if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
  9646. int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
  9647. /* normalize result of wmemcmp() into the range [-1; 1] */
  9648. if (cmp < 0)
  9649. return -1;
  9650. if (cmp > 0)
  9651. return 1;
  9652. #else
  9653. COMPARE(Py_UCS4, Py_UCS4);
  9654. #endif
  9655. break;
  9656. }
  9657. default:
  9658. Py_UNREACHABLE();
  9659. }
  9660. break;
  9661. }
  9662. default:
  9663. Py_UNREACHABLE();
  9664. }
  9665. if (len1 == len2)
  9666. return 0;
  9667. if (len1 < len2)
  9668. return -1;
  9669. else
  9670. return 1;
  9671. #undef COMPARE
  9672. }
  9673. static int
  9674. unicode_compare_eq(PyObject *str1, PyObject *str2)
  9675. {
  9676. int kind;
  9677. const void *data1, *data2;
  9678. Py_ssize_t len;
  9679. int cmp;
  9680. len = PyUnicode_GET_LENGTH(str1);
  9681. if (PyUnicode_GET_LENGTH(str2) != len)
  9682. return 0;
  9683. kind = PyUnicode_KIND(str1);
  9684. if (PyUnicode_KIND(str2) != kind)
  9685. return 0;
  9686. data1 = PyUnicode_DATA(str1);
  9687. data2 = PyUnicode_DATA(str2);
  9688. cmp = memcmp(data1, data2, len * kind);
  9689. return (cmp == 0);
  9690. }
  9691. int
  9692. _PyUnicode_Equal(PyObject *str1, PyObject *str2)
  9693. {
  9694. assert(PyUnicode_Check(str1));
  9695. assert(PyUnicode_Check(str2));
  9696. if (str1 == str2) {
  9697. return 1;
  9698. }
  9699. return unicode_compare_eq(str1, str2);
  9700. }
  9701. int
  9702. PyUnicode_Compare(PyObject *left, PyObject *right)
  9703. {
  9704. if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
  9705. /* a string is equal to itself */
  9706. if (left == right)
  9707. return 0;
  9708. return unicode_compare(left, right);
  9709. }
  9710. PyErr_Format(PyExc_TypeError,
  9711. "Can't compare %.100s and %.100s",
  9712. Py_TYPE(left)->tp_name,
  9713. Py_TYPE(right)->tp_name);
  9714. return -1;
  9715. }
  9716. int
  9717. PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
  9718. {
  9719. Py_ssize_t i;
  9720. int kind;
  9721. Py_UCS4 chr;
  9722. assert(_PyUnicode_CHECK(uni));
  9723. kind = PyUnicode_KIND(uni);
  9724. if (kind == PyUnicode_1BYTE_KIND) {
  9725. const void *data = PyUnicode_1BYTE_DATA(uni);
  9726. size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
  9727. size_t len, len2 = strlen(str);
  9728. int cmp;
  9729. len = Py_MIN(len1, len2);
  9730. cmp = memcmp(data, str, len);
  9731. if (cmp != 0) {
  9732. if (cmp < 0)
  9733. return -1;
  9734. else
  9735. return 1;
  9736. }
  9737. if (len1 > len2)
  9738. return 1; /* uni is longer */
  9739. if (len1 < len2)
  9740. return -1; /* str is longer */
  9741. return 0;
  9742. }
  9743. else {
  9744. const void *data = PyUnicode_DATA(uni);
  9745. /* Compare Unicode string and source character set string */
  9746. for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
  9747. if (chr != (unsigned char)str[i])
  9748. return (chr < (unsigned char)(str[i])) ? -1 : 1;
  9749. /* This check keeps Python strings that end in '\0' from comparing equal
  9750. to C strings identical up to that point. */
  9751. if (PyUnicode_GET_LENGTH(uni) != i || chr)
  9752. return 1; /* uni is longer */
  9753. if (str[i])
  9754. return -1; /* str is longer */
  9755. return 0;
  9756. }
  9757. }
  9758. int
  9759. _PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
  9760. {
  9761. size_t len;
  9762. assert(_PyUnicode_CHECK(unicode));
  9763. assert(str);
  9764. #ifndef NDEBUG
  9765. for (const char *p = str; *p; p++) {
  9766. assert((unsigned char)*p < 128);
  9767. }
  9768. #endif
  9769. if (!PyUnicode_IS_ASCII(unicode))
  9770. return 0;
  9771. len = (size_t)PyUnicode_GET_LENGTH(unicode);
  9772. return strlen(str) == len &&
  9773. memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
  9774. }
  9775. int
  9776. _PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
  9777. {
  9778. PyObject *right_uni;
  9779. assert(_PyUnicode_CHECK(left));
  9780. assert(right->string);
  9781. #ifndef NDEBUG
  9782. for (const char *p = right->string; *p; p++) {
  9783. assert((unsigned char)*p < 128);
  9784. }
  9785. #endif
  9786. if (!PyUnicode_IS_ASCII(left))
  9787. return 0;
  9788. right_uni = _PyUnicode_FromId(right); /* borrowed */
  9789. if (right_uni == NULL) {
  9790. /* memory error or bad data */
  9791. PyErr_Clear();
  9792. return _PyUnicode_EqualToASCIIString(left, right->string);
  9793. }
  9794. if (left == right_uni)
  9795. return 1;
  9796. assert(PyUnicode_CHECK_INTERNED(right_uni));
  9797. if (PyUnicode_CHECK_INTERNED(left)) {
  9798. return 0;
  9799. }
  9800. assert(_PyUnicode_HASH(right_uni) != -1);
  9801. Py_hash_t hash = _PyUnicode_HASH(left);
  9802. if (hash != -1 && hash != _PyUnicode_HASH(right_uni)) {
  9803. return 0;
  9804. }
  9805. return unicode_compare_eq(left, right_uni);
  9806. }
  9807. PyObject *
  9808. PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
  9809. {
  9810. int result;
  9811. if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
  9812. Py_RETURN_NOTIMPLEMENTED;
  9813. if (left == right) {
  9814. switch (op) {
  9815. case Py_EQ:
  9816. case Py_LE:
  9817. case Py_GE:
  9818. /* a string is equal to itself */
  9819. Py_RETURN_TRUE;
  9820. case Py_NE:
  9821. case Py_LT:
  9822. case Py_GT:
  9823. Py_RETURN_FALSE;
  9824. default:
  9825. PyErr_BadArgument();
  9826. return NULL;
  9827. }
  9828. }
  9829. else if (op == Py_EQ || op == Py_NE) {
  9830. result = unicode_compare_eq(left, right);
  9831. result ^= (op == Py_NE);
  9832. return PyBool_FromLong(result);
  9833. }
  9834. else {
  9835. result = unicode_compare(left, right);
  9836. Py_RETURN_RICHCOMPARE(result, 0, op);
  9837. }
  9838. }
  9839. int
  9840. _PyUnicode_EQ(PyObject *aa, PyObject *bb)
  9841. {
  9842. return unicode_eq(aa, bb);
  9843. }
  9844. int
  9845. PyUnicode_Contains(PyObject *str, PyObject *substr)
  9846. {
  9847. int kind1, kind2;
  9848. const void *buf1, *buf2;
  9849. Py_ssize_t len1, len2;
  9850. int result;
  9851. if (!PyUnicode_Check(substr)) {
  9852. PyErr_Format(PyExc_TypeError,
  9853. "'in <string>' requires string as left operand, not %.100s",
  9854. Py_TYPE(substr)->tp_name);
  9855. return -1;
  9856. }
  9857. if (ensure_unicode(str) < 0)
  9858. return -1;
  9859. kind1 = PyUnicode_KIND(str);
  9860. kind2 = PyUnicode_KIND(substr);
  9861. if (kind1 < kind2)
  9862. return 0;
  9863. len1 = PyUnicode_GET_LENGTH(str);
  9864. len2 = PyUnicode_GET_LENGTH(substr);
  9865. if (len1 < len2)
  9866. return 0;
  9867. buf1 = PyUnicode_DATA(str);
  9868. buf2 = PyUnicode_DATA(substr);
  9869. if (len2 == 1) {
  9870. Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
  9871. result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
  9872. return result;
  9873. }
  9874. if (kind2 != kind1) {
  9875. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  9876. if (!buf2)
  9877. return -1;
  9878. }
  9879. switch (kind1) {
  9880. case PyUnicode_1BYTE_KIND:
  9881. result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
  9882. break;
  9883. case PyUnicode_2BYTE_KIND:
  9884. result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
  9885. break;
  9886. case PyUnicode_4BYTE_KIND:
  9887. result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
  9888. break;
  9889. default:
  9890. Py_UNREACHABLE();
  9891. }
  9892. assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(substr)));
  9893. if (kind2 != kind1)
  9894. PyMem_Free((void *)buf2);
  9895. return result;
  9896. }
  9897. /* Concat to string or Unicode object giving a new Unicode object. */
  9898. PyObject *
  9899. PyUnicode_Concat(PyObject *left, PyObject *right)
  9900. {
  9901. PyObject *result;
  9902. Py_UCS4 maxchar, maxchar2;
  9903. Py_ssize_t left_len, right_len, new_len;
  9904. if (ensure_unicode(left) < 0)
  9905. return NULL;
  9906. if (!PyUnicode_Check(right)) {
  9907. PyErr_Format(PyExc_TypeError,
  9908. "can only concatenate str (not \"%.200s\") to str",
  9909. Py_TYPE(right)->tp_name);
  9910. return NULL;
  9911. }
  9912. /* Shortcuts */
  9913. PyObject *empty = unicode_get_empty(); // Borrowed reference
  9914. if (left == empty) {
  9915. return PyUnicode_FromObject(right);
  9916. }
  9917. if (right == empty) {
  9918. return PyUnicode_FromObject(left);
  9919. }
  9920. left_len = PyUnicode_GET_LENGTH(left);
  9921. right_len = PyUnicode_GET_LENGTH(right);
  9922. if (left_len > PY_SSIZE_T_MAX - right_len) {
  9923. PyErr_SetString(PyExc_OverflowError,
  9924. "strings are too large to concat");
  9925. return NULL;
  9926. }
  9927. new_len = left_len + right_len;
  9928. maxchar = PyUnicode_MAX_CHAR_VALUE(left);
  9929. maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
  9930. maxchar = Py_MAX(maxchar, maxchar2);
  9931. /* Concat the two Unicode strings */
  9932. result = PyUnicode_New(new_len, maxchar);
  9933. if (result == NULL)
  9934. return NULL;
  9935. _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
  9936. _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
  9937. assert(_PyUnicode_CheckConsistency(result, 1));
  9938. return result;
  9939. }
  9940. void
  9941. PyUnicode_Append(PyObject **p_left, PyObject *right)
  9942. {
  9943. PyObject *left, *res;
  9944. Py_UCS4 maxchar, maxchar2;
  9945. Py_ssize_t left_len, right_len, new_len;
  9946. if (p_left == NULL) {
  9947. if (!PyErr_Occurred())
  9948. PyErr_BadInternalCall();
  9949. return;
  9950. }
  9951. left = *p_left;
  9952. if (right == NULL || left == NULL
  9953. || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
  9954. if (!PyErr_Occurred())
  9955. PyErr_BadInternalCall();
  9956. goto error;
  9957. }
  9958. /* Shortcuts */
  9959. PyObject *empty = unicode_get_empty(); // Borrowed reference
  9960. if (left == empty) {
  9961. Py_DECREF(left);
  9962. *p_left = Py_NewRef(right);
  9963. return;
  9964. }
  9965. if (right == empty) {
  9966. return;
  9967. }
  9968. left_len = PyUnicode_GET_LENGTH(left);
  9969. right_len = PyUnicode_GET_LENGTH(right);
  9970. if (left_len > PY_SSIZE_T_MAX - right_len) {
  9971. PyErr_SetString(PyExc_OverflowError,
  9972. "strings are too large to concat");
  9973. goto error;
  9974. }
  9975. new_len = left_len + right_len;
  9976. if (unicode_modifiable(left)
  9977. && PyUnicode_CheckExact(right)
  9978. && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
  9979. /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
  9980. to change the structure size, but characters are stored just after
  9981. the structure, and so it requires to move all characters which is
  9982. not so different than duplicating the string. */
  9983. && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
  9984. {
  9985. /* append inplace */
  9986. if (unicode_resize(p_left, new_len) != 0)
  9987. goto error;
  9988. /* copy 'right' into the newly allocated area of 'left' */
  9989. _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
  9990. }
  9991. else {
  9992. maxchar = PyUnicode_MAX_CHAR_VALUE(left);
  9993. maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
  9994. maxchar = Py_MAX(maxchar, maxchar2);
  9995. /* Concat the two Unicode strings */
  9996. res = PyUnicode_New(new_len, maxchar);
  9997. if (res == NULL)
  9998. goto error;
  9999. _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
  10000. _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
  10001. Py_DECREF(left);
  10002. *p_left = res;
  10003. }
  10004. assert(_PyUnicode_CheckConsistency(*p_left, 1));
  10005. return;
  10006. error:
  10007. Py_CLEAR(*p_left);
  10008. }
  10009. void
  10010. PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
  10011. {
  10012. PyUnicode_Append(pleft, right);
  10013. Py_XDECREF(right);
  10014. }
  10015. /*
  10016. Wraps asciilib_parse_args_finds() and additionally ensures that the
  10017. first argument is a unicode object.
  10018. */
  10019. static inline int
  10020. parse_args_finds_unicode(const char * function_name, PyObject *args,
  10021. PyObject **substring,
  10022. Py_ssize_t *start, Py_ssize_t *end)
  10023. {
  10024. if (asciilib_parse_args_finds(function_name, args, substring, start, end)) {
  10025. if (ensure_unicode(*substring) < 0)
  10026. return 0;
  10027. return 1;
  10028. }
  10029. return 0;
  10030. }
  10031. PyDoc_STRVAR(count__doc__,
  10032. "S.count(sub[, start[, end]]) -> int\n\
  10033. \n\
  10034. Return the number of non-overlapping occurrences of substring sub in\n\
  10035. string S[start:end]. Optional arguments start and end are\n\
  10036. interpreted as in slice notation.");
  10037. static PyObject *
  10038. unicode_count(PyObject *self, PyObject *args)
  10039. {
  10040. PyObject *substring = NULL; /* initialize to fix a compiler warning */
  10041. Py_ssize_t start = 0;
  10042. Py_ssize_t end = PY_SSIZE_T_MAX;
  10043. Py_ssize_t result;
  10044. if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
  10045. return NULL;
  10046. result = unicode_count_impl(self, substring, start, end);
  10047. if (result == -1)
  10048. return NULL;
  10049. return PyLong_FromSsize_t(result);
  10050. }
  10051. /*[clinic input]
  10052. str.encode as unicode_encode
  10053. encoding: str(c_default="NULL") = 'utf-8'
  10054. The encoding in which to encode the string.
  10055. errors: str(c_default="NULL") = 'strict'
  10056. The error handling scheme to use for encoding errors.
  10057. The default is 'strict' meaning that encoding errors raise a
  10058. UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
  10059. 'xmlcharrefreplace' as well as any other name registered with
  10060. codecs.register_error that can handle UnicodeEncodeErrors.
  10061. Encode the string using the codec registered for encoding.
  10062. [clinic start generated code]*/
  10063. static PyObject *
  10064. unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
  10065. /*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
  10066. {
  10067. return PyUnicode_AsEncodedString(self, encoding, errors);
  10068. }
  10069. /*[clinic input]
  10070. str.expandtabs as unicode_expandtabs
  10071. tabsize: int = 8
  10072. Return a copy where all tab characters are expanded using spaces.
  10073. If tabsize is not given, a tab size of 8 characters is assumed.
  10074. [clinic start generated code]*/
  10075. static PyObject *
  10076. unicode_expandtabs_impl(PyObject *self, int tabsize)
  10077. /*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
  10078. {
  10079. Py_ssize_t i, j, line_pos, src_len, incr;
  10080. Py_UCS4 ch;
  10081. PyObject *u;
  10082. const void *src_data;
  10083. void *dest_data;
  10084. int kind;
  10085. int found;
  10086. /* First pass: determine size of output string */
  10087. src_len = PyUnicode_GET_LENGTH(self);
  10088. i = j = line_pos = 0;
  10089. kind = PyUnicode_KIND(self);
  10090. src_data = PyUnicode_DATA(self);
  10091. found = 0;
  10092. for (; i < src_len; i++) {
  10093. ch = PyUnicode_READ(kind, src_data, i);
  10094. if (ch == '\t') {
  10095. found = 1;
  10096. if (tabsize > 0) {
  10097. incr = tabsize - (line_pos % tabsize); /* cannot overflow */
  10098. if (j > PY_SSIZE_T_MAX - incr)
  10099. goto overflow;
  10100. line_pos += incr;
  10101. j += incr;
  10102. }
  10103. }
  10104. else {
  10105. if (j > PY_SSIZE_T_MAX - 1)
  10106. goto overflow;
  10107. line_pos++;
  10108. j++;
  10109. if (ch == '\n' || ch == '\r')
  10110. line_pos = 0;
  10111. }
  10112. }
  10113. if (!found)
  10114. return unicode_result_unchanged(self);
  10115. /* Second pass: create output string and fill it */
  10116. u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
  10117. if (!u)
  10118. return NULL;
  10119. dest_data = PyUnicode_DATA(u);
  10120. i = j = line_pos = 0;
  10121. for (; i < src_len; i++) {
  10122. ch = PyUnicode_READ(kind, src_data, i);
  10123. if (ch == '\t') {
  10124. if (tabsize > 0) {
  10125. incr = tabsize - (line_pos % tabsize);
  10126. line_pos += incr;
  10127. unicode_fill(kind, dest_data, ' ', j, incr);
  10128. j += incr;
  10129. }
  10130. }
  10131. else {
  10132. line_pos++;
  10133. PyUnicode_WRITE(kind, dest_data, j, ch);
  10134. j++;
  10135. if (ch == '\n' || ch == '\r')
  10136. line_pos = 0;
  10137. }
  10138. }
  10139. assert (j == PyUnicode_GET_LENGTH(u));
  10140. return unicode_result(u);
  10141. overflow:
  10142. PyErr_SetString(PyExc_OverflowError, "new string is too long");
  10143. return NULL;
  10144. }
  10145. PyDoc_STRVAR(find__doc__,
  10146. "S.find(sub[, start[, end]]) -> int\n\
  10147. \n\
  10148. Return the lowest index in S where substring sub is found,\n\
  10149. such that sub is contained within S[start:end]. Optional\n\
  10150. arguments start and end are interpreted as in slice notation.\n\
  10151. \n\
  10152. Return -1 on failure.");
  10153. static PyObject *
  10154. unicode_find(PyObject *self, PyObject *args)
  10155. {
  10156. /* initialize variables to prevent gcc warning */
  10157. PyObject *substring = NULL;
  10158. Py_ssize_t start = 0;
  10159. Py_ssize_t end = 0;
  10160. Py_ssize_t result;
  10161. if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
  10162. return NULL;
  10163. result = any_find_slice(self, substring, start, end, 1);
  10164. if (result == -2)
  10165. return NULL;
  10166. return PyLong_FromSsize_t(result);
  10167. }
  10168. static PyObject *
  10169. unicode_getitem(PyObject *self, Py_ssize_t index)
  10170. {
  10171. const void *data;
  10172. int kind;
  10173. Py_UCS4 ch;
  10174. if (!PyUnicode_Check(self)) {
  10175. PyErr_BadArgument();
  10176. return NULL;
  10177. }
  10178. if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
  10179. PyErr_SetString(PyExc_IndexError, "string index out of range");
  10180. return NULL;
  10181. }
  10182. kind = PyUnicode_KIND(self);
  10183. data = PyUnicode_DATA(self);
  10184. ch = PyUnicode_READ(kind, data, index);
  10185. return unicode_char(ch);
  10186. }
  10187. /* Believe it or not, this produces the same value for ASCII strings
  10188. as bytes_hash(). */
  10189. static Py_hash_t
  10190. unicode_hash(PyObject *self)
  10191. {
  10192. Py_uhash_t x; /* Unsigned for defined overflow behavior. */
  10193. #ifdef Py_DEBUG
  10194. assert(_Py_HashSecret_Initialized);
  10195. #endif
  10196. if (_PyUnicode_HASH(self) != -1)
  10197. return _PyUnicode_HASH(self);
  10198. x = _Py_HashBytes(PyUnicode_DATA(self),
  10199. PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
  10200. _PyUnicode_HASH(self) = x;
  10201. return x;
  10202. }
  10203. PyDoc_STRVAR(index__doc__,
  10204. "S.index(sub[, start[, end]]) -> int\n\
  10205. \n\
  10206. Return the lowest index in S where substring sub is found,\n\
  10207. such that sub is contained within S[start:end]. Optional\n\
  10208. arguments start and end are interpreted as in slice notation.\n\
  10209. \n\
  10210. Raises ValueError when the substring is not found.");
  10211. static PyObject *
  10212. unicode_index(PyObject *self, PyObject *args)
  10213. {
  10214. /* initialize variables to prevent gcc warning */
  10215. Py_ssize_t result;
  10216. PyObject *substring = NULL;
  10217. Py_ssize_t start = 0;
  10218. Py_ssize_t end = 0;
  10219. if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
  10220. return NULL;
  10221. result = any_find_slice(self, substring, start, end, 1);
  10222. if (result == -2)
  10223. return NULL;
  10224. if (result < 0) {
  10225. PyErr_SetString(PyExc_ValueError, "substring not found");
  10226. return NULL;
  10227. }
  10228. return PyLong_FromSsize_t(result);
  10229. }
  10230. /*[clinic input]
  10231. str.isascii as unicode_isascii
  10232. Return True if all characters in the string are ASCII, False otherwise.
  10233. ASCII characters have code points in the range U+0000-U+007F.
  10234. Empty string is ASCII too.
  10235. [clinic start generated code]*/
  10236. static PyObject *
  10237. unicode_isascii_impl(PyObject *self)
  10238. /*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
  10239. {
  10240. return PyBool_FromLong(PyUnicode_IS_ASCII(self));
  10241. }
  10242. /*[clinic input]
  10243. str.islower as unicode_islower
  10244. Return True if the string is a lowercase string, False otherwise.
  10245. A string is lowercase if all cased characters in the string are lowercase and
  10246. there is at least one cased character in the string.
  10247. [clinic start generated code]*/
  10248. static PyObject *
  10249. unicode_islower_impl(PyObject *self)
  10250. /*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
  10251. {
  10252. Py_ssize_t i, length;
  10253. int kind;
  10254. const void *data;
  10255. int cased;
  10256. length = PyUnicode_GET_LENGTH(self);
  10257. kind = PyUnicode_KIND(self);
  10258. data = PyUnicode_DATA(self);
  10259. /* Shortcut for single character strings */
  10260. if (length == 1)
  10261. return PyBool_FromLong(
  10262. Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
  10263. /* Special case for empty strings */
  10264. if (length == 0)
  10265. Py_RETURN_FALSE;
  10266. cased = 0;
  10267. for (i = 0; i < length; i++) {
  10268. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10269. if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
  10270. Py_RETURN_FALSE;
  10271. else if (!cased && Py_UNICODE_ISLOWER(ch))
  10272. cased = 1;
  10273. }
  10274. return PyBool_FromLong(cased);
  10275. }
  10276. /*[clinic input]
  10277. str.isupper as unicode_isupper
  10278. Return True if the string is an uppercase string, False otherwise.
  10279. A string is uppercase if all cased characters in the string are uppercase and
  10280. there is at least one cased character in the string.
  10281. [clinic start generated code]*/
  10282. static PyObject *
  10283. unicode_isupper_impl(PyObject *self)
  10284. /*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
  10285. {
  10286. Py_ssize_t i, length;
  10287. int kind;
  10288. const void *data;
  10289. int cased;
  10290. length = PyUnicode_GET_LENGTH(self);
  10291. kind = PyUnicode_KIND(self);
  10292. data = PyUnicode_DATA(self);
  10293. /* Shortcut for single character strings */
  10294. if (length == 1)
  10295. return PyBool_FromLong(
  10296. Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
  10297. /* Special case for empty strings */
  10298. if (length == 0)
  10299. Py_RETURN_FALSE;
  10300. cased = 0;
  10301. for (i = 0; i < length; i++) {
  10302. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10303. if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
  10304. Py_RETURN_FALSE;
  10305. else if (!cased && Py_UNICODE_ISUPPER(ch))
  10306. cased = 1;
  10307. }
  10308. return PyBool_FromLong(cased);
  10309. }
  10310. /*[clinic input]
  10311. str.istitle as unicode_istitle
  10312. Return True if the string is a title-cased string, False otherwise.
  10313. In a title-cased string, upper- and title-case characters may only
  10314. follow uncased characters and lowercase characters only cased ones.
  10315. [clinic start generated code]*/
  10316. static PyObject *
  10317. unicode_istitle_impl(PyObject *self)
  10318. /*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
  10319. {
  10320. Py_ssize_t i, length;
  10321. int kind;
  10322. const void *data;
  10323. int cased, previous_is_cased;
  10324. length = PyUnicode_GET_LENGTH(self);
  10325. kind = PyUnicode_KIND(self);
  10326. data = PyUnicode_DATA(self);
  10327. /* Shortcut for single character strings */
  10328. if (length == 1) {
  10329. Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
  10330. return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
  10331. (Py_UNICODE_ISUPPER(ch) != 0));
  10332. }
  10333. /* Special case for empty strings */
  10334. if (length == 0)
  10335. Py_RETURN_FALSE;
  10336. cased = 0;
  10337. previous_is_cased = 0;
  10338. for (i = 0; i < length; i++) {
  10339. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10340. if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
  10341. if (previous_is_cased)
  10342. Py_RETURN_FALSE;
  10343. previous_is_cased = 1;
  10344. cased = 1;
  10345. }
  10346. else if (Py_UNICODE_ISLOWER(ch)) {
  10347. if (!previous_is_cased)
  10348. Py_RETURN_FALSE;
  10349. previous_is_cased = 1;
  10350. cased = 1;
  10351. }
  10352. else
  10353. previous_is_cased = 0;
  10354. }
  10355. return PyBool_FromLong(cased);
  10356. }
  10357. /*[clinic input]
  10358. str.isspace as unicode_isspace
  10359. Return True if the string is a whitespace string, False otherwise.
  10360. A string is whitespace if all characters in the string are whitespace and there
  10361. is at least one character in the string.
  10362. [clinic start generated code]*/
  10363. static PyObject *
  10364. unicode_isspace_impl(PyObject *self)
  10365. /*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
  10366. {
  10367. Py_ssize_t i, length;
  10368. int kind;
  10369. const void *data;
  10370. length = PyUnicode_GET_LENGTH(self);
  10371. kind = PyUnicode_KIND(self);
  10372. data = PyUnicode_DATA(self);
  10373. /* Shortcut for single character strings */
  10374. if (length == 1)
  10375. return PyBool_FromLong(
  10376. Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
  10377. /* Special case for empty strings */
  10378. if (length == 0)
  10379. Py_RETURN_FALSE;
  10380. for (i = 0; i < length; i++) {
  10381. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10382. if (!Py_UNICODE_ISSPACE(ch))
  10383. Py_RETURN_FALSE;
  10384. }
  10385. Py_RETURN_TRUE;
  10386. }
  10387. /*[clinic input]
  10388. str.isalpha as unicode_isalpha
  10389. Return True if the string is an alphabetic string, False otherwise.
  10390. A string is alphabetic if all characters in the string are alphabetic and there
  10391. is at least one character in the string.
  10392. [clinic start generated code]*/
  10393. static PyObject *
  10394. unicode_isalpha_impl(PyObject *self)
  10395. /*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
  10396. {
  10397. Py_ssize_t i, length;
  10398. int kind;
  10399. const void *data;
  10400. length = PyUnicode_GET_LENGTH(self);
  10401. kind = PyUnicode_KIND(self);
  10402. data = PyUnicode_DATA(self);
  10403. /* Shortcut for single character strings */
  10404. if (length == 1)
  10405. return PyBool_FromLong(
  10406. Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
  10407. /* Special case for empty strings */
  10408. if (length == 0)
  10409. Py_RETURN_FALSE;
  10410. for (i = 0; i < length; i++) {
  10411. if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
  10412. Py_RETURN_FALSE;
  10413. }
  10414. Py_RETURN_TRUE;
  10415. }
  10416. /*[clinic input]
  10417. str.isalnum as unicode_isalnum
  10418. Return True if the string is an alpha-numeric string, False otherwise.
  10419. A string is alpha-numeric if all characters in the string are alpha-numeric and
  10420. there is at least one character in the string.
  10421. [clinic start generated code]*/
  10422. static PyObject *
  10423. unicode_isalnum_impl(PyObject *self)
  10424. /*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
  10425. {
  10426. int kind;
  10427. const void *data;
  10428. Py_ssize_t len, i;
  10429. kind = PyUnicode_KIND(self);
  10430. data = PyUnicode_DATA(self);
  10431. len = PyUnicode_GET_LENGTH(self);
  10432. /* Shortcut for single character strings */
  10433. if (len == 1) {
  10434. const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
  10435. return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
  10436. }
  10437. /* Special case for empty strings */
  10438. if (len == 0)
  10439. Py_RETURN_FALSE;
  10440. for (i = 0; i < len; i++) {
  10441. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10442. if (!Py_UNICODE_ISALNUM(ch))
  10443. Py_RETURN_FALSE;
  10444. }
  10445. Py_RETURN_TRUE;
  10446. }
  10447. /*[clinic input]
  10448. str.isdecimal as unicode_isdecimal
  10449. Return True if the string is a decimal string, False otherwise.
  10450. A string is a decimal string if all characters in the string are decimal and
  10451. there is at least one character in the string.
  10452. [clinic start generated code]*/
  10453. static PyObject *
  10454. unicode_isdecimal_impl(PyObject *self)
  10455. /*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
  10456. {
  10457. Py_ssize_t i, length;
  10458. int kind;
  10459. const void *data;
  10460. length = PyUnicode_GET_LENGTH(self);
  10461. kind = PyUnicode_KIND(self);
  10462. data = PyUnicode_DATA(self);
  10463. /* Shortcut for single character strings */
  10464. if (length == 1)
  10465. return PyBool_FromLong(
  10466. Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
  10467. /* Special case for empty strings */
  10468. if (length == 0)
  10469. Py_RETURN_FALSE;
  10470. for (i = 0; i < length; i++) {
  10471. if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
  10472. Py_RETURN_FALSE;
  10473. }
  10474. Py_RETURN_TRUE;
  10475. }
  10476. /*[clinic input]
  10477. str.isdigit as unicode_isdigit
  10478. Return True if the string is a digit string, False otherwise.
  10479. A string is a digit string if all characters in the string are digits and there
  10480. is at least one character in the string.
  10481. [clinic start generated code]*/
  10482. static PyObject *
  10483. unicode_isdigit_impl(PyObject *self)
  10484. /*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
  10485. {
  10486. Py_ssize_t i, length;
  10487. int kind;
  10488. const void *data;
  10489. length = PyUnicode_GET_LENGTH(self);
  10490. kind = PyUnicode_KIND(self);
  10491. data = PyUnicode_DATA(self);
  10492. /* Shortcut for single character strings */
  10493. if (length == 1) {
  10494. const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
  10495. return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
  10496. }
  10497. /* Special case for empty strings */
  10498. if (length == 0)
  10499. Py_RETURN_FALSE;
  10500. for (i = 0; i < length; i++) {
  10501. if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
  10502. Py_RETURN_FALSE;
  10503. }
  10504. Py_RETURN_TRUE;
  10505. }
  10506. /*[clinic input]
  10507. str.isnumeric as unicode_isnumeric
  10508. Return True if the string is a numeric string, False otherwise.
  10509. A string is numeric if all characters in the string are numeric and there is at
  10510. least one character in the string.
  10511. [clinic start generated code]*/
  10512. static PyObject *
  10513. unicode_isnumeric_impl(PyObject *self)
  10514. /*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
  10515. {
  10516. Py_ssize_t i, length;
  10517. int kind;
  10518. const void *data;
  10519. length = PyUnicode_GET_LENGTH(self);
  10520. kind = PyUnicode_KIND(self);
  10521. data = PyUnicode_DATA(self);
  10522. /* Shortcut for single character strings */
  10523. if (length == 1)
  10524. return PyBool_FromLong(
  10525. Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
  10526. /* Special case for empty strings */
  10527. if (length == 0)
  10528. Py_RETURN_FALSE;
  10529. for (i = 0; i < length; i++) {
  10530. if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
  10531. Py_RETURN_FALSE;
  10532. }
  10533. Py_RETURN_TRUE;
  10534. }
  10535. Py_ssize_t
  10536. _PyUnicode_ScanIdentifier(PyObject *self)
  10537. {
  10538. Py_ssize_t i;
  10539. Py_ssize_t len = PyUnicode_GET_LENGTH(self);
  10540. if (len == 0) {
  10541. /* an empty string is not a valid identifier */
  10542. return 0;
  10543. }
  10544. int kind = PyUnicode_KIND(self);
  10545. const void *data = PyUnicode_DATA(self);
  10546. Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
  10547. /* PEP 3131 says that the first character must be in
  10548. XID_Start and subsequent characters in XID_Continue,
  10549. and for the ASCII range, the 2.x rules apply (i.e
  10550. start with letters and underscore, continue with
  10551. letters, digits, underscore). However, given the current
  10552. definition of XID_Start and XID_Continue, it is sufficient
  10553. to check just for these, except that _ must be allowed
  10554. as starting an identifier. */
  10555. if (!_PyUnicode_IsXidStart(ch) && ch != 0x5F /* LOW LINE */) {
  10556. return 0;
  10557. }
  10558. for (i = 1; i < len; i++) {
  10559. ch = PyUnicode_READ(kind, data, i);
  10560. if (!_PyUnicode_IsXidContinue(ch)) {
  10561. return i;
  10562. }
  10563. }
  10564. return i;
  10565. }
  10566. int
  10567. PyUnicode_IsIdentifier(PyObject *self)
  10568. {
  10569. Py_ssize_t i = _PyUnicode_ScanIdentifier(self);
  10570. Py_ssize_t len = PyUnicode_GET_LENGTH(self);
  10571. /* an empty string is not a valid identifier */
  10572. return len && i == len;
  10573. }
  10574. /*[clinic input]
  10575. str.isidentifier as unicode_isidentifier
  10576. Return True if the string is a valid Python identifier, False otherwise.
  10577. Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
  10578. such as "def" or "class".
  10579. [clinic start generated code]*/
  10580. static PyObject *
  10581. unicode_isidentifier_impl(PyObject *self)
  10582. /*[clinic end generated code: output=fe585a9666572905 input=2d807a104f21c0c5]*/
  10583. {
  10584. return PyBool_FromLong(PyUnicode_IsIdentifier(self));
  10585. }
  10586. /*[clinic input]
  10587. str.isprintable as unicode_isprintable
  10588. Return True if the string is printable, False otherwise.
  10589. A string is printable if all of its characters are considered printable in
  10590. repr() or if it is empty.
  10591. [clinic start generated code]*/
  10592. static PyObject *
  10593. unicode_isprintable_impl(PyObject *self)
  10594. /*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
  10595. {
  10596. Py_ssize_t i, length;
  10597. int kind;
  10598. const void *data;
  10599. length = PyUnicode_GET_LENGTH(self);
  10600. kind = PyUnicode_KIND(self);
  10601. data = PyUnicode_DATA(self);
  10602. /* Shortcut for single character strings */
  10603. if (length == 1)
  10604. return PyBool_FromLong(
  10605. Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
  10606. for (i = 0; i < length; i++) {
  10607. if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
  10608. Py_RETURN_FALSE;
  10609. }
  10610. }
  10611. Py_RETURN_TRUE;
  10612. }
  10613. /*[clinic input]
  10614. str.join as unicode_join
  10615. iterable: object
  10616. /
  10617. Concatenate any number of strings.
  10618. The string whose method is called is inserted in between each given string.
  10619. The result is returned as a new string.
  10620. Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
  10621. [clinic start generated code]*/
  10622. static PyObject *
  10623. unicode_join(PyObject *self, PyObject *iterable)
  10624. /*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
  10625. {
  10626. return PyUnicode_Join(self, iterable);
  10627. }
  10628. static Py_ssize_t
  10629. unicode_length(PyObject *self)
  10630. {
  10631. return PyUnicode_GET_LENGTH(self);
  10632. }
  10633. /*[clinic input]
  10634. str.ljust as unicode_ljust
  10635. width: Py_ssize_t
  10636. fillchar: Py_UCS4 = ' '
  10637. /
  10638. Return a left-justified string of length width.
  10639. Padding is done using the specified fill character (default is a space).
  10640. [clinic start generated code]*/
  10641. static PyObject *
  10642. unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
  10643. /*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
  10644. {
  10645. if (PyUnicode_GET_LENGTH(self) >= width)
  10646. return unicode_result_unchanged(self);
  10647. return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
  10648. }
  10649. /*[clinic input]
  10650. str.lower as unicode_lower
  10651. Return a copy of the string converted to lowercase.
  10652. [clinic start generated code]*/
  10653. static PyObject *
  10654. unicode_lower_impl(PyObject *self)
  10655. /*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
  10656. {
  10657. if (PyUnicode_IS_ASCII(self))
  10658. return ascii_upper_or_lower(self, 1);
  10659. return case_operation(self, do_lower);
  10660. }
  10661. #define LEFTSTRIP 0
  10662. #define RIGHTSTRIP 1
  10663. #define BOTHSTRIP 2
  10664. /* Arrays indexed by above */
  10665. static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
  10666. #define STRIPNAME(i) (stripfuncnames[i])
  10667. /* externally visible for str.strip(unicode) */
  10668. PyObject *
  10669. _PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
  10670. {
  10671. const void *data;
  10672. int kind;
  10673. Py_ssize_t i, j, len;
  10674. BLOOM_MASK sepmask;
  10675. Py_ssize_t seplen;
  10676. kind = PyUnicode_KIND(self);
  10677. data = PyUnicode_DATA(self);
  10678. len = PyUnicode_GET_LENGTH(self);
  10679. seplen = PyUnicode_GET_LENGTH(sepobj);
  10680. sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
  10681. PyUnicode_DATA(sepobj),
  10682. seplen);
  10683. i = 0;
  10684. if (striptype != RIGHTSTRIP) {
  10685. while (i < len) {
  10686. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10687. if (!BLOOM(sepmask, ch))
  10688. break;
  10689. if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
  10690. break;
  10691. i++;
  10692. }
  10693. }
  10694. j = len;
  10695. if (striptype != LEFTSTRIP) {
  10696. j--;
  10697. while (j >= i) {
  10698. Py_UCS4 ch = PyUnicode_READ(kind, data, j);
  10699. if (!BLOOM(sepmask, ch))
  10700. break;
  10701. if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
  10702. break;
  10703. j--;
  10704. }
  10705. j++;
  10706. }
  10707. return PyUnicode_Substring(self, i, j);
  10708. }
  10709. PyObject*
  10710. PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
  10711. {
  10712. const unsigned char *data;
  10713. int kind;
  10714. Py_ssize_t length;
  10715. length = PyUnicode_GET_LENGTH(self);
  10716. end = Py_MIN(end, length);
  10717. if (start == 0 && end == length)
  10718. return unicode_result_unchanged(self);
  10719. if (start < 0 || end < 0) {
  10720. PyErr_SetString(PyExc_IndexError, "string index out of range");
  10721. return NULL;
  10722. }
  10723. if (start >= length || end < start)
  10724. _Py_RETURN_UNICODE_EMPTY();
  10725. length = end - start;
  10726. if (PyUnicode_IS_ASCII(self)) {
  10727. data = PyUnicode_1BYTE_DATA(self);
  10728. return _PyUnicode_FromASCII((const char*)(data + start), length);
  10729. }
  10730. else {
  10731. kind = PyUnicode_KIND(self);
  10732. data = PyUnicode_1BYTE_DATA(self);
  10733. return PyUnicode_FromKindAndData(kind,
  10734. data + kind * start,
  10735. length);
  10736. }
  10737. }
  10738. static PyObject *
  10739. do_strip(PyObject *self, int striptype)
  10740. {
  10741. Py_ssize_t len, i, j;
  10742. len = PyUnicode_GET_LENGTH(self);
  10743. if (PyUnicode_IS_ASCII(self)) {
  10744. const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
  10745. i = 0;
  10746. if (striptype != RIGHTSTRIP) {
  10747. while (i < len) {
  10748. Py_UCS1 ch = data[i];
  10749. if (!_Py_ascii_whitespace[ch])
  10750. break;
  10751. i++;
  10752. }
  10753. }
  10754. j = len;
  10755. if (striptype != LEFTSTRIP) {
  10756. j--;
  10757. while (j >= i) {
  10758. Py_UCS1 ch = data[j];
  10759. if (!_Py_ascii_whitespace[ch])
  10760. break;
  10761. j--;
  10762. }
  10763. j++;
  10764. }
  10765. }
  10766. else {
  10767. int kind = PyUnicode_KIND(self);
  10768. const void *data = PyUnicode_DATA(self);
  10769. i = 0;
  10770. if (striptype != RIGHTSTRIP) {
  10771. while (i < len) {
  10772. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10773. if (!Py_UNICODE_ISSPACE(ch))
  10774. break;
  10775. i++;
  10776. }
  10777. }
  10778. j = len;
  10779. if (striptype != LEFTSTRIP) {
  10780. j--;
  10781. while (j >= i) {
  10782. Py_UCS4 ch = PyUnicode_READ(kind, data, j);
  10783. if (!Py_UNICODE_ISSPACE(ch))
  10784. break;
  10785. j--;
  10786. }
  10787. j++;
  10788. }
  10789. }
  10790. return PyUnicode_Substring(self, i, j);
  10791. }
  10792. static PyObject *
  10793. do_argstrip(PyObject *self, int striptype, PyObject *sep)
  10794. {
  10795. if (sep != Py_None) {
  10796. if (PyUnicode_Check(sep))
  10797. return _PyUnicode_XStrip(self, striptype, sep);
  10798. else {
  10799. PyErr_Format(PyExc_TypeError,
  10800. "%s arg must be None or str",
  10801. STRIPNAME(striptype));
  10802. return NULL;
  10803. }
  10804. }
  10805. return do_strip(self, striptype);
  10806. }
  10807. /*[clinic input]
  10808. str.strip as unicode_strip
  10809. chars: object = None
  10810. /
  10811. Return a copy of the string with leading and trailing whitespace removed.
  10812. If chars is given and not None, remove characters in chars instead.
  10813. [clinic start generated code]*/
  10814. static PyObject *
  10815. unicode_strip_impl(PyObject *self, PyObject *chars)
  10816. /*[clinic end generated code: output=ca19018454345d57 input=385289c6f423b954]*/
  10817. {
  10818. return do_argstrip(self, BOTHSTRIP, chars);
  10819. }
  10820. /*[clinic input]
  10821. str.lstrip as unicode_lstrip
  10822. chars: object = None
  10823. /
  10824. Return a copy of the string with leading whitespace removed.
  10825. If chars is given and not None, remove characters in chars instead.
  10826. [clinic start generated code]*/
  10827. static PyObject *
  10828. unicode_lstrip_impl(PyObject *self, PyObject *chars)
  10829. /*[clinic end generated code: output=3b43683251f79ca7 input=529f9f3834448671]*/
  10830. {
  10831. return do_argstrip(self, LEFTSTRIP, chars);
  10832. }
  10833. /*[clinic input]
  10834. str.rstrip as unicode_rstrip
  10835. chars: object = None
  10836. /
  10837. Return a copy of the string with trailing whitespace removed.
  10838. If chars is given and not None, remove characters in chars instead.
  10839. [clinic start generated code]*/
  10840. static PyObject *
  10841. unicode_rstrip_impl(PyObject *self, PyObject *chars)
  10842. /*[clinic end generated code: output=4a59230017cc3b7a input=62566c627916557f]*/
  10843. {
  10844. return do_argstrip(self, RIGHTSTRIP, chars);
  10845. }
  10846. static PyObject*
  10847. unicode_repeat(PyObject *str, Py_ssize_t len)
  10848. {
  10849. PyObject *u;
  10850. Py_ssize_t nchars, n;
  10851. if (len < 1)
  10852. _Py_RETURN_UNICODE_EMPTY();
  10853. /* no repeat, return original string */
  10854. if (len == 1)
  10855. return unicode_result_unchanged(str);
  10856. if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
  10857. PyErr_SetString(PyExc_OverflowError,
  10858. "repeated string is too long");
  10859. return NULL;
  10860. }
  10861. nchars = len * PyUnicode_GET_LENGTH(str);
  10862. u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
  10863. if (!u)
  10864. return NULL;
  10865. assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
  10866. if (PyUnicode_GET_LENGTH(str) == 1) {
  10867. int kind = PyUnicode_KIND(str);
  10868. Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
  10869. if (kind == PyUnicode_1BYTE_KIND) {
  10870. void *to = PyUnicode_DATA(u);
  10871. memset(to, (unsigned char)fill_char, len);
  10872. }
  10873. else if (kind == PyUnicode_2BYTE_KIND) {
  10874. Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
  10875. for (n = 0; n < len; ++n)
  10876. ucs2[n] = fill_char;
  10877. } else {
  10878. Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
  10879. assert(kind == PyUnicode_4BYTE_KIND);
  10880. for (n = 0; n < len; ++n)
  10881. ucs4[n] = fill_char;
  10882. }
  10883. }
  10884. else {
  10885. Py_ssize_t char_size = PyUnicode_KIND(str);
  10886. char *to = (char *) PyUnicode_DATA(u);
  10887. _PyBytes_Repeat(to, nchars * char_size, PyUnicode_DATA(str),
  10888. PyUnicode_GET_LENGTH(str) * char_size);
  10889. }
  10890. assert(_PyUnicode_CheckConsistency(u, 1));
  10891. return u;
  10892. }
  10893. PyObject *
  10894. PyUnicode_Replace(PyObject *str,
  10895. PyObject *substr,
  10896. PyObject *replstr,
  10897. Py_ssize_t maxcount)
  10898. {
  10899. if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
  10900. ensure_unicode(replstr) < 0)
  10901. return NULL;
  10902. return replace(str, substr, replstr, maxcount);
  10903. }
  10904. /*[clinic input]
  10905. str.replace as unicode_replace
  10906. old: unicode
  10907. new: unicode
  10908. count: Py_ssize_t = -1
  10909. Maximum number of occurrences to replace.
  10910. -1 (the default value) means replace all occurrences.
  10911. /
  10912. Return a copy with all occurrences of substring old replaced by new.
  10913. If the optional argument count is given, only the first count occurrences are
  10914. replaced.
  10915. [clinic start generated code]*/
  10916. static PyObject *
  10917. unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
  10918. Py_ssize_t count)
  10919. /*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
  10920. {
  10921. return replace(self, old, new, count);
  10922. }
  10923. /*[clinic input]
  10924. str.removeprefix as unicode_removeprefix
  10925. prefix: unicode
  10926. /
  10927. Return a str with the given prefix string removed if present.
  10928. If the string starts with the prefix string, return string[len(prefix):].
  10929. Otherwise, return a copy of the original string.
  10930. [clinic start generated code]*/
  10931. static PyObject *
  10932. unicode_removeprefix_impl(PyObject *self, PyObject *prefix)
  10933. /*[clinic end generated code: output=f1e5945e9763bcb9 input=27ec40b99a37eb88]*/
  10934. {
  10935. int match = tailmatch(self, prefix, 0, PY_SSIZE_T_MAX, -1);
  10936. if (match == -1) {
  10937. return NULL;
  10938. }
  10939. if (match) {
  10940. return PyUnicode_Substring(self, PyUnicode_GET_LENGTH(prefix),
  10941. PyUnicode_GET_LENGTH(self));
  10942. }
  10943. return unicode_result_unchanged(self);
  10944. }
  10945. /*[clinic input]
  10946. str.removesuffix as unicode_removesuffix
  10947. suffix: unicode
  10948. /
  10949. Return a str with the given suffix string removed if present.
  10950. If the string ends with the suffix string and that suffix is not empty,
  10951. return string[:-len(suffix)]. Otherwise, return a copy of the original
  10952. string.
  10953. [clinic start generated code]*/
  10954. static PyObject *
  10955. unicode_removesuffix_impl(PyObject *self, PyObject *suffix)
  10956. /*[clinic end generated code: output=d36629e227636822 input=12cc32561e769be4]*/
  10957. {
  10958. int match = tailmatch(self, suffix, 0, PY_SSIZE_T_MAX, +1);
  10959. if (match == -1) {
  10960. return NULL;
  10961. }
  10962. if (match) {
  10963. return PyUnicode_Substring(self, 0, PyUnicode_GET_LENGTH(self)
  10964. - PyUnicode_GET_LENGTH(suffix));
  10965. }
  10966. return unicode_result_unchanged(self);
  10967. }
  10968. static PyObject *
  10969. unicode_repr(PyObject *unicode)
  10970. {
  10971. PyObject *repr;
  10972. Py_ssize_t isize;
  10973. Py_ssize_t osize, squote, dquote, i, o;
  10974. Py_UCS4 max, quote;
  10975. int ikind, okind, unchanged;
  10976. const void *idata;
  10977. void *odata;
  10978. isize = PyUnicode_GET_LENGTH(unicode);
  10979. idata = PyUnicode_DATA(unicode);
  10980. /* Compute length of output, quote characters, and
  10981. maximum character */
  10982. osize = 0;
  10983. max = 127;
  10984. squote = dquote = 0;
  10985. ikind = PyUnicode_KIND(unicode);
  10986. for (i = 0; i < isize; i++) {
  10987. Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
  10988. Py_ssize_t incr = 1;
  10989. switch (ch) {
  10990. case '\'': squote++; break;
  10991. case '"': dquote++; break;
  10992. case '\\': case '\t': case '\r': case '\n':
  10993. incr = 2;
  10994. break;
  10995. default:
  10996. /* Fast-path ASCII */
  10997. if (ch < ' ' || ch == 0x7f)
  10998. incr = 4; /* \xHH */
  10999. else if (ch < 0x7f)
  11000. ;
  11001. else if (Py_UNICODE_ISPRINTABLE(ch))
  11002. max = ch > max ? ch : max;
  11003. else if (ch < 0x100)
  11004. incr = 4; /* \xHH */
  11005. else if (ch < 0x10000)
  11006. incr = 6; /* \uHHHH */
  11007. else
  11008. incr = 10; /* \uHHHHHHHH */
  11009. }
  11010. if (osize > PY_SSIZE_T_MAX - incr) {
  11011. PyErr_SetString(PyExc_OverflowError,
  11012. "string is too long to generate repr");
  11013. return NULL;
  11014. }
  11015. osize += incr;
  11016. }
  11017. quote = '\'';
  11018. unchanged = (osize == isize);
  11019. if (squote) {
  11020. unchanged = 0;
  11021. if (dquote)
  11022. /* Both squote and dquote present. Use squote,
  11023. and escape them */
  11024. osize += squote;
  11025. else
  11026. quote = '"';
  11027. }
  11028. osize += 2; /* quotes */
  11029. repr = PyUnicode_New(osize, max);
  11030. if (repr == NULL)
  11031. return NULL;
  11032. okind = PyUnicode_KIND(repr);
  11033. odata = PyUnicode_DATA(repr);
  11034. PyUnicode_WRITE(okind, odata, 0, quote);
  11035. PyUnicode_WRITE(okind, odata, osize-1, quote);
  11036. if (unchanged) {
  11037. _PyUnicode_FastCopyCharacters(repr, 1,
  11038. unicode, 0,
  11039. isize);
  11040. }
  11041. else {
  11042. for (i = 0, o = 1; i < isize; i++) {
  11043. Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
  11044. /* Escape quotes and backslashes */
  11045. if ((ch == quote) || (ch == '\\')) {
  11046. PyUnicode_WRITE(okind, odata, o++, '\\');
  11047. PyUnicode_WRITE(okind, odata, o++, ch);
  11048. continue;
  11049. }
  11050. /* Map special whitespace to '\t', \n', '\r' */
  11051. if (ch == '\t') {
  11052. PyUnicode_WRITE(okind, odata, o++, '\\');
  11053. PyUnicode_WRITE(okind, odata, o++, 't');
  11054. }
  11055. else if (ch == '\n') {
  11056. PyUnicode_WRITE(okind, odata, o++, '\\');
  11057. PyUnicode_WRITE(okind, odata, o++, 'n');
  11058. }
  11059. else if (ch == '\r') {
  11060. PyUnicode_WRITE(okind, odata, o++, '\\');
  11061. PyUnicode_WRITE(okind, odata, o++, 'r');
  11062. }
  11063. /* Map non-printable US ASCII to '\xhh' */
  11064. else if (ch < ' ' || ch == 0x7F) {
  11065. PyUnicode_WRITE(okind, odata, o++, '\\');
  11066. PyUnicode_WRITE(okind, odata, o++, 'x');
  11067. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
  11068. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
  11069. }
  11070. /* Copy ASCII characters as-is */
  11071. else if (ch < 0x7F) {
  11072. PyUnicode_WRITE(okind, odata, o++, ch);
  11073. }
  11074. /* Non-ASCII characters */
  11075. else {
  11076. /* Map Unicode whitespace and control characters
  11077. (categories Z* and C* except ASCII space)
  11078. */
  11079. if (!Py_UNICODE_ISPRINTABLE(ch)) {
  11080. PyUnicode_WRITE(okind, odata, o++, '\\');
  11081. /* Map 8-bit characters to '\xhh' */
  11082. if (ch <= 0xff) {
  11083. PyUnicode_WRITE(okind, odata, o++, 'x');
  11084. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
  11085. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
  11086. }
  11087. /* Map 16-bit characters to '\uxxxx' */
  11088. else if (ch <= 0xffff) {
  11089. PyUnicode_WRITE(okind, odata, o++, 'u');
  11090. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
  11091. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
  11092. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
  11093. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
  11094. }
  11095. /* Map 21-bit characters to '\U00xxxxxx' */
  11096. else {
  11097. PyUnicode_WRITE(okind, odata, o++, 'U');
  11098. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
  11099. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
  11100. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
  11101. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
  11102. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
  11103. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
  11104. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
  11105. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
  11106. }
  11107. }
  11108. /* Copy characters as-is */
  11109. else {
  11110. PyUnicode_WRITE(okind, odata, o++, ch);
  11111. }
  11112. }
  11113. }
  11114. }
  11115. /* Closing quote already added at the beginning */
  11116. assert(_PyUnicode_CheckConsistency(repr, 1));
  11117. return repr;
  11118. }
  11119. PyDoc_STRVAR(rfind__doc__,
  11120. "S.rfind(sub[, start[, end]]) -> int\n\
  11121. \n\
  11122. Return the highest index in S where substring sub is found,\n\
  11123. such that sub is contained within S[start:end]. Optional\n\
  11124. arguments start and end are interpreted as in slice notation.\n\
  11125. \n\
  11126. Return -1 on failure.");
  11127. static PyObject *
  11128. unicode_rfind(PyObject *self, PyObject *args)
  11129. {
  11130. /* initialize variables to prevent gcc warning */
  11131. PyObject *substring = NULL;
  11132. Py_ssize_t start = 0;
  11133. Py_ssize_t end = 0;
  11134. Py_ssize_t result;
  11135. if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
  11136. return NULL;
  11137. result = any_find_slice(self, substring, start, end, -1);
  11138. if (result == -2)
  11139. return NULL;
  11140. return PyLong_FromSsize_t(result);
  11141. }
  11142. PyDoc_STRVAR(rindex__doc__,
  11143. "S.rindex(sub[, start[, end]]) -> int\n\
  11144. \n\
  11145. Return the highest index in S where substring sub is found,\n\
  11146. such that sub is contained within S[start:end]. Optional\n\
  11147. arguments start and end are interpreted as in slice notation.\n\
  11148. \n\
  11149. Raises ValueError when the substring is not found.");
  11150. static PyObject *
  11151. unicode_rindex(PyObject *self, PyObject *args)
  11152. {
  11153. /* initialize variables to prevent gcc warning */
  11154. PyObject *substring = NULL;
  11155. Py_ssize_t start = 0;
  11156. Py_ssize_t end = 0;
  11157. Py_ssize_t result;
  11158. if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
  11159. return NULL;
  11160. result = any_find_slice(self, substring, start, end, -1);
  11161. if (result == -2)
  11162. return NULL;
  11163. if (result < 0) {
  11164. PyErr_SetString(PyExc_ValueError, "substring not found");
  11165. return NULL;
  11166. }
  11167. return PyLong_FromSsize_t(result);
  11168. }
  11169. /*[clinic input]
  11170. str.rjust as unicode_rjust
  11171. width: Py_ssize_t
  11172. fillchar: Py_UCS4 = ' '
  11173. /
  11174. Return a right-justified string of length width.
  11175. Padding is done using the specified fill character (default is a space).
  11176. [clinic start generated code]*/
  11177. static PyObject *
  11178. unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
  11179. /*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
  11180. {
  11181. if (PyUnicode_GET_LENGTH(self) >= width)
  11182. return unicode_result_unchanged(self);
  11183. return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
  11184. }
  11185. PyObject *
  11186. PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
  11187. {
  11188. if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
  11189. return NULL;
  11190. return split(s, sep, maxsplit);
  11191. }
  11192. /*[clinic input]
  11193. str.split as unicode_split
  11194. sep: object = None
  11195. The separator used to split the string.
  11196. When set to None (the default value), will split on any whitespace
  11197. character (including \n \r \t \f and spaces) and will discard
  11198. empty strings from the result.
  11199. maxsplit: Py_ssize_t = -1
  11200. Maximum number of splits.
  11201. -1 (the default value) means no limit.
  11202. Return a list of the substrings in the string, using sep as the separator string.
  11203. Splitting starts at the front of the string and works to the end.
  11204. Note, str.split() is mainly useful for data that has been intentionally
  11205. delimited. With natural text that includes punctuation, consider using
  11206. the regular expression module.
  11207. [clinic start generated code]*/
  11208. static PyObject *
  11209. unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
  11210. /*[clinic end generated code: output=3a65b1db356948dc input=a29bcc0c7a5af0eb]*/
  11211. {
  11212. if (sep == Py_None)
  11213. return split(self, NULL, maxsplit);
  11214. if (PyUnicode_Check(sep))
  11215. return split(self, sep, maxsplit);
  11216. PyErr_Format(PyExc_TypeError,
  11217. "must be str or None, not %.100s",
  11218. Py_TYPE(sep)->tp_name);
  11219. return NULL;
  11220. }
  11221. PyObject *
  11222. PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
  11223. {
  11224. PyObject* out;
  11225. int kind1, kind2;
  11226. const void *buf1, *buf2;
  11227. Py_ssize_t len1, len2;
  11228. if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
  11229. return NULL;
  11230. kind1 = PyUnicode_KIND(str_obj);
  11231. kind2 = PyUnicode_KIND(sep_obj);
  11232. len1 = PyUnicode_GET_LENGTH(str_obj);
  11233. len2 = PyUnicode_GET_LENGTH(sep_obj);
  11234. if (kind1 < kind2 || len1 < len2) {
  11235. PyObject *empty = unicode_get_empty(); // Borrowed reference
  11236. return PyTuple_Pack(3, str_obj, empty, empty);
  11237. }
  11238. buf1 = PyUnicode_DATA(str_obj);
  11239. buf2 = PyUnicode_DATA(sep_obj);
  11240. if (kind2 != kind1) {
  11241. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  11242. if (!buf2)
  11243. return NULL;
  11244. }
  11245. switch (kind1) {
  11246. case PyUnicode_1BYTE_KIND:
  11247. if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
  11248. out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11249. else
  11250. out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11251. break;
  11252. case PyUnicode_2BYTE_KIND:
  11253. out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11254. break;
  11255. case PyUnicode_4BYTE_KIND:
  11256. out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11257. break;
  11258. default:
  11259. Py_UNREACHABLE();
  11260. }
  11261. assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
  11262. if (kind2 != kind1)
  11263. PyMem_Free((void *)buf2);
  11264. return out;
  11265. }
  11266. PyObject *
  11267. PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
  11268. {
  11269. PyObject* out;
  11270. int kind1, kind2;
  11271. const void *buf1, *buf2;
  11272. Py_ssize_t len1, len2;
  11273. if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
  11274. return NULL;
  11275. kind1 = PyUnicode_KIND(str_obj);
  11276. kind2 = PyUnicode_KIND(sep_obj);
  11277. len1 = PyUnicode_GET_LENGTH(str_obj);
  11278. len2 = PyUnicode_GET_LENGTH(sep_obj);
  11279. if (kind1 < kind2 || len1 < len2) {
  11280. PyObject *empty = unicode_get_empty(); // Borrowed reference
  11281. return PyTuple_Pack(3, empty, empty, str_obj);
  11282. }
  11283. buf1 = PyUnicode_DATA(str_obj);
  11284. buf2 = PyUnicode_DATA(sep_obj);
  11285. if (kind2 != kind1) {
  11286. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  11287. if (!buf2)
  11288. return NULL;
  11289. }
  11290. switch (kind1) {
  11291. case PyUnicode_1BYTE_KIND:
  11292. if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
  11293. out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11294. else
  11295. out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11296. break;
  11297. case PyUnicode_2BYTE_KIND:
  11298. out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11299. break;
  11300. case PyUnicode_4BYTE_KIND:
  11301. out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11302. break;
  11303. default:
  11304. Py_UNREACHABLE();
  11305. }
  11306. assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
  11307. if (kind2 != kind1)
  11308. PyMem_Free((void *)buf2);
  11309. return out;
  11310. }
  11311. /*[clinic input]
  11312. str.partition as unicode_partition
  11313. sep: object
  11314. /
  11315. Partition the string into three parts using the given separator.
  11316. This will search for the separator in the string. If the separator is found,
  11317. returns a 3-tuple containing the part before the separator, the separator
  11318. itself, and the part after it.
  11319. If the separator is not found, returns a 3-tuple containing the original string
  11320. and two empty strings.
  11321. [clinic start generated code]*/
  11322. static PyObject *
  11323. unicode_partition(PyObject *self, PyObject *sep)
  11324. /*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
  11325. {
  11326. return PyUnicode_Partition(self, sep);
  11327. }
  11328. /*[clinic input]
  11329. str.rpartition as unicode_rpartition = str.partition
  11330. Partition the string into three parts using the given separator.
  11331. This will search for the separator in the string, starting at the end. If
  11332. the separator is found, returns a 3-tuple containing the part before the
  11333. separator, the separator itself, and the part after it.
  11334. If the separator is not found, returns a 3-tuple containing two empty strings
  11335. and the original string.
  11336. [clinic start generated code]*/
  11337. static PyObject *
  11338. unicode_rpartition(PyObject *self, PyObject *sep)
  11339. /*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
  11340. {
  11341. return PyUnicode_RPartition(self, sep);
  11342. }
  11343. PyObject *
  11344. PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
  11345. {
  11346. if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
  11347. return NULL;
  11348. return rsplit(s, sep, maxsplit);
  11349. }
  11350. /*[clinic input]
  11351. str.rsplit as unicode_rsplit = str.split
  11352. Return a list of the substrings in the string, using sep as the separator string.
  11353. Splitting starts at the end of the string and works to the front.
  11354. [clinic start generated code]*/
  11355. static PyObject *
  11356. unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
  11357. /*[clinic end generated code: output=c2b815c63bcabffc input=ea78406060fce33c]*/
  11358. {
  11359. if (sep == Py_None)
  11360. return rsplit(self, NULL, maxsplit);
  11361. if (PyUnicode_Check(sep))
  11362. return rsplit(self, sep, maxsplit);
  11363. PyErr_Format(PyExc_TypeError,
  11364. "must be str or None, not %.100s",
  11365. Py_TYPE(sep)->tp_name);
  11366. return NULL;
  11367. }
  11368. /*[clinic input]
  11369. str.splitlines as unicode_splitlines
  11370. keepends: bool = False
  11371. Return a list of the lines in the string, breaking at line boundaries.
  11372. Line breaks are not included in the resulting list unless keepends is given and
  11373. true.
  11374. [clinic start generated code]*/
  11375. static PyObject *
  11376. unicode_splitlines_impl(PyObject *self, int keepends)
  11377. /*[clinic end generated code: output=f664dcdad153ec40 input=ba6ad05ee85d2b55]*/
  11378. {
  11379. return PyUnicode_Splitlines(self, keepends);
  11380. }
  11381. static
  11382. PyObject *unicode_str(PyObject *self)
  11383. {
  11384. return unicode_result_unchanged(self);
  11385. }
  11386. /*[clinic input]
  11387. str.swapcase as unicode_swapcase
  11388. Convert uppercase characters to lowercase and lowercase characters to uppercase.
  11389. [clinic start generated code]*/
  11390. static PyObject *
  11391. unicode_swapcase_impl(PyObject *self)
  11392. /*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
  11393. {
  11394. return case_operation(self, do_swapcase);
  11395. }
  11396. /*[clinic input]
  11397. @staticmethod
  11398. str.maketrans as unicode_maketrans
  11399. x: object
  11400. y: unicode=NULL
  11401. z: unicode=NULL
  11402. /
  11403. Return a translation table usable for str.translate().
  11404. If there is only one argument, it must be a dictionary mapping Unicode
  11405. ordinals (integers) or characters to Unicode ordinals, strings or None.
  11406. Character keys will be then converted to ordinals.
  11407. If there are two arguments, they must be strings of equal length, and
  11408. in the resulting dictionary, each character in x will be mapped to the
  11409. character at the same position in y. If there is a third argument, it
  11410. must be a string, whose characters will be mapped to None in the result.
  11411. [clinic start generated code]*/
  11412. static PyObject *
  11413. unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
  11414. /*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
  11415. {
  11416. PyObject *new = NULL, *key, *value;
  11417. Py_ssize_t i = 0;
  11418. int res;
  11419. new = PyDict_New();
  11420. if (!new)
  11421. return NULL;
  11422. if (y != NULL) {
  11423. int x_kind, y_kind, z_kind;
  11424. const void *x_data, *y_data, *z_data;
  11425. /* x must be a string too, of equal length */
  11426. if (!PyUnicode_Check(x)) {
  11427. PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
  11428. "be a string if there is a second argument");
  11429. goto err;
  11430. }
  11431. if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
  11432. PyErr_SetString(PyExc_ValueError, "the first two maketrans "
  11433. "arguments must have equal length");
  11434. goto err;
  11435. }
  11436. /* create entries for translating chars in x to those in y */
  11437. x_kind = PyUnicode_KIND(x);
  11438. y_kind = PyUnicode_KIND(y);
  11439. x_data = PyUnicode_DATA(x);
  11440. y_data = PyUnicode_DATA(y);
  11441. for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
  11442. key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
  11443. if (!key)
  11444. goto err;
  11445. value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
  11446. if (!value) {
  11447. Py_DECREF(key);
  11448. goto err;
  11449. }
  11450. res = PyDict_SetItem(new, key, value);
  11451. Py_DECREF(key);
  11452. Py_DECREF(value);
  11453. if (res < 0)
  11454. goto err;
  11455. }
  11456. /* create entries for deleting chars in z */
  11457. if (z != NULL) {
  11458. z_kind = PyUnicode_KIND(z);
  11459. z_data = PyUnicode_DATA(z);
  11460. for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
  11461. key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
  11462. if (!key)
  11463. goto err;
  11464. res = PyDict_SetItem(new, key, Py_None);
  11465. Py_DECREF(key);
  11466. if (res < 0)
  11467. goto err;
  11468. }
  11469. }
  11470. } else {
  11471. int kind;
  11472. const void *data;
  11473. /* x must be a dict */
  11474. if (!PyDict_CheckExact(x)) {
  11475. PyErr_SetString(PyExc_TypeError, "if you give only one argument "
  11476. "to maketrans it must be a dict");
  11477. goto err;
  11478. }
  11479. /* copy entries into the new dict, converting string keys to int keys */
  11480. while (PyDict_Next(x, &i, &key, &value)) {
  11481. if (PyUnicode_Check(key)) {
  11482. /* convert string keys to integer keys */
  11483. PyObject *newkey;
  11484. if (PyUnicode_GET_LENGTH(key) != 1) {
  11485. PyErr_SetString(PyExc_ValueError, "string keys in translate "
  11486. "table must be of length 1");
  11487. goto err;
  11488. }
  11489. kind = PyUnicode_KIND(key);
  11490. data = PyUnicode_DATA(key);
  11491. newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
  11492. if (!newkey)
  11493. goto err;
  11494. res = PyDict_SetItem(new, newkey, value);
  11495. Py_DECREF(newkey);
  11496. if (res < 0)
  11497. goto err;
  11498. } else if (PyLong_Check(key)) {
  11499. /* just keep integer keys */
  11500. if (PyDict_SetItem(new, key, value) < 0)
  11501. goto err;
  11502. } else {
  11503. PyErr_SetString(PyExc_TypeError, "keys in translate table must "
  11504. "be strings or integers");
  11505. goto err;
  11506. }
  11507. }
  11508. }
  11509. return new;
  11510. err:
  11511. Py_DECREF(new);
  11512. return NULL;
  11513. }
  11514. /*[clinic input]
  11515. str.translate as unicode_translate
  11516. table: object
  11517. Translation table, which must be a mapping of Unicode ordinals to
  11518. Unicode ordinals, strings, or None.
  11519. /
  11520. Replace each character in the string using the given translation table.
  11521. The table must implement lookup/indexing via __getitem__, for instance a
  11522. dictionary or list. If this operation raises LookupError, the character is
  11523. left untouched. Characters mapped to None are deleted.
  11524. [clinic start generated code]*/
  11525. static PyObject *
  11526. unicode_translate(PyObject *self, PyObject *table)
  11527. /*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
  11528. {
  11529. return _PyUnicode_TranslateCharmap(self, table, "ignore");
  11530. }
  11531. /*[clinic input]
  11532. str.upper as unicode_upper
  11533. Return a copy of the string converted to uppercase.
  11534. [clinic start generated code]*/
  11535. static PyObject *
  11536. unicode_upper_impl(PyObject *self)
  11537. /*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
  11538. {
  11539. if (PyUnicode_IS_ASCII(self))
  11540. return ascii_upper_or_lower(self, 0);
  11541. return case_operation(self, do_upper);
  11542. }
  11543. /*[clinic input]
  11544. str.zfill as unicode_zfill
  11545. width: Py_ssize_t
  11546. /
  11547. Pad a numeric string with zeros on the left, to fill a field of the given width.
  11548. The string is never truncated.
  11549. [clinic start generated code]*/
  11550. static PyObject *
  11551. unicode_zfill_impl(PyObject *self, Py_ssize_t width)
  11552. /*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
  11553. {
  11554. Py_ssize_t fill;
  11555. PyObject *u;
  11556. int kind;
  11557. const void *data;
  11558. Py_UCS4 chr;
  11559. if (PyUnicode_GET_LENGTH(self) >= width)
  11560. return unicode_result_unchanged(self);
  11561. fill = width - PyUnicode_GET_LENGTH(self);
  11562. u = pad(self, fill, 0, '0');
  11563. if (u == NULL)
  11564. return NULL;
  11565. kind = PyUnicode_KIND(u);
  11566. data = PyUnicode_DATA(u);
  11567. chr = PyUnicode_READ(kind, data, fill);
  11568. if (chr == '+' || chr == '-') {
  11569. /* move sign to beginning of string */
  11570. PyUnicode_WRITE(kind, data, 0, chr);
  11571. PyUnicode_WRITE(kind, data, fill, '0');
  11572. }
  11573. assert(_PyUnicode_CheckConsistency(u, 1));
  11574. return u;
  11575. }
  11576. PyDoc_STRVAR(startswith__doc__,
  11577. "S.startswith(prefix[, start[, end]]) -> bool\n\
  11578. \n\
  11579. Return True if S starts with the specified prefix, False otherwise.\n\
  11580. With optional start, test S beginning at that position.\n\
  11581. With optional end, stop comparing S at that position.\n\
  11582. prefix can also be a tuple of strings to try.");
  11583. static PyObject *
  11584. unicode_startswith(PyObject *self,
  11585. PyObject *args)
  11586. {
  11587. PyObject *subobj;
  11588. PyObject *substring;
  11589. Py_ssize_t start = 0;
  11590. Py_ssize_t end = PY_SSIZE_T_MAX;
  11591. int result;
  11592. if (!asciilib_parse_args_finds("startswith", args, &subobj, &start, &end))
  11593. return NULL;
  11594. if (PyTuple_Check(subobj)) {
  11595. Py_ssize_t i;
  11596. for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
  11597. substring = PyTuple_GET_ITEM(subobj, i);
  11598. if (!PyUnicode_Check(substring)) {
  11599. PyErr_Format(PyExc_TypeError,
  11600. "tuple for startswith must only contain str, "
  11601. "not %.100s",
  11602. Py_TYPE(substring)->tp_name);
  11603. return NULL;
  11604. }
  11605. result = tailmatch(self, substring, start, end, -1);
  11606. if (result == -1)
  11607. return NULL;
  11608. if (result) {
  11609. Py_RETURN_TRUE;
  11610. }
  11611. }
  11612. /* nothing matched */
  11613. Py_RETURN_FALSE;
  11614. }
  11615. if (!PyUnicode_Check(subobj)) {
  11616. PyErr_Format(PyExc_TypeError,
  11617. "startswith first arg must be str or "
  11618. "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
  11619. return NULL;
  11620. }
  11621. result = tailmatch(self, subobj, start, end, -1);
  11622. if (result == -1)
  11623. return NULL;
  11624. return PyBool_FromLong(result);
  11625. }
  11626. PyDoc_STRVAR(endswith__doc__,
  11627. "S.endswith(suffix[, start[, end]]) -> bool\n\
  11628. \n\
  11629. Return True if S ends with the specified suffix, False otherwise.\n\
  11630. With optional start, test S beginning at that position.\n\
  11631. With optional end, stop comparing S at that position.\n\
  11632. suffix can also be a tuple of strings to try.");
  11633. static PyObject *
  11634. unicode_endswith(PyObject *self,
  11635. PyObject *args)
  11636. {
  11637. PyObject *subobj;
  11638. PyObject *substring;
  11639. Py_ssize_t start = 0;
  11640. Py_ssize_t end = PY_SSIZE_T_MAX;
  11641. int result;
  11642. if (!asciilib_parse_args_finds("endswith", args, &subobj, &start, &end))
  11643. return NULL;
  11644. if (PyTuple_Check(subobj)) {
  11645. Py_ssize_t i;
  11646. for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
  11647. substring = PyTuple_GET_ITEM(subobj, i);
  11648. if (!PyUnicode_Check(substring)) {
  11649. PyErr_Format(PyExc_TypeError,
  11650. "tuple for endswith must only contain str, "
  11651. "not %.100s",
  11652. Py_TYPE(substring)->tp_name);
  11653. return NULL;
  11654. }
  11655. result = tailmatch(self, substring, start, end, +1);
  11656. if (result == -1)
  11657. return NULL;
  11658. if (result) {
  11659. Py_RETURN_TRUE;
  11660. }
  11661. }
  11662. Py_RETURN_FALSE;
  11663. }
  11664. if (!PyUnicode_Check(subobj)) {
  11665. PyErr_Format(PyExc_TypeError,
  11666. "endswith first arg must be str or "
  11667. "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
  11668. return NULL;
  11669. }
  11670. result = tailmatch(self, subobj, start, end, +1);
  11671. if (result == -1)
  11672. return NULL;
  11673. return PyBool_FromLong(result);
  11674. }
  11675. static inline void
  11676. _PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
  11677. {
  11678. writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
  11679. writer->data = PyUnicode_DATA(writer->buffer);
  11680. if (!writer->readonly) {
  11681. writer->kind = PyUnicode_KIND(writer->buffer);
  11682. writer->size = PyUnicode_GET_LENGTH(writer->buffer);
  11683. }
  11684. else {
  11685. /* use a value smaller than PyUnicode_1BYTE_KIND() so
  11686. _PyUnicodeWriter_PrepareKind() will copy the buffer. */
  11687. writer->kind = 0;
  11688. assert(writer->kind <= PyUnicode_1BYTE_KIND);
  11689. /* Copy-on-write mode: set buffer size to 0 so
  11690. * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
  11691. * next write. */
  11692. writer->size = 0;
  11693. }
  11694. }
  11695. void
  11696. _PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
  11697. {
  11698. memset(writer, 0, sizeof(*writer));
  11699. /* ASCII is the bare minimum */
  11700. writer->min_char = 127;
  11701. /* use a value smaller than PyUnicode_1BYTE_KIND() so
  11702. _PyUnicodeWriter_PrepareKind() will copy the buffer. */
  11703. writer->kind = 0;
  11704. assert(writer->kind <= PyUnicode_1BYTE_KIND);
  11705. }
  11706. // Initialize _PyUnicodeWriter with initial buffer
  11707. static inline void
  11708. _PyUnicodeWriter_InitWithBuffer(_PyUnicodeWriter *writer, PyObject *buffer)
  11709. {
  11710. memset(writer, 0, sizeof(*writer));
  11711. writer->buffer = buffer;
  11712. _PyUnicodeWriter_Update(writer);
  11713. writer->min_length = writer->size;
  11714. }
  11715. int
  11716. _PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
  11717. Py_ssize_t length, Py_UCS4 maxchar)
  11718. {
  11719. Py_ssize_t newlen;
  11720. PyObject *newbuffer;
  11721. assert(maxchar <= MAX_UNICODE);
  11722. /* ensure that the _PyUnicodeWriter_Prepare macro was used */
  11723. assert((maxchar > writer->maxchar && length >= 0)
  11724. || length > 0);
  11725. if (length > PY_SSIZE_T_MAX - writer->pos) {
  11726. PyErr_NoMemory();
  11727. return -1;
  11728. }
  11729. newlen = writer->pos + length;
  11730. maxchar = Py_MAX(maxchar, writer->min_char);
  11731. if (writer->buffer == NULL) {
  11732. assert(!writer->readonly);
  11733. if (writer->overallocate
  11734. && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
  11735. /* overallocate to limit the number of realloc() */
  11736. newlen += newlen / OVERALLOCATE_FACTOR;
  11737. }
  11738. if (newlen < writer->min_length)
  11739. newlen = writer->min_length;
  11740. writer->buffer = PyUnicode_New(newlen, maxchar);
  11741. if (writer->buffer == NULL)
  11742. return -1;
  11743. }
  11744. else if (newlen > writer->size) {
  11745. if (writer->overallocate
  11746. && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
  11747. /* overallocate to limit the number of realloc() */
  11748. newlen += newlen / OVERALLOCATE_FACTOR;
  11749. }
  11750. if (newlen < writer->min_length)
  11751. newlen = writer->min_length;
  11752. if (maxchar > writer->maxchar || writer->readonly) {
  11753. /* resize + widen */
  11754. maxchar = Py_MAX(maxchar, writer->maxchar);
  11755. newbuffer = PyUnicode_New(newlen, maxchar);
  11756. if (newbuffer == NULL)
  11757. return -1;
  11758. _PyUnicode_FastCopyCharacters(newbuffer, 0,
  11759. writer->buffer, 0, writer->pos);
  11760. Py_DECREF(writer->buffer);
  11761. writer->readonly = 0;
  11762. }
  11763. else {
  11764. newbuffer = resize_compact(writer->buffer, newlen);
  11765. if (newbuffer == NULL)
  11766. return -1;
  11767. }
  11768. writer->buffer = newbuffer;
  11769. }
  11770. else if (maxchar > writer->maxchar) {
  11771. assert(!writer->readonly);
  11772. newbuffer = PyUnicode_New(writer->size, maxchar);
  11773. if (newbuffer == NULL)
  11774. return -1;
  11775. _PyUnicode_FastCopyCharacters(newbuffer, 0,
  11776. writer->buffer, 0, writer->pos);
  11777. Py_SETREF(writer->buffer, newbuffer);
  11778. }
  11779. _PyUnicodeWriter_Update(writer);
  11780. return 0;
  11781. #undef OVERALLOCATE_FACTOR
  11782. }
  11783. int
  11784. _PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
  11785. int kind)
  11786. {
  11787. Py_UCS4 maxchar;
  11788. /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
  11789. assert(writer->kind < kind);
  11790. switch (kind)
  11791. {
  11792. case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
  11793. case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
  11794. case PyUnicode_4BYTE_KIND: maxchar = MAX_UNICODE; break;
  11795. default:
  11796. Py_UNREACHABLE();
  11797. }
  11798. return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
  11799. }
  11800. static inline int
  11801. _PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
  11802. {
  11803. assert(ch <= MAX_UNICODE);
  11804. if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
  11805. return -1;
  11806. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
  11807. writer->pos++;
  11808. return 0;
  11809. }
  11810. int
  11811. _PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
  11812. {
  11813. return _PyUnicodeWriter_WriteCharInline(writer, ch);
  11814. }
  11815. int
  11816. _PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
  11817. {
  11818. Py_UCS4 maxchar;
  11819. Py_ssize_t len;
  11820. len = PyUnicode_GET_LENGTH(str);
  11821. if (len == 0)
  11822. return 0;
  11823. maxchar = PyUnicode_MAX_CHAR_VALUE(str);
  11824. if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
  11825. if (writer->buffer == NULL && !writer->overallocate) {
  11826. assert(_PyUnicode_CheckConsistency(str, 1));
  11827. writer->readonly = 1;
  11828. writer->buffer = Py_NewRef(str);
  11829. _PyUnicodeWriter_Update(writer);
  11830. writer->pos += len;
  11831. return 0;
  11832. }
  11833. if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
  11834. return -1;
  11835. }
  11836. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  11837. str, 0, len);
  11838. writer->pos += len;
  11839. return 0;
  11840. }
  11841. int
  11842. _PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
  11843. Py_ssize_t start, Py_ssize_t end)
  11844. {
  11845. Py_UCS4 maxchar;
  11846. Py_ssize_t len;
  11847. assert(0 <= start);
  11848. assert(end <= PyUnicode_GET_LENGTH(str));
  11849. assert(start <= end);
  11850. if (end == 0)
  11851. return 0;
  11852. if (start == 0 && end == PyUnicode_GET_LENGTH(str))
  11853. return _PyUnicodeWriter_WriteStr(writer, str);
  11854. if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
  11855. maxchar = _PyUnicode_FindMaxChar(str, start, end);
  11856. else
  11857. maxchar = writer->maxchar;
  11858. len = end - start;
  11859. if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
  11860. return -1;
  11861. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  11862. str, start, len);
  11863. writer->pos += len;
  11864. return 0;
  11865. }
  11866. int
  11867. _PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
  11868. const char *ascii, Py_ssize_t len)
  11869. {
  11870. if (len == -1)
  11871. len = strlen(ascii);
  11872. assert(ucs1lib_find_max_char((const Py_UCS1*)ascii, (const Py_UCS1*)ascii + len) < 128);
  11873. if (writer->buffer == NULL && !writer->overallocate) {
  11874. PyObject *str;
  11875. str = _PyUnicode_FromASCII(ascii, len);
  11876. if (str == NULL)
  11877. return -1;
  11878. writer->readonly = 1;
  11879. writer->buffer = str;
  11880. _PyUnicodeWriter_Update(writer);
  11881. writer->pos += len;
  11882. return 0;
  11883. }
  11884. if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
  11885. return -1;
  11886. switch (writer->kind)
  11887. {
  11888. case PyUnicode_1BYTE_KIND:
  11889. {
  11890. const Py_UCS1 *str = (const Py_UCS1 *)ascii;
  11891. Py_UCS1 *data = writer->data;
  11892. memcpy(data + writer->pos, str, len);
  11893. break;
  11894. }
  11895. case PyUnicode_2BYTE_KIND:
  11896. {
  11897. _PyUnicode_CONVERT_BYTES(
  11898. Py_UCS1, Py_UCS2,
  11899. ascii, ascii + len,
  11900. (Py_UCS2 *)writer->data + writer->pos);
  11901. break;
  11902. }
  11903. case PyUnicode_4BYTE_KIND:
  11904. {
  11905. _PyUnicode_CONVERT_BYTES(
  11906. Py_UCS1, Py_UCS4,
  11907. ascii, ascii + len,
  11908. (Py_UCS4 *)writer->data + writer->pos);
  11909. break;
  11910. }
  11911. default:
  11912. Py_UNREACHABLE();
  11913. }
  11914. writer->pos += len;
  11915. return 0;
  11916. }
  11917. int
  11918. _PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
  11919. const char *str, Py_ssize_t len)
  11920. {
  11921. Py_UCS4 maxchar;
  11922. maxchar = ucs1lib_find_max_char((const Py_UCS1*)str, (const Py_UCS1*)str + len);
  11923. if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
  11924. return -1;
  11925. unicode_write_cstr(writer->buffer, writer->pos, str, len);
  11926. writer->pos += len;
  11927. return 0;
  11928. }
  11929. PyObject *
  11930. _PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
  11931. {
  11932. PyObject *str;
  11933. if (writer->pos == 0) {
  11934. Py_CLEAR(writer->buffer);
  11935. _Py_RETURN_UNICODE_EMPTY();
  11936. }
  11937. str = writer->buffer;
  11938. writer->buffer = NULL;
  11939. if (writer->readonly) {
  11940. assert(PyUnicode_GET_LENGTH(str) == writer->pos);
  11941. return str;
  11942. }
  11943. if (PyUnicode_GET_LENGTH(str) != writer->pos) {
  11944. PyObject *str2;
  11945. str2 = resize_compact(str, writer->pos);
  11946. if (str2 == NULL) {
  11947. Py_DECREF(str);
  11948. return NULL;
  11949. }
  11950. str = str2;
  11951. }
  11952. assert(_PyUnicode_CheckConsistency(str, 1));
  11953. return unicode_result(str);
  11954. }
  11955. void
  11956. _PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
  11957. {
  11958. Py_CLEAR(writer->buffer);
  11959. }
  11960. #include "stringlib/unicode_format.h"
  11961. PyDoc_STRVAR(format__doc__,
  11962. "S.format(*args, **kwargs) -> str\n\
  11963. \n\
  11964. Return a formatted version of S, using substitutions from args and kwargs.\n\
  11965. The substitutions are identified by braces ('{' and '}').");
  11966. PyDoc_STRVAR(format_map__doc__,
  11967. "S.format_map(mapping) -> str\n\
  11968. \n\
  11969. Return a formatted version of S, using substitutions from mapping.\n\
  11970. The substitutions are identified by braces ('{' and '}').");
  11971. /*[clinic input]
  11972. str.__format__ as unicode___format__
  11973. format_spec: unicode
  11974. /
  11975. Return a formatted version of the string as described by format_spec.
  11976. [clinic start generated code]*/
  11977. static PyObject *
  11978. unicode___format___impl(PyObject *self, PyObject *format_spec)
  11979. /*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
  11980. {
  11981. _PyUnicodeWriter writer;
  11982. int ret;
  11983. _PyUnicodeWriter_Init(&writer);
  11984. ret = _PyUnicode_FormatAdvancedWriter(&writer,
  11985. self, format_spec, 0,
  11986. PyUnicode_GET_LENGTH(format_spec));
  11987. if (ret == -1) {
  11988. _PyUnicodeWriter_Dealloc(&writer);
  11989. return NULL;
  11990. }
  11991. return _PyUnicodeWriter_Finish(&writer);
  11992. }
  11993. /*[clinic input]
  11994. str.__sizeof__ as unicode_sizeof
  11995. Return the size of the string in memory, in bytes.
  11996. [clinic start generated code]*/
  11997. static PyObject *
  11998. unicode_sizeof_impl(PyObject *self)
  11999. /*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
  12000. {
  12001. Py_ssize_t size;
  12002. /* If it's a compact object, account for base structure +
  12003. character data. */
  12004. if (PyUnicode_IS_COMPACT_ASCII(self)) {
  12005. size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
  12006. }
  12007. else if (PyUnicode_IS_COMPACT(self)) {
  12008. size = sizeof(PyCompactUnicodeObject) +
  12009. (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
  12010. }
  12011. else {
  12012. /* If it is a two-block object, account for base object, and
  12013. for character block if present. */
  12014. size = sizeof(PyUnicodeObject);
  12015. if (_PyUnicode_DATA_ANY(self))
  12016. size += (PyUnicode_GET_LENGTH(self) + 1) *
  12017. PyUnicode_KIND(self);
  12018. }
  12019. if (_PyUnicode_HAS_UTF8_MEMORY(self))
  12020. size += PyUnicode_UTF8_LENGTH(self) + 1;
  12021. return PyLong_FromSsize_t(size);
  12022. }
  12023. static PyObject *
  12024. unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
  12025. {
  12026. PyObject *copy = _PyUnicode_Copy(v);
  12027. if (!copy)
  12028. return NULL;
  12029. return Py_BuildValue("(N)", copy);
  12030. }
  12031. static PyMethodDef unicode_methods[] = {
  12032. UNICODE_ENCODE_METHODDEF
  12033. UNICODE_REPLACE_METHODDEF
  12034. UNICODE_SPLIT_METHODDEF
  12035. UNICODE_RSPLIT_METHODDEF
  12036. UNICODE_JOIN_METHODDEF
  12037. UNICODE_CAPITALIZE_METHODDEF
  12038. UNICODE_CASEFOLD_METHODDEF
  12039. UNICODE_TITLE_METHODDEF
  12040. UNICODE_CENTER_METHODDEF
  12041. {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
  12042. UNICODE_EXPANDTABS_METHODDEF
  12043. {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
  12044. UNICODE_PARTITION_METHODDEF
  12045. {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
  12046. UNICODE_LJUST_METHODDEF
  12047. UNICODE_LOWER_METHODDEF
  12048. UNICODE_LSTRIP_METHODDEF
  12049. {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
  12050. {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
  12051. UNICODE_RJUST_METHODDEF
  12052. UNICODE_RSTRIP_METHODDEF
  12053. UNICODE_RPARTITION_METHODDEF
  12054. UNICODE_SPLITLINES_METHODDEF
  12055. UNICODE_STRIP_METHODDEF
  12056. UNICODE_SWAPCASE_METHODDEF
  12057. UNICODE_TRANSLATE_METHODDEF
  12058. UNICODE_UPPER_METHODDEF
  12059. {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
  12060. {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
  12061. UNICODE_REMOVEPREFIX_METHODDEF
  12062. UNICODE_REMOVESUFFIX_METHODDEF
  12063. UNICODE_ISASCII_METHODDEF
  12064. UNICODE_ISLOWER_METHODDEF
  12065. UNICODE_ISUPPER_METHODDEF
  12066. UNICODE_ISTITLE_METHODDEF
  12067. UNICODE_ISSPACE_METHODDEF
  12068. UNICODE_ISDECIMAL_METHODDEF
  12069. UNICODE_ISDIGIT_METHODDEF
  12070. UNICODE_ISNUMERIC_METHODDEF
  12071. UNICODE_ISALPHA_METHODDEF
  12072. UNICODE_ISALNUM_METHODDEF
  12073. UNICODE_ISIDENTIFIER_METHODDEF
  12074. UNICODE_ISPRINTABLE_METHODDEF
  12075. UNICODE_ZFILL_METHODDEF
  12076. {"format", _PyCFunction_CAST(do_string_format), METH_VARARGS | METH_KEYWORDS, format__doc__},
  12077. {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
  12078. UNICODE___FORMAT___METHODDEF
  12079. UNICODE_MAKETRANS_METHODDEF
  12080. UNICODE_SIZEOF_METHODDEF
  12081. {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
  12082. {NULL, NULL}
  12083. };
  12084. static PyObject *
  12085. unicode_mod(PyObject *v, PyObject *w)
  12086. {
  12087. if (!PyUnicode_Check(v))
  12088. Py_RETURN_NOTIMPLEMENTED;
  12089. return PyUnicode_Format(v, w);
  12090. }
  12091. static PyNumberMethods unicode_as_number = {
  12092. 0, /*nb_add*/
  12093. 0, /*nb_subtract*/
  12094. 0, /*nb_multiply*/
  12095. unicode_mod, /*nb_remainder*/
  12096. };
  12097. static PySequenceMethods unicode_as_sequence = {
  12098. (lenfunc) unicode_length, /* sq_length */
  12099. PyUnicode_Concat, /* sq_concat */
  12100. (ssizeargfunc) unicode_repeat, /* sq_repeat */
  12101. (ssizeargfunc) unicode_getitem, /* sq_item */
  12102. 0, /* sq_slice */
  12103. 0, /* sq_ass_item */
  12104. 0, /* sq_ass_slice */
  12105. PyUnicode_Contains, /* sq_contains */
  12106. };
  12107. static PyObject*
  12108. unicode_subscript(PyObject* self, PyObject* item)
  12109. {
  12110. if (_PyIndex_Check(item)) {
  12111. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  12112. if (i == -1 && PyErr_Occurred())
  12113. return NULL;
  12114. if (i < 0)
  12115. i += PyUnicode_GET_LENGTH(self);
  12116. return unicode_getitem(self, i);
  12117. } else if (PySlice_Check(item)) {
  12118. Py_ssize_t start, stop, step, slicelength, i;
  12119. size_t cur;
  12120. PyObject *result;
  12121. const void *src_data;
  12122. void *dest_data;
  12123. int src_kind, dest_kind;
  12124. Py_UCS4 ch, max_char, kind_limit;
  12125. if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
  12126. return NULL;
  12127. }
  12128. slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
  12129. &start, &stop, step);
  12130. if (slicelength <= 0) {
  12131. _Py_RETURN_UNICODE_EMPTY();
  12132. } else if (start == 0 && step == 1 &&
  12133. slicelength == PyUnicode_GET_LENGTH(self)) {
  12134. return unicode_result_unchanged(self);
  12135. } else if (step == 1) {
  12136. return PyUnicode_Substring(self,
  12137. start, start + slicelength);
  12138. }
  12139. /* General case */
  12140. src_kind = PyUnicode_KIND(self);
  12141. src_data = PyUnicode_DATA(self);
  12142. if (!PyUnicode_IS_ASCII(self)) {
  12143. kind_limit = kind_maxchar_limit(src_kind);
  12144. max_char = 0;
  12145. for (cur = start, i = 0; i < slicelength; cur += step, i++) {
  12146. ch = PyUnicode_READ(src_kind, src_data, cur);
  12147. if (ch > max_char) {
  12148. max_char = ch;
  12149. if (max_char >= kind_limit)
  12150. break;
  12151. }
  12152. }
  12153. }
  12154. else
  12155. max_char = 127;
  12156. result = PyUnicode_New(slicelength, max_char);
  12157. if (result == NULL)
  12158. return NULL;
  12159. dest_kind = PyUnicode_KIND(result);
  12160. dest_data = PyUnicode_DATA(result);
  12161. for (cur = start, i = 0; i < slicelength; cur += step, i++) {
  12162. Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
  12163. PyUnicode_WRITE(dest_kind, dest_data, i, ch);
  12164. }
  12165. assert(_PyUnicode_CheckConsistency(result, 1));
  12166. return result;
  12167. } else {
  12168. PyErr_Format(PyExc_TypeError, "string indices must be integers, not '%.200s'",
  12169. Py_TYPE(item)->tp_name);
  12170. return NULL;
  12171. }
  12172. }
  12173. static PyMappingMethods unicode_as_mapping = {
  12174. (lenfunc)unicode_length, /* mp_length */
  12175. (binaryfunc)unicode_subscript, /* mp_subscript */
  12176. (objobjargproc)0, /* mp_ass_subscript */
  12177. };
  12178. /* Helpers for PyUnicode_Format() */
  12179. struct unicode_formatter_t {
  12180. PyObject *args;
  12181. int args_owned;
  12182. Py_ssize_t arglen, argidx;
  12183. PyObject *dict;
  12184. int fmtkind;
  12185. Py_ssize_t fmtcnt, fmtpos;
  12186. const void *fmtdata;
  12187. PyObject *fmtstr;
  12188. _PyUnicodeWriter writer;
  12189. };
  12190. struct unicode_format_arg_t {
  12191. Py_UCS4 ch;
  12192. int flags;
  12193. Py_ssize_t width;
  12194. int prec;
  12195. int sign;
  12196. };
  12197. static PyObject *
  12198. unicode_format_getnextarg(struct unicode_formatter_t *ctx)
  12199. {
  12200. Py_ssize_t argidx = ctx->argidx;
  12201. if (argidx < ctx->arglen) {
  12202. ctx->argidx++;
  12203. if (ctx->arglen < 0)
  12204. return ctx->args;
  12205. else
  12206. return PyTuple_GetItem(ctx->args, argidx);
  12207. }
  12208. PyErr_SetString(PyExc_TypeError,
  12209. "not enough arguments for format string");
  12210. return NULL;
  12211. }
  12212. /* Returns a new reference to a PyUnicode object, or NULL on failure. */
  12213. /* Format a float into the writer if the writer is not NULL, or into *p_output
  12214. otherwise.
  12215. Return 0 on success, raise an exception and return -1 on error. */
  12216. static int
  12217. formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
  12218. PyObject **p_output,
  12219. _PyUnicodeWriter *writer)
  12220. {
  12221. char *p;
  12222. double x;
  12223. Py_ssize_t len;
  12224. int prec;
  12225. int dtoa_flags = 0;
  12226. x = PyFloat_AsDouble(v);
  12227. if (x == -1.0 && PyErr_Occurred())
  12228. return -1;
  12229. prec = arg->prec;
  12230. if (prec < 0)
  12231. prec = 6;
  12232. if (arg->flags & F_ALT)
  12233. dtoa_flags |= Py_DTSF_ALT;
  12234. p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
  12235. if (p == NULL)
  12236. return -1;
  12237. len = strlen(p);
  12238. if (writer) {
  12239. if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
  12240. PyMem_Free(p);
  12241. return -1;
  12242. }
  12243. }
  12244. else
  12245. *p_output = _PyUnicode_FromASCII(p, len);
  12246. PyMem_Free(p);
  12247. return 0;
  12248. }
  12249. /* formatlong() emulates the format codes d, u, o, x and X, and
  12250. * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
  12251. * Python's regular ints.
  12252. * Return value: a new PyUnicodeObject*, or NULL if error.
  12253. * The output string is of the form
  12254. * "-"? ("0x" | "0X")? digit+
  12255. * "0x"/"0X" are present only for x and X conversions, with F_ALT
  12256. * set in flags. The case of hex digits will be correct,
  12257. * There will be at least prec digits, zero-filled on the left if
  12258. * necessary to get that many.
  12259. * val object to be converted
  12260. * flags bitmask of format flags; only F_ALT is looked at
  12261. * prec minimum number of digits; 0-fill on left if needed
  12262. * type a character in [duoxX]; u acts the same as d
  12263. *
  12264. * CAUTION: o, x and X conversions on regular ints can never
  12265. * produce a '-' sign, but can for Python's unbounded ints.
  12266. */
  12267. PyObject *
  12268. _PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
  12269. {
  12270. PyObject *result = NULL;
  12271. char *buf;
  12272. Py_ssize_t i;
  12273. int sign; /* 1 if '-', else 0 */
  12274. int len; /* number of characters */
  12275. Py_ssize_t llen;
  12276. int numdigits; /* len == numnondigits + numdigits */
  12277. int numnondigits = 0;
  12278. /* Avoid exceeding SSIZE_T_MAX */
  12279. if (prec > INT_MAX-3) {
  12280. PyErr_SetString(PyExc_OverflowError,
  12281. "precision too large");
  12282. return NULL;
  12283. }
  12284. assert(PyLong_Check(val));
  12285. switch (type) {
  12286. default:
  12287. Py_UNREACHABLE();
  12288. case 'd':
  12289. case 'i':
  12290. case 'u':
  12291. /* int and int subclasses should print numerically when a numeric */
  12292. /* format code is used (see issue18780) */
  12293. result = PyNumber_ToBase(val, 10);
  12294. break;
  12295. case 'o':
  12296. numnondigits = 2;
  12297. result = PyNumber_ToBase(val, 8);
  12298. break;
  12299. case 'x':
  12300. case 'X':
  12301. numnondigits = 2;
  12302. result = PyNumber_ToBase(val, 16);
  12303. break;
  12304. }
  12305. if (!result)
  12306. return NULL;
  12307. assert(unicode_modifiable(result));
  12308. assert(PyUnicode_IS_ASCII(result));
  12309. /* To modify the string in-place, there can only be one reference. */
  12310. if (Py_REFCNT(result) != 1) {
  12311. Py_DECREF(result);
  12312. PyErr_BadInternalCall();
  12313. return NULL;
  12314. }
  12315. buf = PyUnicode_DATA(result);
  12316. llen = PyUnicode_GET_LENGTH(result);
  12317. if (llen > INT_MAX) {
  12318. Py_DECREF(result);
  12319. PyErr_SetString(PyExc_ValueError,
  12320. "string too large in _PyUnicode_FormatLong");
  12321. return NULL;
  12322. }
  12323. len = (int)llen;
  12324. sign = buf[0] == '-';
  12325. numnondigits += sign;
  12326. numdigits = len - numnondigits;
  12327. assert(numdigits > 0);
  12328. /* Get rid of base marker unless F_ALT */
  12329. if (((alt) == 0 &&
  12330. (type == 'o' || type == 'x' || type == 'X'))) {
  12331. assert(buf[sign] == '0');
  12332. assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
  12333. buf[sign+1] == 'o');
  12334. numnondigits -= 2;
  12335. buf += 2;
  12336. len -= 2;
  12337. if (sign)
  12338. buf[0] = '-';
  12339. assert(len == numnondigits + numdigits);
  12340. assert(numdigits > 0);
  12341. }
  12342. /* Fill with leading zeroes to meet minimum width. */
  12343. if (prec > numdigits) {
  12344. PyObject *r1 = PyBytes_FromStringAndSize(NULL,
  12345. numnondigits + prec);
  12346. char *b1;
  12347. if (!r1) {
  12348. Py_DECREF(result);
  12349. return NULL;
  12350. }
  12351. b1 = PyBytes_AS_STRING(r1);
  12352. for (i = 0; i < numnondigits; ++i)
  12353. *b1++ = *buf++;
  12354. for (i = 0; i < prec - numdigits; i++)
  12355. *b1++ = '0';
  12356. for (i = 0; i < numdigits; i++)
  12357. *b1++ = *buf++;
  12358. *b1 = '\0';
  12359. Py_SETREF(result, r1);
  12360. buf = PyBytes_AS_STRING(result);
  12361. len = numnondigits + prec;
  12362. }
  12363. /* Fix up case for hex conversions. */
  12364. if (type == 'X') {
  12365. /* Need to convert all lower case letters to upper case.
  12366. and need to convert 0x to 0X (and -0x to -0X). */
  12367. for (i = 0; i < len; i++)
  12368. if (buf[i] >= 'a' && buf[i] <= 'x')
  12369. buf[i] -= 'a'-'A';
  12370. }
  12371. if (!PyUnicode_Check(result)
  12372. || buf != PyUnicode_DATA(result)) {
  12373. PyObject *unicode;
  12374. unicode = _PyUnicode_FromASCII(buf, len);
  12375. Py_SETREF(result, unicode);
  12376. }
  12377. else if (len != PyUnicode_GET_LENGTH(result)) {
  12378. if (PyUnicode_Resize(&result, len) < 0)
  12379. Py_CLEAR(result);
  12380. }
  12381. return result;
  12382. }
  12383. /* Format an integer or a float as an integer.
  12384. * Return 1 if the number has been formatted into the writer,
  12385. * 0 if the number has been formatted into *p_output
  12386. * -1 and raise an exception on error */
  12387. static int
  12388. mainformatlong(PyObject *v,
  12389. struct unicode_format_arg_t *arg,
  12390. PyObject **p_output,
  12391. _PyUnicodeWriter *writer)
  12392. {
  12393. PyObject *iobj, *res;
  12394. char type = (char)arg->ch;
  12395. if (!PyNumber_Check(v))
  12396. goto wrongtype;
  12397. /* make sure number is a type of integer for o, x, and X */
  12398. if (!PyLong_Check(v)) {
  12399. if (type == 'o' || type == 'x' || type == 'X') {
  12400. iobj = _PyNumber_Index(v);
  12401. }
  12402. else {
  12403. iobj = PyNumber_Long(v);
  12404. }
  12405. if (iobj == NULL ) {
  12406. if (PyErr_ExceptionMatches(PyExc_TypeError))
  12407. goto wrongtype;
  12408. return -1;
  12409. }
  12410. assert(PyLong_Check(iobj));
  12411. }
  12412. else {
  12413. iobj = Py_NewRef(v);
  12414. }
  12415. if (PyLong_CheckExact(v)
  12416. && arg->width == -1 && arg->prec == -1
  12417. && !(arg->flags & (F_SIGN | F_BLANK))
  12418. && type != 'X')
  12419. {
  12420. /* Fast path */
  12421. int alternate = arg->flags & F_ALT;
  12422. int base;
  12423. switch(type)
  12424. {
  12425. default:
  12426. Py_UNREACHABLE();
  12427. case 'd':
  12428. case 'i':
  12429. case 'u':
  12430. base = 10;
  12431. break;
  12432. case 'o':
  12433. base = 8;
  12434. break;
  12435. case 'x':
  12436. case 'X':
  12437. base = 16;
  12438. break;
  12439. }
  12440. if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
  12441. Py_DECREF(iobj);
  12442. return -1;
  12443. }
  12444. Py_DECREF(iobj);
  12445. return 1;
  12446. }
  12447. res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
  12448. Py_DECREF(iobj);
  12449. if (res == NULL)
  12450. return -1;
  12451. *p_output = res;
  12452. return 0;
  12453. wrongtype:
  12454. switch(type)
  12455. {
  12456. case 'o':
  12457. case 'x':
  12458. case 'X':
  12459. PyErr_Format(PyExc_TypeError,
  12460. "%%%c format: an integer is required, "
  12461. "not %.200s",
  12462. type, Py_TYPE(v)->tp_name);
  12463. break;
  12464. default:
  12465. PyErr_Format(PyExc_TypeError,
  12466. "%%%c format: a real number is required, "
  12467. "not %.200s",
  12468. type, Py_TYPE(v)->tp_name);
  12469. break;
  12470. }
  12471. return -1;
  12472. }
  12473. static Py_UCS4
  12474. formatchar(PyObject *v)
  12475. {
  12476. /* presume that the buffer is at least 3 characters long */
  12477. if (PyUnicode_Check(v)) {
  12478. if (PyUnicode_GET_LENGTH(v) == 1) {
  12479. return PyUnicode_READ_CHAR(v, 0);
  12480. }
  12481. goto onError;
  12482. }
  12483. else {
  12484. int overflow;
  12485. long x = PyLong_AsLongAndOverflow(v, &overflow);
  12486. if (x == -1 && PyErr_Occurred()) {
  12487. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  12488. goto onError;
  12489. }
  12490. return (Py_UCS4) -1;
  12491. }
  12492. if (x < 0 || x > MAX_UNICODE) {
  12493. /* this includes an overflow in converting to C long */
  12494. PyErr_SetString(PyExc_OverflowError,
  12495. "%c arg not in range(0x110000)");
  12496. return (Py_UCS4) -1;
  12497. }
  12498. return (Py_UCS4) x;
  12499. }
  12500. onError:
  12501. PyErr_SetString(PyExc_TypeError,
  12502. "%c requires int or char");
  12503. return (Py_UCS4) -1;
  12504. }
  12505. /* Parse options of an argument: flags, width, precision.
  12506. Handle also "%(name)" syntax.
  12507. Return 0 if the argument has been formatted into arg->str.
  12508. Return 1 if the argument has been written into ctx->writer,
  12509. Raise an exception and return -1 on error. */
  12510. static int
  12511. unicode_format_arg_parse(struct unicode_formatter_t *ctx,
  12512. struct unicode_format_arg_t *arg)
  12513. {
  12514. #define FORMAT_READ(ctx) \
  12515. PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
  12516. PyObject *v;
  12517. if (arg->ch == '(') {
  12518. /* Get argument value from a dictionary. Example: "%(name)s". */
  12519. Py_ssize_t keystart;
  12520. Py_ssize_t keylen;
  12521. PyObject *key;
  12522. int pcount = 1;
  12523. if (ctx->dict == NULL) {
  12524. PyErr_SetString(PyExc_TypeError,
  12525. "format requires a mapping");
  12526. return -1;
  12527. }
  12528. ++ctx->fmtpos;
  12529. --ctx->fmtcnt;
  12530. keystart = ctx->fmtpos;
  12531. /* Skip over balanced parentheses */
  12532. while (pcount > 0 && --ctx->fmtcnt >= 0) {
  12533. arg->ch = FORMAT_READ(ctx);
  12534. if (arg->ch == ')')
  12535. --pcount;
  12536. else if (arg->ch == '(')
  12537. ++pcount;
  12538. ctx->fmtpos++;
  12539. }
  12540. keylen = ctx->fmtpos - keystart - 1;
  12541. if (ctx->fmtcnt < 0 || pcount > 0) {
  12542. PyErr_SetString(PyExc_ValueError,
  12543. "incomplete format key");
  12544. return -1;
  12545. }
  12546. key = PyUnicode_Substring(ctx->fmtstr,
  12547. keystart, keystart + keylen);
  12548. if (key == NULL)
  12549. return -1;
  12550. if (ctx->args_owned) {
  12551. ctx->args_owned = 0;
  12552. Py_DECREF(ctx->args);
  12553. }
  12554. ctx->args = PyObject_GetItem(ctx->dict, key);
  12555. Py_DECREF(key);
  12556. if (ctx->args == NULL)
  12557. return -1;
  12558. ctx->args_owned = 1;
  12559. ctx->arglen = -1;
  12560. ctx->argidx = -2;
  12561. }
  12562. /* Parse flags. Example: "%+i" => flags=F_SIGN. */
  12563. while (--ctx->fmtcnt >= 0) {
  12564. arg->ch = FORMAT_READ(ctx);
  12565. ctx->fmtpos++;
  12566. switch (arg->ch) {
  12567. case '-': arg->flags |= F_LJUST; continue;
  12568. case '+': arg->flags |= F_SIGN; continue;
  12569. case ' ': arg->flags |= F_BLANK; continue;
  12570. case '#': arg->flags |= F_ALT; continue;
  12571. case '0': arg->flags |= F_ZERO; continue;
  12572. }
  12573. break;
  12574. }
  12575. /* Parse width. Example: "%10s" => width=10 */
  12576. if (arg->ch == '*') {
  12577. v = unicode_format_getnextarg(ctx);
  12578. if (v == NULL)
  12579. return -1;
  12580. if (!PyLong_Check(v)) {
  12581. PyErr_SetString(PyExc_TypeError,
  12582. "* wants int");
  12583. return -1;
  12584. }
  12585. arg->width = PyLong_AsSsize_t(v);
  12586. if (arg->width == -1 && PyErr_Occurred())
  12587. return -1;
  12588. if (arg->width < 0) {
  12589. arg->flags |= F_LJUST;
  12590. arg->width = -arg->width;
  12591. }
  12592. if (--ctx->fmtcnt >= 0) {
  12593. arg->ch = FORMAT_READ(ctx);
  12594. ctx->fmtpos++;
  12595. }
  12596. }
  12597. else if (arg->ch >= '0' && arg->ch <= '9') {
  12598. arg->width = arg->ch - '0';
  12599. while (--ctx->fmtcnt >= 0) {
  12600. arg->ch = FORMAT_READ(ctx);
  12601. ctx->fmtpos++;
  12602. if (arg->ch < '0' || arg->ch > '9')
  12603. break;
  12604. /* Since arg->ch is unsigned, the RHS would end up as unsigned,
  12605. mixing signed and unsigned comparison. Since arg->ch is between
  12606. '0' and '9', casting to int is safe. */
  12607. if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
  12608. PyErr_SetString(PyExc_ValueError,
  12609. "width too big");
  12610. return -1;
  12611. }
  12612. arg->width = arg->width*10 + (arg->ch - '0');
  12613. }
  12614. }
  12615. /* Parse precision. Example: "%.3f" => prec=3 */
  12616. if (arg->ch == '.') {
  12617. arg->prec = 0;
  12618. if (--ctx->fmtcnt >= 0) {
  12619. arg->ch = FORMAT_READ(ctx);
  12620. ctx->fmtpos++;
  12621. }
  12622. if (arg->ch == '*') {
  12623. v = unicode_format_getnextarg(ctx);
  12624. if (v == NULL)
  12625. return -1;
  12626. if (!PyLong_Check(v)) {
  12627. PyErr_SetString(PyExc_TypeError,
  12628. "* wants int");
  12629. return -1;
  12630. }
  12631. arg->prec = _PyLong_AsInt(v);
  12632. if (arg->prec == -1 && PyErr_Occurred())
  12633. return -1;
  12634. if (arg->prec < 0)
  12635. arg->prec = 0;
  12636. if (--ctx->fmtcnt >= 0) {
  12637. arg->ch = FORMAT_READ(ctx);
  12638. ctx->fmtpos++;
  12639. }
  12640. }
  12641. else if (arg->ch >= '0' && arg->ch <= '9') {
  12642. arg->prec = arg->ch - '0';
  12643. while (--ctx->fmtcnt >= 0) {
  12644. arg->ch = FORMAT_READ(ctx);
  12645. ctx->fmtpos++;
  12646. if (arg->ch < '0' || arg->ch > '9')
  12647. break;
  12648. if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
  12649. PyErr_SetString(PyExc_ValueError,
  12650. "precision too big");
  12651. return -1;
  12652. }
  12653. arg->prec = arg->prec*10 + (arg->ch - '0');
  12654. }
  12655. }
  12656. }
  12657. /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
  12658. if (ctx->fmtcnt >= 0) {
  12659. if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
  12660. if (--ctx->fmtcnt >= 0) {
  12661. arg->ch = FORMAT_READ(ctx);
  12662. ctx->fmtpos++;
  12663. }
  12664. }
  12665. }
  12666. if (ctx->fmtcnt < 0) {
  12667. PyErr_SetString(PyExc_ValueError,
  12668. "incomplete format");
  12669. return -1;
  12670. }
  12671. return 0;
  12672. #undef FORMAT_READ
  12673. }
  12674. /* Format one argument. Supported conversion specifiers:
  12675. - "s", "r", "a": any type
  12676. - "i", "d", "u": int or float
  12677. - "o", "x", "X": int
  12678. - "e", "E", "f", "F", "g", "G": float
  12679. - "c": int or str (1 character)
  12680. When possible, the output is written directly into the Unicode writer
  12681. (ctx->writer). A string is created when padding is required.
  12682. Return 0 if the argument has been formatted into *p_str,
  12683. 1 if the argument has been written into ctx->writer,
  12684. -1 on error. */
  12685. static int
  12686. unicode_format_arg_format(struct unicode_formatter_t *ctx,
  12687. struct unicode_format_arg_t *arg,
  12688. PyObject **p_str)
  12689. {
  12690. PyObject *v;
  12691. _PyUnicodeWriter *writer = &ctx->writer;
  12692. if (ctx->fmtcnt == 0)
  12693. ctx->writer.overallocate = 0;
  12694. v = unicode_format_getnextarg(ctx);
  12695. if (v == NULL)
  12696. return -1;
  12697. switch (arg->ch) {
  12698. case 's':
  12699. case 'r':
  12700. case 'a':
  12701. if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
  12702. /* Fast path */
  12703. if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
  12704. return -1;
  12705. return 1;
  12706. }
  12707. if (PyUnicode_CheckExact(v) && arg->ch == 's') {
  12708. *p_str = Py_NewRef(v);
  12709. }
  12710. else {
  12711. if (arg->ch == 's')
  12712. *p_str = PyObject_Str(v);
  12713. else if (arg->ch == 'r')
  12714. *p_str = PyObject_Repr(v);
  12715. else
  12716. *p_str = PyObject_ASCII(v);
  12717. }
  12718. break;
  12719. case 'i':
  12720. case 'd':
  12721. case 'u':
  12722. case 'o':
  12723. case 'x':
  12724. case 'X':
  12725. {
  12726. int ret = mainformatlong(v, arg, p_str, writer);
  12727. if (ret != 0)
  12728. return ret;
  12729. arg->sign = 1;
  12730. break;
  12731. }
  12732. case 'e':
  12733. case 'E':
  12734. case 'f':
  12735. case 'F':
  12736. case 'g':
  12737. case 'G':
  12738. if (arg->width == -1 && arg->prec == -1
  12739. && !(arg->flags & (F_SIGN | F_BLANK)))
  12740. {
  12741. /* Fast path */
  12742. if (formatfloat(v, arg, NULL, writer) == -1)
  12743. return -1;
  12744. return 1;
  12745. }
  12746. arg->sign = 1;
  12747. if (formatfloat(v, arg, p_str, NULL) == -1)
  12748. return -1;
  12749. break;
  12750. case 'c':
  12751. {
  12752. Py_UCS4 ch = formatchar(v);
  12753. if (ch == (Py_UCS4) -1)
  12754. return -1;
  12755. if (arg->width == -1 && arg->prec == -1) {
  12756. /* Fast path */
  12757. if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
  12758. return -1;
  12759. return 1;
  12760. }
  12761. *p_str = PyUnicode_FromOrdinal(ch);
  12762. break;
  12763. }
  12764. default:
  12765. PyErr_Format(PyExc_ValueError,
  12766. "unsupported format character '%c' (0x%x) "
  12767. "at index %zd",
  12768. (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
  12769. (int)arg->ch,
  12770. ctx->fmtpos - 1);
  12771. return -1;
  12772. }
  12773. if (*p_str == NULL)
  12774. return -1;
  12775. assert (PyUnicode_Check(*p_str));
  12776. return 0;
  12777. }
  12778. static int
  12779. unicode_format_arg_output(struct unicode_formatter_t *ctx,
  12780. struct unicode_format_arg_t *arg,
  12781. PyObject *str)
  12782. {
  12783. Py_ssize_t len;
  12784. int kind;
  12785. const void *pbuf;
  12786. Py_ssize_t pindex;
  12787. Py_UCS4 signchar;
  12788. Py_ssize_t buflen;
  12789. Py_UCS4 maxchar;
  12790. Py_ssize_t sublen;
  12791. _PyUnicodeWriter *writer = &ctx->writer;
  12792. Py_UCS4 fill;
  12793. fill = ' ';
  12794. if (arg->sign && arg->flags & F_ZERO)
  12795. fill = '0';
  12796. len = PyUnicode_GET_LENGTH(str);
  12797. if ((arg->width == -1 || arg->width <= len)
  12798. && (arg->prec == -1 || arg->prec >= len)
  12799. && !(arg->flags & (F_SIGN | F_BLANK)))
  12800. {
  12801. /* Fast path */
  12802. if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
  12803. return -1;
  12804. return 0;
  12805. }
  12806. /* Truncate the string for "s", "r" and "a" formats
  12807. if the precision is set */
  12808. if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
  12809. if (arg->prec >= 0 && len > arg->prec)
  12810. len = arg->prec;
  12811. }
  12812. /* Adjust sign and width */
  12813. kind = PyUnicode_KIND(str);
  12814. pbuf = PyUnicode_DATA(str);
  12815. pindex = 0;
  12816. signchar = '\0';
  12817. if (arg->sign) {
  12818. Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
  12819. if (ch == '-' || ch == '+') {
  12820. signchar = ch;
  12821. len--;
  12822. pindex++;
  12823. }
  12824. else if (arg->flags & F_SIGN)
  12825. signchar = '+';
  12826. else if (arg->flags & F_BLANK)
  12827. signchar = ' ';
  12828. else
  12829. arg->sign = 0;
  12830. }
  12831. if (arg->width < len)
  12832. arg->width = len;
  12833. /* Prepare the writer */
  12834. maxchar = writer->maxchar;
  12835. if (!(arg->flags & F_LJUST)) {
  12836. if (arg->sign) {
  12837. if ((arg->width-1) > len)
  12838. maxchar = Py_MAX(maxchar, fill);
  12839. }
  12840. else {
  12841. if (arg->width > len)
  12842. maxchar = Py_MAX(maxchar, fill);
  12843. }
  12844. }
  12845. if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
  12846. Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
  12847. maxchar = Py_MAX(maxchar, strmaxchar);
  12848. }
  12849. buflen = arg->width;
  12850. if (arg->sign && len == arg->width)
  12851. buflen++;
  12852. if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
  12853. return -1;
  12854. /* Write the sign if needed */
  12855. if (arg->sign) {
  12856. if (fill != ' ') {
  12857. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
  12858. writer->pos += 1;
  12859. }
  12860. if (arg->width > len)
  12861. arg->width--;
  12862. }
  12863. /* Write the numeric prefix for "x", "X" and "o" formats
  12864. if the alternate form is used.
  12865. For example, write "0x" for the "%#x" format. */
  12866. if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
  12867. assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
  12868. assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
  12869. if (fill != ' ') {
  12870. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
  12871. PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
  12872. writer->pos += 2;
  12873. pindex += 2;
  12874. }
  12875. arg->width -= 2;
  12876. if (arg->width < 0)
  12877. arg->width = 0;
  12878. len -= 2;
  12879. }
  12880. /* Pad left with the fill character if needed */
  12881. if (arg->width > len && !(arg->flags & F_LJUST)) {
  12882. sublen = arg->width - len;
  12883. unicode_fill(writer->kind, writer->data, fill, writer->pos, sublen);
  12884. writer->pos += sublen;
  12885. arg->width = len;
  12886. }
  12887. /* If padding with spaces: write sign if needed and/or numeric prefix if
  12888. the alternate form is used */
  12889. if (fill == ' ') {
  12890. if (arg->sign) {
  12891. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
  12892. writer->pos += 1;
  12893. }
  12894. if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
  12895. assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
  12896. assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
  12897. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
  12898. PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
  12899. writer->pos += 2;
  12900. pindex += 2;
  12901. }
  12902. }
  12903. /* Write characters */
  12904. if (len) {
  12905. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  12906. str, pindex, len);
  12907. writer->pos += len;
  12908. }
  12909. /* Pad right with the fill character if needed */
  12910. if (arg->width > len) {
  12911. sublen = arg->width - len;
  12912. unicode_fill(writer->kind, writer->data, ' ', writer->pos, sublen);
  12913. writer->pos += sublen;
  12914. }
  12915. return 0;
  12916. }
  12917. /* Helper of PyUnicode_Format(): format one arg.
  12918. Return 0 on success, raise an exception and return -1 on error. */
  12919. static int
  12920. unicode_format_arg(struct unicode_formatter_t *ctx)
  12921. {
  12922. struct unicode_format_arg_t arg;
  12923. PyObject *str;
  12924. int ret;
  12925. arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
  12926. if (arg.ch == '%') {
  12927. ctx->fmtpos++;
  12928. ctx->fmtcnt--;
  12929. if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
  12930. return -1;
  12931. return 0;
  12932. }
  12933. arg.flags = 0;
  12934. arg.width = -1;
  12935. arg.prec = -1;
  12936. arg.sign = 0;
  12937. str = NULL;
  12938. ret = unicode_format_arg_parse(ctx, &arg);
  12939. if (ret == -1)
  12940. return -1;
  12941. ret = unicode_format_arg_format(ctx, &arg, &str);
  12942. if (ret == -1)
  12943. return -1;
  12944. if (ret != 1) {
  12945. ret = unicode_format_arg_output(ctx, &arg, str);
  12946. Py_DECREF(str);
  12947. if (ret == -1)
  12948. return -1;
  12949. }
  12950. if (ctx->dict && (ctx->argidx < ctx->arglen)) {
  12951. PyErr_SetString(PyExc_TypeError,
  12952. "not all arguments converted during string formatting");
  12953. return -1;
  12954. }
  12955. return 0;
  12956. }
  12957. PyObject *
  12958. PyUnicode_Format(PyObject *format, PyObject *args)
  12959. {
  12960. struct unicode_formatter_t ctx;
  12961. if (format == NULL || args == NULL) {
  12962. PyErr_BadInternalCall();
  12963. return NULL;
  12964. }
  12965. if (ensure_unicode(format) < 0)
  12966. return NULL;
  12967. ctx.fmtstr = format;
  12968. ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
  12969. ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
  12970. ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
  12971. ctx.fmtpos = 0;
  12972. _PyUnicodeWriter_Init(&ctx.writer);
  12973. ctx.writer.min_length = ctx.fmtcnt + 100;
  12974. ctx.writer.overallocate = 1;
  12975. if (PyTuple_Check(args)) {
  12976. ctx.arglen = PyTuple_Size(args);
  12977. ctx.argidx = 0;
  12978. }
  12979. else {
  12980. ctx.arglen = -1;
  12981. ctx.argidx = -2;
  12982. }
  12983. ctx.args_owned = 0;
  12984. if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
  12985. ctx.dict = args;
  12986. else
  12987. ctx.dict = NULL;
  12988. ctx.args = args;
  12989. while (--ctx.fmtcnt >= 0) {
  12990. if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
  12991. Py_ssize_t nonfmtpos;
  12992. nonfmtpos = ctx.fmtpos++;
  12993. while (ctx.fmtcnt >= 0 &&
  12994. PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
  12995. ctx.fmtpos++;
  12996. ctx.fmtcnt--;
  12997. }
  12998. if (ctx.fmtcnt < 0) {
  12999. ctx.fmtpos--;
  13000. ctx.writer.overallocate = 0;
  13001. }
  13002. if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
  13003. nonfmtpos, ctx.fmtpos) < 0)
  13004. goto onError;
  13005. }
  13006. else {
  13007. ctx.fmtpos++;
  13008. if (unicode_format_arg(&ctx) == -1)
  13009. goto onError;
  13010. }
  13011. }
  13012. if (ctx.argidx < ctx.arglen && !ctx.dict) {
  13013. PyErr_SetString(PyExc_TypeError,
  13014. "not all arguments converted during string formatting");
  13015. goto onError;
  13016. }
  13017. if (ctx.args_owned) {
  13018. Py_DECREF(ctx.args);
  13019. }
  13020. return _PyUnicodeWriter_Finish(&ctx.writer);
  13021. onError:
  13022. _PyUnicodeWriter_Dealloc(&ctx.writer);
  13023. if (ctx.args_owned) {
  13024. Py_DECREF(ctx.args);
  13025. }
  13026. return NULL;
  13027. }
  13028. static PyObject *
  13029. unicode_subtype_new(PyTypeObject *type, PyObject *unicode);
  13030. /*[clinic input]
  13031. @classmethod
  13032. str.__new__ as unicode_new
  13033. object as x: object = NULL
  13034. encoding: str = NULL
  13035. errors: str = NULL
  13036. [clinic start generated code]*/
  13037. static PyObject *
  13038. unicode_new_impl(PyTypeObject *type, PyObject *x, const char *encoding,
  13039. const char *errors)
  13040. /*[clinic end generated code: output=fc72d4878b0b57e9 input=e81255e5676d174e]*/
  13041. {
  13042. PyObject *unicode;
  13043. if (x == NULL) {
  13044. unicode = unicode_new_empty();
  13045. }
  13046. else if (encoding == NULL && errors == NULL) {
  13047. unicode = PyObject_Str(x);
  13048. }
  13049. else {
  13050. unicode = PyUnicode_FromEncodedObject(x, encoding, errors);
  13051. }
  13052. if (unicode != NULL && type != &PyUnicode_Type) {
  13053. Py_SETREF(unicode, unicode_subtype_new(type, unicode));
  13054. }
  13055. return unicode;
  13056. }
  13057. static PyObject *
  13058. unicode_subtype_new(PyTypeObject *type, PyObject *unicode)
  13059. {
  13060. PyObject *self;
  13061. Py_ssize_t length, char_size;
  13062. int share_utf8;
  13063. int kind;
  13064. void *data;
  13065. assert(PyType_IsSubtype(type, &PyUnicode_Type));
  13066. assert(_PyUnicode_CHECK(unicode));
  13067. self = type->tp_alloc(type, 0);
  13068. if (self == NULL) {
  13069. return NULL;
  13070. }
  13071. kind = PyUnicode_KIND(unicode);
  13072. length = PyUnicode_GET_LENGTH(unicode);
  13073. _PyUnicode_LENGTH(self) = length;
  13074. #ifdef Py_DEBUG
  13075. _PyUnicode_HASH(self) = -1;
  13076. #else
  13077. _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
  13078. #endif
  13079. _PyUnicode_STATE(self).interned = 0;
  13080. _PyUnicode_STATE(self).kind = kind;
  13081. _PyUnicode_STATE(self).compact = 0;
  13082. _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
  13083. _PyUnicode_STATE(self).statically_allocated = 0;
  13084. _PyUnicode_UTF8_LENGTH(self) = 0;
  13085. _PyUnicode_UTF8(self) = NULL;
  13086. _PyUnicode_DATA_ANY(self) = NULL;
  13087. share_utf8 = 0;
  13088. if (kind == PyUnicode_1BYTE_KIND) {
  13089. char_size = 1;
  13090. if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
  13091. share_utf8 = 1;
  13092. }
  13093. else if (kind == PyUnicode_2BYTE_KIND) {
  13094. char_size = 2;
  13095. }
  13096. else {
  13097. assert(kind == PyUnicode_4BYTE_KIND);
  13098. char_size = 4;
  13099. }
  13100. /* Ensure we won't overflow the length. */
  13101. if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
  13102. PyErr_NoMemory();
  13103. goto onError;
  13104. }
  13105. data = PyObject_Malloc((length + 1) * char_size);
  13106. if (data == NULL) {
  13107. PyErr_NoMemory();
  13108. goto onError;
  13109. }
  13110. _PyUnicode_DATA_ANY(self) = data;
  13111. if (share_utf8) {
  13112. _PyUnicode_UTF8_LENGTH(self) = length;
  13113. _PyUnicode_UTF8(self) = data;
  13114. }
  13115. memcpy(data, PyUnicode_DATA(unicode), kind * (length + 1));
  13116. assert(_PyUnicode_CheckConsistency(self, 1));
  13117. #ifdef Py_DEBUG
  13118. _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
  13119. #endif
  13120. return self;
  13121. onError:
  13122. Py_DECREF(self);
  13123. return NULL;
  13124. }
  13125. void
  13126. _PyUnicode_ExactDealloc(PyObject *op)
  13127. {
  13128. assert(PyUnicode_CheckExact(op));
  13129. unicode_dealloc(op);
  13130. }
  13131. PyDoc_STRVAR(unicode_doc,
  13132. "str(object='') -> str\n\
  13133. str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
  13134. \n\
  13135. Create a new string object from the given object. If encoding or\n\
  13136. errors is specified, then the object must expose a data buffer\n\
  13137. that will be decoded using the given encoding and error handler.\n\
  13138. Otherwise, returns the result of object.__str__() (if defined)\n\
  13139. or repr(object).\n\
  13140. encoding defaults to sys.getdefaultencoding().\n\
  13141. errors defaults to 'strict'.");
  13142. static PyObject *unicode_iter(PyObject *seq);
  13143. PyTypeObject PyUnicode_Type = {
  13144. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  13145. "str", /* tp_name */
  13146. sizeof(PyUnicodeObject), /* tp_basicsize */
  13147. 0, /* tp_itemsize */
  13148. /* Slots */
  13149. (destructor)unicode_dealloc, /* tp_dealloc */
  13150. 0, /* tp_vectorcall_offset */
  13151. 0, /* tp_getattr */
  13152. 0, /* tp_setattr */
  13153. 0, /* tp_as_async */
  13154. unicode_repr, /* tp_repr */
  13155. &unicode_as_number, /* tp_as_number */
  13156. &unicode_as_sequence, /* tp_as_sequence */
  13157. &unicode_as_mapping, /* tp_as_mapping */
  13158. (hashfunc) unicode_hash, /* tp_hash*/
  13159. 0, /* tp_call*/
  13160. (reprfunc) unicode_str, /* tp_str */
  13161. PyObject_GenericGetAttr, /* tp_getattro */
  13162. 0, /* tp_setattro */
  13163. 0, /* tp_as_buffer */
  13164. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  13165. Py_TPFLAGS_UNICODE_SUBCLASS |
  13166. _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
  13167. unicode_doc, /* tp_doc */
  13168. 0, /* tp_traverse */
  13169. 0, /* tp_clear */
  13170. PyUnicode_RichCompare, /* tp_richcompare */
  13171. 0, /* tp_weaklistoffset */
  13172. unicode_iter, /* tp_iter */
  13173. 0, /* tp_iternext */
  13174. unicode_methods, /* tp_methods */
  13175. 0, /* tp_members */
  13176. 0, /* tp_getset */
  13177. 0, /* tp_base */
  13178. 0, /* tp_dict */
  13179. 0, /* tp_descr_get */
  13180. 0, /* tp_descr_set */
  13181. 0, /* tp_dictoffset */
  13182. 0, /* tp_init */
  13183. 0, /* tp_alloc */
  13184. unicode_new, /* tp_new */
  13185. PyObject_Del, /* tp_free */
  13186. };
  13187. /* Initialize the Unicode implementation */
  13188. static void
  13189. _init_global_state(void)
  13190. {
  13191. static int initialized = 0;
  13192. if (initialized) {
  13193. return;
  13194. }
  13195. initialized = 1;
  13196. /* initialize the linebreak bloom filter */
  13197. const Py_UCS2 linebreak[] = {
  13198. 0x000A, /* LINE FEED */
  13199. 0x000D, /* CARRIAGE RETURN */
  13200. 0x001C, /* FILE SEPARATOR */
  13201. 0x001D, /* GROUP SEPARATOR */
  13202. 0x001E, /* RECORD SEPARATOR */
  13203. 0x0085, /* NEXT LINE */
  13204. 0x2028, /* LINE SEPARATOR */
  13205. 0x2029, /* PARAGRAPH SEPARATOR */
  13206. };
  13207. bloom_linebreak = make_bloom_mask(
  13208. PyUnicode_2BYTE_KIND, linebreak,
  13209. Py_ARRAY_LENGTH(linebreak));
  13210. }
  13211. void
  13212. _PyUnicode_InitState(PyInterpreterState *interp)
  13213. {
  13214. if (!_Py_IsMainInterpreter(interp)) {
  13215. return;
  13216. }
  13217. _init_global_state();
  13218. }
  13219. PyStatus
  13220. _PyUnicode_InitGlobalObjects(PyInterpreterState *interp)
  13221. {
  13222. if (_Py_IsMainInterpreter(interp)) {
  13223. PyStatus status = init_global_interned_strings(interp);
  13224. if (_PyStatus_EXCEPTION(status)) {
  13225. return status;
  13226. }
  13227. }
  13228. assert(INTERNED_STRINGS);
  13229. return _PyStatus_OK();
  13230. }
  13231. PyStatus
  13232. _PyUnicode_InitInternDict(PyInterpreterState *interp)
  13233. {
  13234. assert(INTERNED_STRINGS);
  13235. if (init_interned_dict(interp)) {
  13236. PyErr_Clear();
  13237. return _PyStatus_ERR("failed to create interned dict");
  13238. }
  13239. return _PyStatus_OK();
  13240. }
  13241. PyStatus
  13242. _PyUnicode_InitTypes(PyInterpreterState *interp)
  13243. {
  13244. if (_PyStaticType_InitBuiltin(interp, &EncodingMapType) < 0) {
  13245. goto error;
  13246. }
  13247. if (_PyStaticType_InitBuiltin(interp, &PyFieldNameIter_Type) < 0) {
  13248. goto error;
  13249. }
  13250. if (_PyStaticType_InitBuiltin(interp, &PyFormatterIter_Type) < 0) {
  13251. goto error;
  13252. }
  13253. return _PyStatus_OK();
  13254. error:
  13255. return _PyStatus_ERR("Can't initialize unicode types");
  13256. }
  13257. static /* non-null */ PyObject*
  13258. intern_static(PyInterpreterState *interp, PyObject *s /* stolen */)
  13259. {
  13260. // Note that this steals a reference to `s`, but in many cases that
  13261. // stolen ref is returned, requiring no decref/incref.
  13262. assert(s != NULL);
  13263. assert(_PyUnicode_CHECK(s));
  13264. assert(_PyUnicode_STATE(s).statically_allocated);
  13265. assert(!PyUnicode_CHECK_INTERNED(s));
  13266. #ifdef Py_DEBUG
  13267. /* We must not add process-global interned string if there's already a
  13268. * per-interpreter interned_dict, which might contain duplicates.
  13269. */
  13270. PyObject *interned = get_interned_dict(interp);
  13271. // assert(interned == NULL);
  13272. #endif
  13273. /* Look in the global cache first. */
  13274. PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
  13275. /* We should only init each string once */
  13276. assert(r == NULL);
  13277. /* but just in case (for the non-debug build), handle this */
  13278. if (r != NULL && r != s) {
  13279. assert(_PyUnicode_STATE(r).interned == SSTATE_INTERNED_IMMORTAL_STATIC);
  13280. assert(_PyUnicode_CHECK(r));
  13281. Py_DECREF(s);
  13282. return Py_NewRef(r);
  13283. }
  13284. if (_Py_hashtable_set(INTERNED_STRINGS, s, s) < -1) {
  13285. Py_FatalError("failed to intern static string");
  13286. }
  13287. _PyUnicode_STATE(s).interned = SSTATE_INTERNED_IMMORTAL_STATIC;
  13288. return s;
  13289. }
  13290. void
  13291. _PyUnicode_InternStatic(PyInterpreterState *interp, PyObject **p)
  13292. {
  13293. // This should only be called as part of runtime initialization
  13294. assert(!Py_IsInitialized());
  13295. *p = intern_static(interp, *p);
  13296. assert(*p);
  13297. }
  13298. static void
  13299. immortalize_interned(PyObject *s)
  13300. {
  13301. assert(PyUnicode_CHECK_INTERNED(s) == SSTATE_INTERNED_MORTAL);
  13302. assert(!_Py_IsImmortal(s));
  13303. #ifdef Py_REF_DEBUG
  13304. /* The reference count value should be excluded from the RefTotal.
  13305. The decrements to these objects will not be registered so they
  13306. need to be accounted for in here. */
  13307. for (Py_ssize_t i = 0; i < Py_REFCNT(s); i++) {
  13308. _Py_DecRefTotal(_PyInterpreterState_GET());
  13309. }
  13310. #endif
  13311. _PyUnicode_STATE(s).interned = SSTATE_INTERNED_IMMORTAL;
  13312. _Py_SetImmortal(s);
  13313. }
  13314. static /* non-null */ PyObject*
  13315. intern_common(PyInterpreterState *interp, PyObject *s /* stolen */,
  13316. bool immortalize)
  13317. {
  13318. // Note that this steals a reference to `s`, but in many cases that
  13319. // stolen ref is returned, requiring no decref/incref.
  13320. #ifdef Py_DEBUG
  13321. assert(s != NULL);
  13322. assert(_PyUnicode_CHECK(s));
  13323. #else
  13324. if (s == NULL || !PyUnicode_Check(s)) {
  13325. return s;
  13326. }
  13327. #endif
  13328. /* If it's a subclass, we don't really know what putting
  13329. it in the interned dict might do. */
  13330. if (!PyUnicode_CheckExact(s)) {
  13331. return s;
  13332. }
  13333. /* Is it already interned? */
  13334. switch (PyUnicode_CHECK_INTERNED(s)) {
  13335. case SSTATE_NOT_INTERNED:
  13336. // no, go on
  13337. break;
  13338. case SSTATE_INTERNED_MORTAL:
  13339. // yes but we might need to make it immortal
  13340. if (immortalize) {
  13341. immortalize_interned(s);
  13342. }
  13343. return s;
  13344. default:
  13345. // all done
  13346. return s;
  13347. }
  13348. if (_PyUnicode_STATE(s).statically_allocated) {
  13349. return intern_static(interp, s);
  13350. }
  13351. /* If it's already immortal, intern it as such */
  13352. if (_Py_IsImmortal(s)) {
  13353. immortalize = 1;
  13354. }
  13355. /* if it's a short string, get the singleton */
  13356. if (PyUnicode_GET_LENGTH(s) == 1 &&
  13357. PyUnicode_KIND(s) == PyUnicode_1BYTE_KIND) {
  13358. PyObject *r = LATIN1(*(unsigned char*)PyUnicode_DATA(s));
  13359. assert(PyUnicode_CHECK_INTERNED(r));
  13360. Py_DECREF(s);
  13361. return r;
  13362. }
  13363. #ifdef Py_DEBUG
  13364. assert(!unicode_is_singleton(s));
  13365. #endif
  13366. /* Look in the global cache now. */
  13367. {
  13368. PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
  13369. if (r != NULL) {
  13370. assert(_PyUnicode_STATE(r).statically_allocated);
  13371. assert(r != s); // r must be statically_allocated; s is not
  13372. Py_DECREF(s);
  13373. return Py_NewRef(r);
  13374. }
  13375. }
  13376. /* Do a setdefault on the per-interpreter cache. */
  13377. PyObject *interned = get_interned_dict(interp);
  13378. assert(interned != NULL);
  13379. PyObject *t = PyDict_SetDefault(interned, s, s); // t is borrowed
  13380. if (t == NULL) {
  13381. PyErr_Clear();
  13382. return s;
  13383. }
  13384. if (t != s) {
  13385. // value was already present (not inserted)
  13386. Py_INCREF(t);
  13387. Py_DECREF(s);
  13388. if (immortalize &&
  13389. PyUnicode_CHECK_INTERNED(t) == SSTATE_INTERNED_MORTAL) {
  13390. immortalize_interned(t);
  13391. }
  13392. return t;
  13393. }
  13394. else {
  13395. // value was newly inserted
  13396. }
  13397. /* NOT_INTERNED -> INTERNED_MORTAL */
  13398. assert(_PyUnicode_STATE(s).interned == SSTATE_NOT_INTERNED);
  13399. if (!_Py_IsImmortal(s)) {
  13400. /* The two references in interned dict (key and value) are not counted.
  13401. unicode_dealloc() and _PyUnicode_ClearInterned() take care of this. */
  13402. Py_SET_REFCNT(s, Py_REFCNT(s) - 2);
  13403. #ifdef Py_REF_DEBUG
  13404. /* let's be pedantic with the ref total */
  13405. _Py_DecRefTotal(_PyInterpreterState_GET());
  13406. _Py_DecRefTotal(_PyInterpreterState_GET());
  13407. #endif
  13408. }
  13409. _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
  13410. /* INTERNED_MORTAL -> INTERNED_IMMORTAL (if needed) */
  13411. #ifdef Py_DEBUG
  13412. if (_Py_IsImmortal(s)) {
  13413. assert(immortalize);
  13414. }
  13415. #endif
  13416. if (immortalize) {
  13417. immortalize_interned(s);
  13418. }
  13419. return s;
  13420. }
  13421. void
  13422. _PyUnicode_InternImmortal(PyInterpreterState *interp, PyObject **p)
  13423. {
  13424. *p = intern_common(interp, *p, 1);
  13425. assert(*p);
  13426. }
  13427. void
  13428. _PyUnicode_InternMortal(PyInterpreterState *interp, PyObject **p)
  13429. {
  13430. *p = intern_common(interp, *p, 0);
  13431. assert(*p);
  13432. }
  13433. void
  13434. _PyUnicode_InternInPlace(PyInterpreterState *interp, PyObject **p)
  13435. {
  13436. _PyUnicode_InternImmortal(interp, p);
  13437. return;
  13438. }
  13439. void
  13440. PyUnicode_InternInPlace(PyObject **p)
  13441. {
  13442. PyInterpreterState *interp = _PyInterpreterState_GET();
  13443. _PyUnicode_InternMortal(interp, p);
  13444. }
  13445. // Public-looking name kept for the stable ABI; user should not call this:
  13446. PyAPI_FUNC(void) PyUnicode_InternImmortal(PyObject **);
  13447. void
  13448. PyUnicode_InternImmortal(PyObject **p)
  13449. {
  13450. PyInterpreterState *interp = _PyInterpreterState_GET();
  13451. _PyUnicode_InternImmortal(interp, p);
  13452. }
  13453. PyObject *
  13454. PyUnicode_InternFromString(const char *cp)
  13455. {
  13456. PyObject *s = PyUnicode_FromString(cp);
  13457. if (s == NULL) {
  13458. return NULL;
  13459. }
  13460. PyInterpreterState *interp = _PyInterpreterState_GET();
  13461. _PyUnicode_InternMortal(interp, &s);
  13462. return s;
  13463. }
  13464. void
  13465. _PyUnicode_ClearInterned(PyInterpreterState *interp)
  13466. {
  13467. PyObject *interned = get_interned_dict(interp);
  13468. if (interned == NULL) {
  13469. return;
  13470. }
  13471. assert(PyDict_CheckExact(interned));
  13472. if (has_shared_intern_dict(interp)) {
  13473. // the dict doesn't belong to this interpreter, skip the debug
  13474. // checks on it and just clear the pointer to it
  13475. clear_interned_dict(interp);
  13476. return;
  13477. }
  13478. #ifdef INTERNED_STATS
  13479. fprintf(stderr, "releasing %zd interned strings\n",
  13480. PyDict_GET_SIZE(interned));
  13481. Py_ssize_t total_length = 0;
  13482. #endif
  13483. Py_ssize_t pos = 0;
  13484. PyObject *s, *ignored_value;
  13485. while (PyDict_Next(interned, &pos, &s, &ignored_value)) {
  13486. assert(PyUnicode_IS_READY(s));
  13487. int shared = 0;
  13488. switch (PyUnicode_CHECK_INTERNED(s)) {
  13489. case SSTATE_INTERNED_IMMORTAL:
  13490. /* Make immortal interned strings mortal again.
  13491. *
  13492. * Currently, the runtime is not able to guarantee that it can exit
  13493. * without allocations that carry over to a future initialization
  13494. * of Python within the same process. i.e:
  13495. * ./python -X showrefcount -c 'import itertools'
  13496. * [237 refs, 237 blocks]
  13497. *
  13498. * This should remain disabled (`Py_DEBUG` only) until there is a
  13499. * strict guarantee that no memory will be left after
  13500. * `Py_Finalize`.
  13501. */
  13502. #ifdef Py_DEBUG
  13503. // Skip the Immortal Instance check and restore
  13504. // the two references (key and value) ignored
  13505. // by PyUnicode_InternInPlace().
  13506. s->ob_refcnt = 2;
  13507. #ifdef Py_REF_DEBUG
  13508. /* let's be pedantic with the ref total */
  13509. _Py_IncRefTotal(_PyInterpreterState_GET());
  13510. _Py_IncRefTotal(_PyInterpreterState_GET());
  13511. #endif
  13512. #ifdef INTERNED_STATS
  13513. total_length += PyUnicode_GET_LENGTH(s);
  13514. #endif
  13515. #endif // Py_DEBUG
  13516. break;
  13517. case SSTATE_INTERNED_IMMORTAL_STATIC:
  13518. /* It is shared between interpreters, so we should unmark it
  13519. only when this is the last interpreter in which it's
  13520. interned. We immortalize all the statically initialized
  13521. strings during startup, so we can rely on the
  13522. main interpreter to be the last one. */
  13523. if (!_Py_IsMainInterpreter(interp)) {
  13524. shared = 1;
  13525. }
  13526. break;
  13527. case SSTATE_INTERNED_MORTAL:
  13528. // Restore 2 references held by the interned dict; these will
  13529. // be decref'd by clear_interned_dict's PyDict_Clear.
  13530. Py_SET_REFCNT(s, Py_REFCNT(s) + 2);
  13531. #ifdef Py_REF_DEBUG
  13532. /* let's be pedantic with the ref total */
  13533. _Py_IncRefTotal(_PyInterpreterState_GET());
  13534. _Py_IncRefTotal(_PyInterpreterState_GET());
  13535. #endif
  13536. break;
  13537. case SSTATE_NOT_INTERNED:
  13538. /* fall through */
  13539. default:
  13540. Py_UNREACHABLE();
  13541. }
  13542. if (!shared) {
  13543. _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
  13544. }
  13545. }
  13546. #ifdef INTERNED_STATS
  13547. fprintf(stderr,
  13548. "total length of all interned strings: %zd characters\n",
  13549. total_length);
  13550. #endif
  13551. struct _Py_unicode_state *state = &interp->unicode;
  13552. struct _Py_unicode_ids *ids = &state->ids;
  13553. for (Py_ssize_t i=0; i < ids->size; i++) {
  13554. Py_XINCREF(ids->array[i]);
  13555. }
  13556. clear_interned_dict(interp);
  13557. if (_Py_IsMainInterpreter(interp)) {
  13558. clear_global_interned_strings();
  13559. }
  13560. }
  13561. /********************* Unicode Iterator **************************/
  13562. typedef struct {
  13563. PyObject_HEAD
  13564. Py_ssize_t it_index;
  13565. PyObject *it_seq; /* Set to NULL when iterator is exhausted */
  13566. } unicodeiterobject;
  13567. static void
  13568. unicodeiter_dealloc(unicodeiterobject *it)
  13569. {
  13570. _PyObject_GC_UNTRACK(it);
  13571. Py_XDECREF(it->it_seq);
  13572. PyObject_GC_Del(it);
  13573. }
  13574. static int
  13575. unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
  13576. {
  13577. Py_VISIT(it->it_seq);
  13578. return 0;
  13579. }
  13580. static PyObject *
  13581. unicodeiter_next(unicodeiterobject *it)
  13582. {
  13583. PyObject *seq;
  13584. assert(it != NULL);
  13585. seq = it->it_seq;
  13586. if (seq == NULL)
  13587. return NULL;
  13588. assert(_PyUnicode_CHECK(seq));
  13589. if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
  13590. int kind = PyUnicode_KIND(seq);
  13591. const void *data = PyUnicode_DATA(seq);
  13592. Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
  13593. it->it_index++;
  13594. return unicode_char(chr);
  13595. }
  13596. it->it_seq = NULL;
  13597. Py_DECREF(seq);
  13598. return NULL;
  13599. }
  13600. static PyObject *
  13601. unicode_ascii_iter_next(unicodeiterobject *it)
  13602. {
  13603. assert(it != NULL);
  13604. PyObject *seq = it->it_seq;
  13605. if (seq == NULL) {
  13606. return NULL;
  13607. }
  13608. assert(_PyUnicode_CHECK(seq));
  13609. assert(PyUnicode_IS_COMPACT_ASCII(seq));
  13610. if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
  13611. const void *data = ((void*)(_PyASCIIObject_CAST(seq) + 1));
  13612. Py_UCS1 chr = (Py_UCS1)PyUnicode_READ(PyUnicode_1BYTE_KIND,
  13613. data, it->it_index);
  13614. it->it_index++;
  13615. PyObject *item = (PyObject*)&_Py_SINGLETON(strings).ascii[chr];
  13616. return Py_NewRef(item);
  13617. }
  13618. it->it_seq = NULL;
  13619. Py_DECREF(seq);
  13620. return NULL;
  13621. }
  13622. static PyObject *
  13623. unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
  13624. {
  13625. Py_ssize_t len = 0;
  13626. if (it->it_seq)
  13627. len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
  13628. return PyLong_FromSsize_t(len);
  13629. }
  13630. PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
  13631. static PyObject *
  13632. unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
  13633. {
  13634. PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
  13635. /* _PyEval_GetBuiltin can invoke arbitrary code,
  13636. * call must be before access of iterator pointers.
  13637. * see issue #101765 */
  13638. if (it->it_seq != NULL) {
  13639. return Py_BuildValue("N(O)n", iter, it->it_seq, it->it_index);
  13640. } else {
  13641. PyObject *u = unicode_new_empty();
  13642. if (u == NULL) {
  13643. Py_XDECREF(iter);
  13644. return NULL;
  13645. }
  13646. return Py_BuildValue("N(N)", iter, u);
  13647. }
  13648. }
  13649. PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
  13650. static PyObject *
  13651. unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
  13652. {
  13653. Py_ssize_t index = PyLong_AsSsize_t(state);
  13654. if (index == -1 && PyErr_Occurred())
  13655. return NULL;
  13656. if (it->it_seq != NULL) {
  13657. if (index < 0)
  13658. index = 0;
  13659. else if (index > PyUnicode_GET_LENGTH(it->it_seq))
  13660. index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
  13661. it->it_index = index;
  13662. }
  13663. Py_RETURN_NONE;
  13664. }
  13665. PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
  13666. static PyMethodDef unicodeiter_methods[] = {
  13667. {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
  13668. length_hint_doc},
  13669. {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
  13670. reduce_doc},
  13671. {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
  13672. setstate_doc},
  13673. {NULL, NULL} /* sentinel */
  13674. };
  13675. PyTypeObject PyUnicodeIter_Type = {
  13676. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  13677. "str_iterator", /* tp_name */
  13678. sizeof(unicodeiterobject), /* tp_basicsize */
  13679. 0, /* tp_itemsize */
  13680. /* methods */
  13681. (destructor)unicodeiter_dealloc, /* tp_dealloc */
  13682. 0, /* tp_vectorcall_offset */
  13683. 0, /* tp_getattr */
  13684. 0, /* tp_setattr */
  13685. 0, /* tp_as_async */
  13686. 0, /* tp_repr */
  13687. 0, /* tp_as_number */
  13688. 0, /* tp_as_sequence */
  13689. 0, /* tp_as_mapping */
  13690. 0, /* tp_hash */
  13691. 0, /* tp_call */
  13692. 0, /* tp_str */
  13693. PyObject_GenericGetAttr, /* tp_getattro */
  13694. 0, /* tp_setattro */
  13695. 0, /* tp_as_buffer */
  13696. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  13697. 0, /* tp_doc */
  13698. (traverseproc)unicodeiter_traverse, /* tp_traverse */
  13699. 0, /* tp_clear */
  13700. 0, /* tp_richcompare */
  13701. 0, /* tp_weaklistoffset */
  13702. PyObject_SelfIter, /* tp_iter */
  13703. (iternextfunc)unicodeiter_next, /* tp_iternext */
  13704. unicodeiter_methods, /* tp_methods */
  13705. 0,
  13706. };
  13707. PyTypeObject _PyUnicodeASCIIIter_Type = {
  13708. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  13709. .tp_name = "str_ascii_iterator",
  13710. .tp_basicsize = sizeof(unicodeiterobject),
  13711. .tp_dealloc = (destructor)unicodeiter_dealloc,
  13712. .tp_getattro = PyObject_GenericGetAttr,
  13713. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  13714. .tp_traverse = (traverseproc)unicodeiter_traverse,
  13715. .tp_iter = PyObject_SelfIter,
  13716. .tp_iternext = (iternextfunc)unicode_ascii_iter_next,
  13717. .tp_methods = unicodeiter_methods,
  13718. };
  13719. static PyObject *
  13720. unicode_iter(PyObject *seq)
  13721. {
  13722. unicodeiterobject *it;
  13723. if (!PyUnicode_Check(seq)) {
  13724. PyErr_BadInternalCall();
  13725. return NULL;
  13726. }
  13727. if (PyUnicode_IS_COMPACT_ASCII(seq)) {
  13728. it = PyObject_GC_New(unicodeiterobject, &_PyUnicodeASCIIIter_Type);
  13729. }
  13730. else {
  13731. it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
  13732. }
  13733. if (it == NULL)
  13734. return NULL;
  13735. it->it_index = 0;
  13736. it->it_seq = Py_NewRef(seq);
  13737. _PyObject_GC_TRACK(it);
  13738. return (PyObject *)it;
  13739. }
  13740. static int
  13741. encode_wstr_utf8(wchar_t *wstr, char **str, const char *name)
  13742. {
  13743. int res;
  13744. res = _Py_EncodeUTF8Ex(wstr, str, NULL, NULL, 1, _Py_ERROR_STRICT);
  13745. if (res == -2) {
  13746. PyErr_Format(PyExc_RuntimeError, "cannot encode %s", name);
  13747. return -1;
  13748. }
  13749. if (res < 0) {
  13750. PyErr_NoMemory();
  13751. return -1;
  13752. }
  13753. return 0;
  13754. }
  13755. static int
  13756. config_get_codec_name(wchar_t **config_encoding)
  13757. {
  13758. char *encoding;
  13759. if (encode_wstr_utf8(*config_encoding, &encoding, "stdio_encoding") < 0) {
  13760. return -1;
  13761. }
  13762. PyObject *name_obj = NULL;
  13763. PyObject *codec = _PyCodec_Lookup(encoding);
  13764. PyMem_RawFree(encoding);
  13765. if (!codec)
  13766. goto error;
  13767. name_obj = PyObject_GetAttrString(codec, "name");
  13768. Py_CLEAR(codec);
  13769. if (!name_obj) {
  13770. goto error;
  13771. }
  13772. wchar_t *wname = PyUnicode_AsWideCharString(name_obj, NULL);
  13773. Py_DECREF(name_obj);
  13774. if (wname == NULL) {
  13775. goto error;
  13776. }
  13777. wchar_t *raw_wname = _PyMem_RawWcsdup(wname);
  13778. if (raw_wname == NULL) {
  13779. PyMem_Free(wname);
  13780. PyErr_NoMemory();
  13781. goto error;
  13782. }
  13783. PyMem_RawFree(*config_encoding);
  13784. *config_encoding = raw_wname;
  13785. PyMem_Free(wname);
  13786. return 0;
  13787. error:
  13788. Py_XDECREF(codec);
  13789. Py_XDECREF(name_obj);
  13790. return -1;
  13791. }
  13792. static PyStatus
  13793. init_stdio_encoding(PyInterpreterState *interp)
  13794. {
  13795. /* Update the stdio encoding to the normalized Python codec name. */
  13796. PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
  13797. if (config_get_codec_name(&config->stdio_encoding) < 0) {
  13798. return _PyStatus_ERR("failed to get the Python codec name "
  13799. "of the stdio encoding");
  13800. }
  13801. return _PyStatus_OK();
  13802. }
  13803. static int
  13804. init_fs_codec(PyInterpreterState *interp)
  13805. {
  13806. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  13807. _Py_error_handler error_handler;
  13808. error_handler = get_error_handler_wide(config->filesystem_errors);
  13809. if (error_handler == _Py_ERROR_UNKNOWN) {
  13810. PyErr_SetString(PyExc_RuntimeError, "unknown filesystem error handler");
  13811. return -1;
  13812. }
  13813. char *encoding, *errors;
  13814. if (encode_wstr_utf8(config->filesystem_encoding,
  13815. &encoding,
  13816. "filesystem_encoding") < 0) {
  13817. return -1;
  13818. }
  13819. if (encode_wstr_utf8(config->filesystem_errors,
  13820. &errors,
  13821. "filesystem_errors") < 0) {
  13822. PyMem_RawFree(encoding);
  13823. return -1;
  13824. }
  13825. struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
  13826. PyMem_RawFree(fs_codec->encoding);
  13827. fs_codec->encoding = encoding;
  13828. /* encoding has been normalized by init_fs_encoding() */
  13829. fs_codec->utf8 = (strcmp(encoding, "utf-8") == 0);
  13830. PyMem_RawFree(fs_codec->errors);
  13831. fs_codec->errors = errors;
  13832. fs_codec->error_handler = error_handler;
  13833. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  13834. assert(fs_codec->utf8 == 1);
  13835. #endif
  13836. /* At this point, PyUnicode_EncodeFSDefault() and
  13837. PyUnicode_DecodeFSDefault() can now use the Python codec rather than
  13838. the C implementation of the filesystem encoding. */
  13839. /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
  13840. global configuration variables. */
  13841. if (_Py_IsMainInterpreter(interp)) {
  13842. if (_Py_SetFileSystemEncoding(fs_codec->encoding,
  13843. fs_codec->errors) < 0) {
  13844. PyErr_NoMemory();
  13845. return -1;
  13846. }
  13847. }
  13848. return 0;
  13849. }
  13850. static PyStatus
  13851. init_fs_encoding(PyThreadState *tstate)
  13852. {
  13853. PyInterpreterState *interp = tstate->interp;
  13854. /* Update the filesystem encoding to the normalized Python codec name.
  13855. For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
  13856. (Python codec name). */
  13857. PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
  13858. if (config_get_codec_name(&config->filesystem_encoding) < 0) {
  13859. _Py_DumpPathConfig(tstate);
  13860. return _PyStatus_ERR("failed to get the Python codec "
  13861. "of the filesystem encoding");
  13862. }
  13863. if (init_fs_codec(interp) < 0) {
  13864. return _PyStatus_ERR("cannot initialize filesystem codec");
  13865. }
  13866. return _PyStatus_OK();
  13867. }
  13868. PyStatus
  13869. _PyUnicode_InitEncodings(PyThreadState *tstate)
  13870. {
  13871. PyStatus status = init_fs_encoding(tstate);
  13872. if (_PyStatus_EXCEPTION(status)) {
  13873. return status;
  13874. }
  13875. return init_stdio_encoding(tstate->interp);
  13876. }
  13877. static void
  13878. _PyUnicode_FiniEncodings(struct _Py_unicode_fs_codec *fs_codec)
  13879. {
  13880. PyMem_RawFree(fs_codec->encoding);
  13881. fs_codec->encoding = NULL;
  13882. fs_codec->utf8 = 0;
  13883. PyMem_RawFree(fs_codec->errors);
  13884. fs_codec->errors = NULL;
  13885. fs_codec->error_handler = _Py_ERROR_UNKNOWN;
  13886. }
  13887. #ifdef MS_WINDOWS
  13888. int
  13889. _PyUnicode_EnableLegacyWindowsFSEncoding(void)
  13890. {
  13891. PyInterpreterState *interp = _PyInterpreterState_GET();
  13892. PyConfig *config = (PyConfig *)_PyInterpreterState_GetConfig(interp);
  13893. /* Set the filesystem encoding to mbcs/replace (PEP 529) */
  13894. wchar_t *encoding = _PyMem_RawWcsdup(L"mbcs");
  13895. wchar_t *errors = _PyMem_RawWcsdup(L"replace");
  13896. if (encoding == NULL || errors == NULL) {
  13897. PyMem_RawFree(encoding);
  13898. PyMem_RawFree(errors);
  13899. PyErr_NoMemory();
  13900. return -1;
  13901. }
  13902. PyMem_RawFree(config->filesystem_encoding);
  13903. config->filesystem_encoding = encoding;
  13904. PyMem_RawFree(config->filesystem_errors);
  13905. config->filesystem_errors = errors;
  13906. return init_fs_codec(interp);
  13907. }
  13908. #endif
  13909. #ifdef Py_DEBUG
  13910. static inline int
  13911. unicode_is_finalizing(void)
  13912. {
  13913. return (get_interned_dict(_PyInterpreterState_Main()) == NULL);
  13914. }
  13915. #endif
  13916. void
  13917. _PyUnicode_FiniTypes(PyInterpreterState *interp)
  13918. {
  13919. _PyStaticType_Dealloc(interp, &EncodingMapType);
  13920. _PyStaticType_Dealloc(interp, &PyFieldNameIter_Type);
  13921. _PyStaticType_Dealloc(interp, &PyFormatterIter_Type);
  13922. }
  13923. void
  13924. _PyUnicode_Fini(PyInterpreterState *interp)
  13925. {
  13926. struct _Py_unicode_state *state = &interp->unicode;
  13927. if (!has_shared_intern_dict(interp)) {
  13928. // _PyUnicode_ClearInterned() must be called before _PyUnicode_Fini()
  13929. assert(get_interned_dict(interp) == NULL);
  13930. }
  13931. _PyUnicode_FiniEncodings(&state->fs_codec);
  13932. // bpo-47182: force a unicodedata CAPI capsule re-import on
  13933. // subsequent initialization of interpreter.
  13934. interp->unicode.ucnhash_capi = NULL;
  13935. unicode_clear_identifiers(state);
  13936. }
  13937. /* A _string module, to export formatter_parser and formatter_field_name_split
  13938. to the string.Formatter class implemented in Python. */
  13939. static PyMethodDef _string_methods[] = {
  13940. {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
  13941. METH_O, PyDoc_STR("split the argument as a field name")},
  13942. {"formatter_parser", (PyCFunction) formatter_parser,
  13943. METH_O, PyDoc_STR("parse the argument as a format string")},
  13944. {NULL, NULL}
  13945. };
  13946. static PyModuleDef_Slot module_slots[] = {
  13947. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  13948. {0, NULL}
  13949. };
  13950. static struct PyModuleDef _string_module = {
  13951. PyModuleDef_HEAD_INIT,
  13952. .m_name = "_string",
  13953. .m_doc = PyDoc_STR("string helper module"),
  13954. .m_size = 0,
  13955. .m_methods = _string_methods,
  13956. .m_slots = module_slots,
  13957. };
  13958. PyMODINIT_FUNC
  13959. PyInit__string(void)
  13960. {
  13961. return PyModuleDef_Init(&_string_module);
  13962. }
  13963. #ifdef __cplusplus
  13964. }
  13965. #endif