unicodeobject.c 446 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418
  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(ch) \
  152. (ch < 128 \
  153. ? (PyObject*)&_Py_SINGLETON(strings).ascii[ch] \
  154. : (PyObject*)&_Py_SINGLETON(strings).latin1[ch - 128])
  155. #ifdef MS_WINDOWS
  156. /* On Windows, overallocate by 50% is the best factor */
  157. # define OVERALLOCATE_FACTOR 2
  158. #else
  159. /* On Linux, overallocate by 25% is the best factor */
  160. # define OVERALLOCATE_FACTOR 4
  161. #endif
  162. /* Forward declaration */
  163. static inline int
  164. _PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch);
  165. static inline void
  166. _PyUnicodeWriter_InitWithBuffer(_PyUnicodeWriter *writer, PyObject *buffer);
  167. static PyObject *
  168. unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
  169. const char *errors);
  170. static PyObject *
  171. unicode_decode_utf8(const char *s, Py_ssize_t size,
  172. _Py_error_handler error_handler, const char *errors,
  173. Py_ssize_t *consumed);
  174. #ifdef Py_DEBUG
  175. static inline int unicode_is_finalizing(void);
  176. static int unicode_is_singleton(PyObject *unicode);
  177. #endif
  178. // Return a borrowed reference to the empty string singleton.
  179. static inline PyObject* unicode_get_empty(void)
  180. {
  181. _Py_DECLARE_STR(empty, "");
  182. return &_Py_STR(empty);
  183. }
  184. // Return a strong reference to the empty string singleton.
  185. static inline PyObject* unicode_new_empty(void)
  186. {
  187. PyObject *empty = unicode_get_empty();
  188. return Py_NewRef(empty);
  189. }
  190. /* This dictionary holds all interned unicode strings. Note that references
  191. to strings in this dictionary are *not* counted in the string's ob_refcnt.
  192. When the interned string reaches a refcnt of 0 the string deallocation
  193. function will delete the reference from this dictionary.
  194. */
  195. static inline PyObject *get_interned_dict(PyInterpreterState *interp)
  196. {
  197. return _Py_INTERP_CACHED_OBJECT(interp, interned_strings);
  198. }
  199. #define INTERNED_STRINGS _PyRuntime.cached_objects.interned_strings
  200. Py_ssize_t
  201. _PyUnicode_InternedSize(void)
  202. {
  203. PyObject *dict = get_interned_dict(_PyInterpreterState_GET());
  204. return _Py_hashtable_len(INTERNED_STRINGS) + PyDict_GET_SIZE(dict);
  205. }
  206. static Py_hash_t unicode_hash(PyObject *);
  207. static int unicode_compare_eq(PyObject *, PyObject *);
  208. static Py_uhash_t
  209. hashtable_unicode_hash(const void *key)
  210. {
  211. return unicode_hash((PyObject *)key);
  212. }
  213. static int
  214. hashtable_unicode_compare(const void *key1, const void *key2)
  215. {
  216. PyObject *obj1 = (PyObject *)key1;
  217. PyObject *obj2 = (PyObject *)key2;
  218. if (obj1 != NULL && obj2 != NULL) {
  219. return unicode_compare_eq(obj1, obj2);
  220. }
  221. else {
  222. return obj1 == obj2;
  223. }
  224. }
  225. static int
  226. init_interned_dict(PyInterpreterState *interp)
  227. {
  228. if (_Py_IsMainInterpreter(interp)) {
  229. assert(INTERNED_STRINGS == NULL);
  230. _Py_hashtable_allocator_t hashtable_alloc = {PyMem_RawMalloc, PyMem_RawFree};
  231. INTERNED_STRINGS = _Py_hashtable_new_full(
  232. hashtable_unicode_hash,
  233. hashtable_unicode_compare,
  234. NULL,
  235. NULL,
  236. &hashtable_alloc
  237. );
  238. if (INTERNED_STRINGS == NULL) {
  239. return -1;
  240. }
  241. }
  242. assert(get_interned_dict(interp) == NULL);
  243. PyObject *interned = interned = PyDict_New();
  244. if (interned == NULL) {
  245. return -1;
  246. }
  247. _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = interned;
  248. return 0;
  249. }
  250. static void
  251. clear_interned_dict(PyInterpreterState *interp)
  252. {
  253. PyObject *interned = get_interned_dict(interp);
  254. if (interned != NULL) {
  255. PyDict_Clear(interned);
  256. Py_DECREF(interned);
  257. _Py_INTERP_CACHED_OBJECT(interp, interned_strings) = NULL;
  258. }
  259. if (_Py_IsMainInterpreter(interp) && INTERNED_STRINGS != NULL) {
  260. _Py_hashtable_destroy(INTERNED_STRINGS);
  261. INTERNED_STRINGS = NULL;
  262. }
  263. }
  264. #define _Py_RETURN_UNICODE_EMPTY() \
  265. do { \
  266. return unicode_new_empty(); \
  267. } while (0)
  268. static inline void
  269. unicode_fill(int kind, void *data, Py_UCS4 value,
  270. Py_ssize_t start, Py_ssize_t length)
  271. {
  272. assert(0 <= start);
  273. switch (kind) {
  274. case PyUnicode_1BYTE_KIND: {
  275. assert(value <= 0xff);
  276. Py_UCS1 ch = (unsigned char)value;
  277. Py_UCS1 *to = (Py_UCS1 *)data + start;
  278. memset(to, ch, length);
  279. break;
  280. }
  281. case PyUnicode_2BYTE_KIND: {
  282. assert(value <= 0xffff);
  283. Py_UCS2 ch = (Py_UCS2)value;
  284. Py_UCS2 *to = (Py_UCS2 *)data + start;
  285. const Py_UCS2 *end = to + length;
  286. for (; to < end; ++to) *to = ch;
  287. break;
  288. }
  289. case PyUnicode_4BYTE_KIND: {
  290. assert(value <= MAX_UNICODE);
  291. Py_UCS4 ch = value;
  292. Py_UCS4 * to = (Py_UCS4 *)data + start;
  293. const Py_UCS4 *end = to + length;
  294. for (; to < end; ++to) *to = ch;
  295. break;
  296. }
  297. default: Py_UNREACHABLE();
  298. }
  299. }
  300. /* Fast detection of the most frequent whitespace characters */
  301. const unsigned char _Py_ascii_whitespace[] = {
  302. 0, 0, 0, 0, 0, 0, 0, 0,
  303. /* case 0x0009: * CHARACTER TABULATION */
  304. /* case 0x000A: * LINE FEED */
  305. /* case 0x000B: * LINE TABULATION */
  306. /* case 0x000C: * FORM FEED */
  307. /* case 0x000D: * CARRIAGE RETURN */
  308. 0, 1, 1, 1, 1, 1, 0, 0,
  309. 0, 0, 0, 0, 0, 0, 0, 0,
  310. /* case 0x001C: * FILE SEPARATOR */
  311. /* case 0x001D: * GROUP SEPARATOR */
  312. /* case 0x001E: * RECORD SEPARATOR */
  313. /* case 0x001F: * UNIT SEPARATOR */
  314. 0, 0, 0, 0, 1, 1, 1, 1,
  315. /* case 0x0020: * SPACE */
  316. 1, 0, 0, 0, 0, 0, 0, 0,
  317. 0, 0, 0, 0, 0, 0, 0, 0,
  318. 0, 0, 0, 0, 0, 0, 0, 0,
  319. 0, 0, 0, 0, 0, 0, 0, 0,
  320. 0, 0, 0, 0, 0, 0, 0, 0,
  321. 0, 0, 0, 0, 0, 0, 0, 0,
  322. 0, 0, 0, 0, 0, 0, 0, 0,
  323. 0, 0, 0, 0, 0, 0, 0, 0,
  324. 0, 0, 0, 0, 0, 0, 0, 0,
  325. 0, 0, 0, 0, 0, 0, 0, 0,
  326. 0, 0, 0, 0, 0, 0, 0, 0,
  327. 0, 0, 0, 0, 0, 0, 0, 0
  328. };
  329. /* forward */
  330. static PyObject* get_latin1_char(unsigned char ch);
  331. static int unicode_modifiable(PyObject *unicode);
  332. static PyObject *
  333. _PyUnicode_FromUCS1(const Py_UCS1 *s, Py_ssize_t size);
  334. static PyObject *
  335. _PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
  336. static PyObject *
  337. _PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
  338. static PyObject *
  339. unicode_encode_call_errorhandler(const char *errors,
  340. PyObject **errorHandler,const char *encoding, const char *reason,
  341. PyObject *unicode, PyObject **exceptionObject,
  342. Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
  343. static void
  344. raise_encode_exception(PyObject **exceptionObject,
  345. const char *encoding,
  346. PyObject *unicode,
  347. Py_ssize_t startpos, Py_ssize_t endpos,
  348. const char *reason);
  349. /* Same for linebreaks */
  350. static const unsigned char ascii_linebreak[] = {
  351. 0, 0, 0, 0, 0, 0, 0, 0,
  352. /* 0x000A, * LINE FEED */
  353. /* 0x000B, * LINE TABULATION */
  354. /* 0x000C, * FORM FEED */
  355. /* 0x000D, * CARRIAGE RETURN */
  356. 0, 0, 1, 1, 1, 1, 0, 0,
  357. 0, 0, 0, 0, 0, 0, 0, 0,
  358. /* 0x001C, * FILE SEPARATOR */
  359. /* 0x001D, * GROUP SEPARATOR */
  360. /* 0x001E, * RECORD SEPARATOR */
  361. 0, 0, 0, 0, 1, 1, 1, 0,
  362. 0, 0, 0, 0, 0, 0, 0, 0,
  363. 0, 0, 0, 0, 0, 0, 0, 0,
  364. 0, 0, 0, 0, 0, 0, 0, 0,
  365. 0, 0, 0, 0, 0, 0, 0, 0,
  366. 0, 0, 0, 0, 0, 0, 0, 0,
  367. 0, 0, 0, 0, 0, 0, 0, 0,
  368. 0, 0, 0, 0, 0, 0, 0, 0,
  369. 0, 0, 0, 0, 0, 0, 0, 0,
  370. 0, 0, 0, 0, 0, 0, 0, 0,
  371. 0, 0, 0, 0, 0, 0, 0, 0,
  372. 0, 0, 0, 0, 0, 0, 0, 0,
  373. 0, 0, 0, 0, 0, 0, 0, 0
  374. };
  375. static int convert_uc(PyObject *obj, void *addr);
  376. struct encoding_map;
  377. #include "clinic/unicodeobject.c.h"
  378. _Py_error_handler
  379. _Py_GetErrorHandler(const char *errors)
  380. {
  381. if (errors == NULL || strcmp(errors, "strict") == 0) {
  382. return _Py_ERROR_STRICT;
  383. }
  384. if (strcmp(errors, "surrogateescape") == 0) {
  385. return _Py_ERROR_SURROGATEESCAPE;
  386. }
  387. if (strcmp(errors, "replace") == 0) {
  388. return _Py_ERROR_REPLACE;
  389. }
  390. if (strcmp(errors, "ignore") == 0) {
  391. return _Py_ERROR_IGNORE;
  392. }
  393. if (strcmp(errors, "backslashreplace") == 0) {
  394. return _Py_ERROR_BACKSLASHREPLACE;
  395. }
  396. if (strcmp(errors, "surrogatepass") == 0) {
  397. return _Py_ERROR_SURROGATEPASS;
  398. }
  399. if (strcmp(errors, "xmlcharrefreplace") == 0) {
  400. return _Py_ERROR_XMLCHARREFREPLACE;
  401. }
  402. return _Py_ERROR_OTHER;
  403. }
  404. static _Py_error_handler
  405. get_error_handler_wide(const wchar_t *errors)
  406. {
  407. if (errors == NULL || wcscmp(errors, L"strict") == 0) {
  408. return _Py_ERROR_STRICT;
  409. }
  410. if (wcscmp(errors, L"surrogateescape") == 0) {
  411. return _Py_ERROR_SURROGATEESCAPE;
  412. }
  413. if (wcscmp(errors, L"replace") == 0) {
  414. return _Py_ERROR_REPLACE;
  415. }
  416. if (wcscmp(errors, L"ignore") == 0) {
  417. return _Py_ERROR_IGNORE;
  418. }
  419. if (wcscmp(errors, L"backslashreplace") == 0) {
  420. return _Py_ERROR_BACKSLASHREPLACE;
  421. }
  422. if (wcscmp(errors, L"surrogatepass") == 0) {
  423. return _Py_ERROR_SURROGATEPASS;
  424. }
  425. if (wcscmp(errors, L"xmlcharrefreplace") == 0) {
  426. return _Py_ERROR_XMLCHARREFREPLACE;
  427. }
  428. return _Py_ERROR_OTHER;
  429. }
  430. static inline int
  431. unicode_check_encoding_errors(const char *encoding, const char *errors)
  432. {
  433. if (encoding == NULL && errors == NULL) {
  434. return 0;
  435. }
  436. PyInterpreterState *interp = _PyInterpreterState_GET();
  437. #ifndef Py_DEBUG
  438. /* In release mode, only check in development mode (-X dev) */
  439. if (!_PyInterpreterState_GetConfig(interp)->dev_mode) {
  440. return 0;
  441. }
  442. #else
  443. /* Always check in debug mode */
  444. #endif
  445. /* Avoid calling _PyCodec_Lookup() and PyCodec_LookupError() before the
  446. codec registry is ready: before_PyUnicode_InitEncodings() is called. */
  447. if (!interp->unicode.fs_codec.encoding) {
  448. return 0;
  449. }
  450. /* Disable checks during Python finalization. For example, it allows to
  451. call _PyObject_Dump() during finalization for debugging purpose. */
  452. if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
  453. return 0;
  454. }
  455. if (encoding != NULL
  456. // Fast path for the most common built-in encodings. Even if the codec
  457. // is cached, _PyCodec_Lookup() decodes the bytes string from UTF-8 to
  458. // create a temporary Unicode string (the key in the cache).
  459. && strcmp(encoding, "utf-8") != 0
  460. && strcmp(encoding, "utf8") != 0
  461. && strcmp(encoding, "ascii") != 0)
  462. {
  463. PyObject *handler = _PyCodec_Lookup(encoding);
  464. if (handler == NULL) {
  465. return -1;
  466. }
  467. Py_DECREF(handler);
  468. }
  469. if (errors != NULL
  470. // Fast path for the most common built-in error handlers.
  471. && strcmp(errors, "strict") != 0
  472. && strcmp(errors, "ignore") != 0
  473. && strcmp(errors, "replace") != 0
  474. && strcmp(errors, "surrogateescape") != 0
  475. && strcmp(errors, "surrogatepass") != 0)
  476. {
  477. PyObject *handler = PyCodec_LookupError(errors);
  478. if (handler == NULL) {
  479. return -1;
  480. }
  481. Py_DECREF(handler);
  482. }
  483. return 0;
  484. }
  485. int
  486. _PyUnicode_CheckConsistency(PyObject *op, int check_content)
  487. {
  488. #define CHECK(expr) \
  489. do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
  490. assert(op != NULL);
  491. CHECK(PyUnicode_Check(op));
  492. PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
  493. int kind = ascii->state.kind;
  494. if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
  495. CHECK(kind == PyUnicode_1BYTE_KIND);
  496. }
  497. else {
  498. PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
  499. void *data;
  500. if (ascii->state.compact == 1) {
  501. data = compact + 1;
  502. CHECK(kind == PyUnicode_1BYTE_KIND
  503. || kind == PyUnicode_2BYTE_KIND
  504. || kind == PyUnicode_4BYTE_KIND);
  505. CHECK(ascii->state.ascii == 0);
  506. CHECK(compact->utf8 != data);
  507. }
  508. else {
  509. PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
  510. data = unicode->data.any;
  511. CHECK(kind == PyUnicode_1BYTE_KIND
  512. || kind == PyUnicode_2BYTE_KIND
  513. || kind == PyUnicode_4BYTE_KIND);
  514. CHECK(ascii->state.compact == 0);
  515. CHECK(data != NULL);
  516. if (ascii->state.ascii) {
  517. CHECK(compact->utf8 == data);
  518. CHECK(compact->utf8_length == ascii->length);
  519. }
  520. else {
  521. CHECK(compact->utf8 != data);
  522. }
  523. }
  524. if (compact->utf8 == NULL)
  525. CHECK(compact->utf8_length == 0);
  526. }
  527. /* check that the best kind is used: O(n) operation */
  528. if (check_content) {
  529. Py_ssize_t i;
  530. Py_UCS4 maxchar = 0;
  531. const void *data;
  532. Py_UCS4 ch;
  533. data = PyUnicode_DATA(ascii);
  534. for (i=0; i < ascii->length; i++)
  535. {
  536. ch = PyUnicode_READ(kind, data, i);
  537. if (ch > maxchar)
  538. maxchar = ch;
  539. }
  540. if (kind == PyUnicode_1BYTE_KIND) {
  541. if (ascii->state.ascii == 0) {
  542. CHECK(maxchar >= 128);
  543. CHECK(maxchar <= 255);
  544. }
  545. else
  546. CHECK(maxchar < 128);
  547. }
  548. else if (kind == PyUnicode_2BYTE_KIND) {
  549. CHECK(maxchar >= 0x100);
  550. CHECK(maxchar <= 0xFFFF);
  551. }
  552. else {
  553. CHECK(maxchar >= 0x10000);
  554. CHECK(maxchar <= MAX_UNICODE);
  555. }
  556. CHECK(PyUnicode_READ(kind, data, ascii->length) == 0);
  557. }
  558. return 1;
  559. #undef CHECK
  560. }
  561. static PyObject*
  562. unicode_result(PyObject *unicode)
  563. {
  564. assert(_PyUnicode_CHECK(unicode));
  565. Py_ssize_t length = PyUnicode_GET_LENGTH(unicode);
  566. if (length == 0) {
  567. PyObject *empty = unicode_get_empty();
  568. if (unicode != empty) {
  569. Py_DECREF(unicode);
  570. Py_INCREF(empty);
  571. }
  572. return empty;
  573. }
  574. if (length == 1) {
  575. int kind = PyUnicode_KIND(unicode);
  576. if (kind == PyUnicode_1BYTE_KIND) {
  577. const Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
  578. Py_UCS1 ch = data[0];
  579. PyObject *latin1_char = LATIN1(ch);
  580. if (unicode != latin1_char) {
  581. Py_INCREF(latin1_char);
  582. Py_DECREF(unicode);
  583. }
  584. return latin1_char;
  585. }
  586. }
  587. assert(_PyUnicode_CheckConsistency(unicode, 1));
  588. return unicode;
  589. }
  590. static PyObject*
  591. unicode_result_unchanged(PyObject *unicode)
  592. {
  593. if (PyUnicode_CheckExact(unicode)) {
  594. return Py_NewRef(unicode);
  595. }
  596. else
  597. /* Subtype -- return genuine unicode string with the same value. */
  598. return _PyUnicode_Copy(unicode);
  599. }
  600. /* Implementation of the "backslashreplace" error handler for 8-bit encodings:
  601. ASCII, Latin1, UTF-8, etc. */
  602. static char*
  603. backslashreplace(_PyBytesWriter *writer, char *str,
  604. PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
  605. {
  606. Py_ssize_t size, i;
  607. Py_UCS4 ch;
  608. int kind;
  609. const void *data;
  610. kind = PyUnicode_KIND(unicode);
  611. data = PyUnicode_DATA(unicode);
  612. size = 0;
  613. /* determine replacement size */
  614. for (i = collstart; i < collend; ++i) {
  615. Py_ssize_t incr;
  616. ch = PyUnicode_READ(kind, data, i);
  617. if (ch < 0x100)
  618. incr = 2+2;
  619. else if (ch < 0x10000)
  620. incr = 2+4;
  621. else {
  622. assert(ch <= MAX_UNICODE);
  623. incr = 2+8;
  624. }
  625. if (size > PY_SSIZE_T_MAX - incr) {
  626. PyErr_SetString(PyExc_OverflowError,
  627. "encoded result is too long for a Python string");
  628. return NULL;
  629. }
  630. size += incr;
  631. }
  632. str = _PyBytesWriter_Prepare(writer, str, size);
  633. if (str == NULL)
  634. return NULL;
  635. /* generate replacement */
  636. for (i = collstart; i < collend; ++i) {
  637. ch = PyUnicode_READ(kind, data, i);
  638. *str++ = '\\';
  639. if (ch >= 0x00010000) {
  640. *str++ = 'U';
  641. *str++ = Py_hexdigits[(ch>>28)&0xf];
  642. *str++ = Py_hexdigits[(ch>>24)&0xf];
  643. *str++ = Py_hexdigits[(ch>>20)&0xf];
  644. *str++ = Py_hexdigits[(ch>>16)&0xf];
  645. *str++ = Py_hexdigits[(ch>>12)&0xf];
  646. *str++ = Py_hexdigits[(ch>>8)&0xf];
  647. }
  648. else if (ch >= 0x100) {
  649. *str++ = 'u';
  650. *str++ = Py_hexdigits[(ch>>12)&0xf];
  651. *str++ = Py_hexdigits[(ch>>8)&0xf];
  652. }
  653. else
  654. *str++ = 'x';
  655. *str++ = Py_hexdigits[(ch>>4)&0xf];
  656. *str++ = Py_hexdigits[ch&0xf];
  657. }
  658. return str;
  659. }
  660. /* Implementation of the "xmlcharrefreplace" error handler for 8-bit encodings:
  661. ASCII, Latin1, UTF-8, etc. */
  662. static char*
  663. xmlcharrefreplace(_PyBytesWriter *writer, char *str,
  664. PyObject *unicode, Py_ssize_t collstart, Py_ssize_t collend)
  665. {
  666. Py_ssize_t size, i;
  667. Py_UCS4 ch;
  668. int kind;
  669. const void *data;
  670. kind = PyUnicode_KIND(unicode);
  671. data = PyUnicode_DATA(unicode);
  672. size = 0;
  673. /* determine replacement size */
  674. for (i = collstart; i < collend; ++i) {
  675. Py_ssize_t incr;
  676. ch = PyUnicode_READ(kind, data, i);
  677. if (ch < 10)
  678. incr = 2+1+1;
  679. else if (ch < 100)
  680. incr = 2+2+1;
  681. else if (ch < 1000)
  682. incr = 2+3+1;
  683. else if (ch < 10000)
  684. incr = 2+4+1;
  685. else if (ch < 100000)
  686. incr = 2+5+1;
  687. else if (ch < 1000000)
  688. incr = 2+6+1;
  689. else {
  690. assert(ch <= MAX_UNICODE);
  691. incr = 2+7+1;
  692. }
  693. if (size > PY_SSIZE_T_MAX - incr) {
  694. PyErr_SetString(PyExc_OverflowError,
  695. "encoded result is too long for a Python string");
  696. return NULL;
  697. }
  698. size += incr;
  699. }
  700. str = _PyBytesWriter_Prepare(writer, str, size);
  701. if (str == NULL)
  702. return NULL;
  703. /* generate replacement */
  704. for (i = collstart; i < collend; ++i) {
  705. size = sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
  706. if (size < 0) {
  707. return NULL;
  708. }
  709. str += size;
  710. }
  711. return str;
  712. }
  713. /* --- Bloom Filters ----------------------------------------------------- */
  714. /* stuff to implement simple "bloom filters" for Unicode characters.
  715. to keep things simple, we use a single bitmask, using the least 5
  716. bits from each unicode characters as the bit index. */
  717. /* the linebreak mask is set up by _PyUnicode_Init() below */
  718. #if LONG_BIT >= 128
  719. #define BLOOM_WIDTH 128
  720. #elif LONG_BIT >= 64
  721. #define BLOOM_WIDTH 64
  722. #elif LONG_BIT >= 32
  723. #define BLOOM_WIDTH 32
  724. #else
  725. #error "LONG_BIT is smaller than 32"
  726. #endif
  727. #define BLOOM_MASK unsigned long
  728. static BLOOM_MASK bloom_linebreak = ~(BLOOM_MASK)0;
  729. #define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
  730. #define BLOOM_LINEBREAK(ch) \
  731. ((ch) < 128U ? ascii_linebreak[(ch)] : \
  732. (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
  733. static inline BLOOM_MASK
  734. make_bloom_mask(int kind, const void* ptr, Py_ssize_t len)
  735. {
  736. #define BLOOM_UPDATE(TYPE, MASK, PTR, LEN) \
  737. do { \
  738. TYPE *data = (TYPE *)PTR; \
  739. TYPE *end = data + LEN; \
  740. Py_UCS4 ch; \
  741. for (; data != end; data++) { \
  742. ch = *data; \
  743. MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \
  744. } \
  745. break; \
  746. } while (0)
  747. /* calculate simple bloom-style bitmask for a given unicode string */
  748. BLOOM_MASK mask;
  749. mask = 0;
  750. switch (kind) {
  751. case PyUnicode_1BYTE_KIND:
  752. BLOOM_UPDATE(Py_UCS1, mask, ptr, len);
  753. break;
  754. case PyUnicode_2BYTE_KIND:
  755. BLOOM_UPDATE(Py_UCS2, mask, ptr, len);
  756. break;
  757. case PyUnicode_4BYTE_KIND:
  758. BLOOM_UPDATE(Py_UCS4, mask, ptr, len);
  759. break;
  760. default:
  761. Py_UNREACHABLE();
  762. }
  763. return mask;
  764. #undef BLOOM_UPDATE
  765. }
  766. static int
  767. ensure_unicode(PyObject *obj)
  768. {
  769. if (!PyUnicode_Check(obj)) {
  770. PyErr_Format(PyExc_TypeError,
  771. "must be str, not %.100s",
  772. Py_TYPE(obj)->tp_name);
  773. return -1;
  774. }
  775. return 0;
  776. }
  777. /* Compilation of templated routines */
  778. #define STRINGLIB_GET_EMPTY() unicode_get_empty()
  779. #include "stringlib/asciilib.h"
  780. #include "stringlib/fastsearch.h"
  781. #include "stringlib/partition.h"
  782. #include "stringlib/split.h"
  783. #include "stringlib/count.h"
  784. #include "stringlib/find.h"
  785. #include "stringlib/find_max_char.h"
  786. #include "stringlib/undef.h"
  787. #include "stringlib/ucs1lib.h"
  788. #include "stringlib/fastsearch.h"
  789. #include "stringlib/partition.h"
  790. #include "stringlib/split.h"
  791. #include "stringlib/count.h"
  792. #include "stringlib/find.h"
  793. #include "stringlib/replace.h"
  794. #include "stringlib/find_max_char.h"
  795. #include "stringlib/undef.h"
  796. #include "stringlib/ucs2lib.h"
  797. #include "stringlib/fastsearch.h"
  798. #include "stringlib/partition.h"
  799. #include "stringlib/split.h"
  800. #include "stringlib/count.h"
  801. #include "stringlib/find.h"
  802. #include "stringlib/replace.h"
  803. #include "stringlib/find_max_char.h"
  804. #include "stringlib/undef.h"
  805. #include "stringlib/ucs4lib.h"
  806. #include "stringlib/fastsearch.h"
  807. #include "stringlib/partition.h"
  808. #include "stringlib/split.h"
  809. #include "stringlib/count.h"
  810. #include "stringlib/find.h"
  811. #include "stringlib/replace.h"
  812. #include "stringlib/find_max_char.h"
  813. #include "stringlib/undef.h"
  814. #undef STRINGLIB_GET_EMPTY
  815. /* --- Unicode Object ----------------------------------------------------- */
  816. static inline Py_ssize_t
  817. findchar(const void *s, int kind,
  818. Py_ssize_t size, Py_UCS4 ch,
  819. int direction)
  820. {
  821. switch (kind) {
  822. case PyUnicode_1BYTE_KIND:
  823. if ((Py_UCS1) ch != ch)
  824. return -1;
  825. if (direction > 0)
  826. return ucs1lib_find_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
  827. else
  828. return ucs1lib_rfind_char((const Py_UCS1 *) s, size, (Py_UCS1) ch);
  829. case PyUnicode_2BYTE_KIND:
  830. if ((Py_UCS2) ch != ch)
  831. return -1;
  832. if (direction > 0)
  833. return ucs2lib_find_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
  834. else
  835. return ucs2lib_rfind_char((const Py_UCS2 *) s, size, (Py_UCS2) ch);
  836. case PyUnicode_4BYTE_KIND:
  837. if (direction > 0)
  838. return ucs4lib_find_char((const Py_UCS4 *) s, size, ch);
  839. else
  840. return ucs4lib_rfind_char((const Py_UCS4 *) s, size, ch);
  841. default:
  842. Py_UNREACHABLE();
  843. }
  844. }
  845. #ifdef Py_DEBUG
  846. /* Fill the data of a Unicode string with invalid characters to detect bugs
  847. earlier.
  848. _PyUnicode_CheckConsistency(str, 1) detects invalid characters, at least for
  849. ASCII and UCS-4 strings. U+00FF is invalid in ASCII and U+FFFFFFFF is an
  850. invalid character in Unicode 6.0. */
  851. static void
  852. unicode_fill_invalid(PyObject *unicode, Py_ssize_t old_length)
  853. {
  854. int kind = PyUnicode_KIND(unicode);
  855. Py_UCS1 *data = PyUnicode_1BYTE_DATA(unicode);
  856. Py_ssize_t length = _PyUnicode_LENGTH(unicode);
  857. if (length <= old_length)
  858. return;
  859. memset(data + old_length * kind, 0xff, (length - old_length) * kind);
  860. }
  861. #endif
  862. static PyObject*
  863. resize_compact(PyObject *unicode, Py_ssize_t length)
  864. {
  865. Py_ssize_t char_size;
  866. Py_ssize_t struct_size;
  867. Py_ssize_t new_size;
  868. PyObject *new_unicode;
  869. #ifdef Py_DEBUG
  870. Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
  871. #endif
  872. assert(unicode_modifiable(unicode));
  873. assert(PyUnicode_IS_COMPACT(unicode));
  874. char_size = PyUnicode_KIND(unicode);
  875. if (PyUnicode_IS_ASCII(unicode))
  876. struct_size = sizeof(PyASCIIObject);
  877. else
  878. struct_size = sizeof(PyCompactUnicodeObject);
  879. if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
  880. PyErr_NoMemory();
  881. return NULL;
  882. }
  883. new_size = (struct_size + (length + 1) * char_size);
  884. if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
  885. PyObject_Free(_PyUnicode_UTF8(unicode));
  886. _PyUnicode_UTF8(unicode) = NULL;
  887. _PyUnicode_UTF8_LENGTH(unicode) = 0;
  888. }
  889. #ifdef Py_TRACE_REFS
  890. _Py_ForgetReference(unicode);
  891. #endif
  892. new_unicode = (PyObject *)PyObject_Realloc(unicode, new_size);
  893. if (new_unicode == NULL) {
  894. _Py_NewReferenceNoTotal(unicode);
  895. PyErr_NoMemory();
  896. return NULL;
  897. }
  898. unicode = new_unicode;
  899. _Py_NewReferenceNoTotal(unicode);
  900. _PyUnicode_LENGTH(unicode) = length;
  901. #ifdef Py_DEBUG
  902. unicode_fill_invalid(unicode, old_length);
  903. #endif
  904. PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
  905. length, 0);
  906. assert(_PyUnicode_CheckConsistency(unicode, 0));
  907. return unicode;
  908. }
  909. static int
  910. resize_inplace(PyObject *unicode, Py_ssize_t length)
  911. {
  912. assert(!PyUnicode_IS_COMPACT(unicode));
  913. assert(Py_REFCNT(unicode) == 1);
  914. Py_ssize_t new_size;
  915. Py_ssize_t char_size;
  916. int share_utf8;
  917. void *data;
  918. #ifdef Py_DEBUG
  919. Py_ssize_t old_length = _PyUnicode_LENGTH(unicode);
  920. #endif
  921. data = _PyUnicode_DATA_ANY(unicode);
  922. char_size = PyUnicode_KIND(unicode);
  923. share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
  924. if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
  925. PyErr_NoMemory();
  926. return -1;
  927. }
  928. new_size = (length + 1) * char_size;
  929. if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
  930. {
  931. PyObject_Free(_PyUnicode_UTF8(unicode));
  932. _PyUnicode_UTF8(unicode) = NULL;
  933. _PyUnicode_UTF8_LENGTH(unicode) = 0;
  934. }
  935. data = (PyObject *)PyObject_Realloc(data, new_size);
  936. if (data == NULL) {
  937. PyErr_NoMemory();
  938. return -1;
  939. }
  940. _PyUnicode_DATA_ANY(unicode) = data;
  941. if (share_utf8) {
  942. _PyUnicode_UTF8(unicode) = data;
  943. _PyUnicode_UTF8_LENGTH(unicode) = length;
  944. }
  945. _PyUnicode_LENGTH(unicode) = length;
  946. PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
  947. #ifdef Py_DEBUG
  948. unicode_fill_invalid(unicode, old_length);
  949. #endif
  950. /* check for integer overflow */
  951. if (length > PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1) {
  952. PyErr_NoMemory();
  953. return -1;
  954. }
  955. assert(_PyUnicode_CheckConsistency(unicode, 0));
  956. return 0;
  957. }
  958. static PyObject*
  959. resize_copy(PyObject *unicode, Py_ssize_t length)
  960. {
  961. Py_ssize_t copy_length;
  962. PyObject *copy;
  963. copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
  964. if (copy == NULL)
  965. return NULL;
  966. copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
  967. _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, copy_length);
  968. return copy;
  969. }
  970. static const char*
  971. unicode_kind_name(PyObject *unicode)
  972. {
  973. /* don't check consistency: unicode_kind_name() is called from
  974. _PyUnicode_Dump() */
  975. if (!PyUnicode_IS_COMPACT(unicode))
  976. {
  977. switch (PyUnicode_KIND(unicode))
  978. {
  979. case PyUnicode_1BYTE_KIND:
  980. if (PyUnicode_IS_ASCII(unicode))
  981. return "legacy ascii";
  982. else
  983. return "legacy latin1";
  984. case PyUnicode_2BYTE_KIND:
  985. return "legacy UCS2";
  986. case PyUnicode_4BYTE_KIND:
  987. return "legacy UCS4";
  988. default:
  989. return "<legacy invalid kind>";
  990. }
  991. }
  992. switch (PyUnicode_KIND(unicode)) {
  993. case PyUnicode_1BYTE_KIND:
  994. if (PyUnicode_IS_ASCII(unicode))
  995. return "ascii";
  996. else
  997. return "latin1";
  998. case PyUnicode_2BYTE_KIND:
  999. return "UCS2";
  1000. case PyUnicode_4BYTE_KIND:
  1001. return "UCS4";
  1002. default:
  1003. return "<invalid compact kind>";
  1004. }
  1005. }
  1006. #ifdef Py_DEBUG
  1007. /* Functions wrapping macros for use in debugger */
  1008. const char *_PyUnicode_utf8(void *unicode_raw){
  1009. PyObject *unicode = _PyObject_CAST(unicode_raw);
  1010. return PyUnicode_UTF8(unicode);
  1011. }
  1012. const void *_PyUnicode_compact_data(void *unicode_raw) {
  1013. PyObject *unicode = _PyObject_CAST(unicode_raw);
  1014. return _PyUnicode_COMPACT_DATA(unicode);
  1015. }
  1016. const void *_PyUnicode_data(void *unicode_raw) {
  1017. PyObject *unicode = _PyObject_CAST(unicode_raw);
  1018. printf("obj %p\n", (void*)unicode);
  1019. printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
  1020. printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
  1021. printf("ascii op %p\n", (void*)(_PyASCIIObject_CAST(unicode) + 1));
  1022. printf("compact op %p\n", (void*)(_PyCompactUnicodeObject_CAST(unicode) + 1));
  1023. printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
  1024. return PyUnicode_DATA(unicode);
  1025. }
  1026. void
  1027. _PyUnicode_Dump(PyObject *op)
  1028. {
  1029. PyASCIIObject *ascii = _PyASCIIObject_CAST(op);
  1030. PyCompactUnicodeObject *compact = _PyCompactUnicodeObject_CAST(op);
  1031. PyUnicodeObject *unicode = _PyUnicodeObject_CAST(op);
  1032. const void *data;
  1033. if (ascii->state.compact)
  1034. {
  1035. if (ascii->state.ascii)
  1036. data = (ascii + 1);
  1037. else
  1038. data = (compact + 1);
  1039. }
  1040. else
  1041. data = unicode->data.any;
  1042. printf("%s: len=%zu, ", unicode_kind_name(op), ascii->length);
  1043. if (!ascii->state.ascii) {
  1044. printf("utf8=%p (%zu)", (void *)compact->utf8, compact->utf8_length);
  1045. }
  1046. printf(", data=%p\n", data);
  1047. }
  1048. #endif
  1049. PyObject *
  1050. PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
  1051. {
  1052. /* Optimization for empty strings */
  1053. if (size == 0) {
  1054. return unicode_new_empty();
  1055. }
  1056. PyObject *obj;
  1057. PyCompactUnicodeObject *unicode;
  1058. void *data;
  1059. int kind;
  1060. int is_ascii;
  1061. Py_ssize_t char_size;
  1062. Py_ssize_t struct_size;
  1063. is_ascii = 0;
  1064. struct_size = sizeof(PyCompactUnicodeObject);
  1065. if (maxchar < 128) {
  1066. kind = PyUnicode_1BYTE_KIND;
  1067. char_size = 1;
  1068. is_ascii = 1;
  1069. struct_size = sizeof(PyASCIIObject);
  1070. }
  1071. else if (maxchar < 256) {
  1072. kind = PyUnicode_1BYTE_KIND;
  1073. char_size = 1;
  1074. }
  1075. else if (maxchar < 65536) {
  1076. kind = PyUnicode_2BYTE_KIND;
  1077. char_size = 2;
  1078. }
  1079. else {
  1080. if (maxchar > MAX_UNICODE) {
  1081. PyErr_SetString(PyExc_SystemError,
  1082. "invalid maximum character passed to PyUnicode_New");
  1083. return NULL;
  1084. }
  1085. kind = PyUnicode_4BYTE_KIND;
  1086. char_size = 4;
  1087. }
  1088. /* Ensure we won't overflow the size. */
  1089. if (size < 0) {
  1090. PyErr_SetString(PyExc_SystemError,
  1091. "Negative size passed to PyUnicode_New");
  1092. return NULL;
  1093. }
  1094. if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
  1095. return PyErr_NoMemory();
  1096. /* Duplicated allocation code from _PyObject_New() instead of a call to
  1097. * PyObject_New() so we are able to allocate space for the object and
  1098. * it's data buffer.
  1099. */
  1100. obj = (PyObject *) PyObject_Malloc(struct_size + (size + 1) * char_size);
  1101. if (obj == NULL) {
  1102. return PyErr_NoMemory();
  1103. }
  1104. _PyObject_Init(obj, &PyUnicode_Type);
  1105. unicode = (PyCompactUnicodeObject *)obj;
  1106. if (is_ascii)
  1107. data = ((PyASCIIObject*)obj) + 1;
  1108. else
  1109. data = unicode + 1;
  1110. _PyUnicode_LENGTH(unicode) = size;
  1111. _PyUnicode_HASH(unicode) = -1;
  1112. _PyUnicode_STATE(unicode).interned = 0;
  1113. _PyUnicode_STATE(unicode).kind = kind;
  1114. _PyUnicode_STATE(unicode).compact = 1;
  1115. _PyUnicode_STATE(unicode).ascii = is_ascii;
  1116. _PyUnicode_STATE(unicode).statically_allocated = 0;
  1117. if (is_ascii) {
  1118. ((char*)data)[size] = 0;
  1119. }
  1120. else if (kind == PyUnicode_1BYTE_KIND) {
  1121. ((char*)data)[size] = 0;
  1122. unicode->utf8 = NULL;
  1123. unicode->utf8_length = 0;
  1124. }
  1125. else {
  1126. unicode->utf8 = NULL;
  1127. unicode->utf8_length = 0;
  1128. if (kind == PyUnicode_2BYTE_KIND)
  1129. ((Py_UCS2*)data)[size] = 0;
  1130. else /* kind == PyUnicode_4BYTE_KIND */
  1131. ((Py_UCS4*)data)[size] = 0;
  1132. }
  1133. #ifdef Py_DEBUG
  1134. unicode_fill_invalid((PyObject*)unicode, 0);
  1135. #endif
  1136. assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
  1137. return obj;
  1138. }
  1139. #if SIZEOF_WCHAR_T == 2
  1140. /* Helper function to convert a 16-bits wchar_t representation to UCS4, this
  1141. will decode surrogate pairs, the other conversions are implemented as macros
  1142. for efficiency.
  1143. This function assumes that unicode can hold one more code point than wstr
  1144. characters for a terminating null character. */
  1145. static void
  1146. unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
  1147. PyObject *unicode)
  1148. {
  1149. const wchar_t *iter;
  1150. Py_UCS4 *ucs4_out;
  1151. assert(unicode != NULL);
  1152. assert(_PyUnicode_CHECK(unicode));
  1153. assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
  1154. ucs4_out = PyUnicode_4BYTE_DATA(unicode);
  1155. for (iter = begin; iter < end; ) {
  1156. assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
  1157. _PyUnicode_GET_LENGTH(unicode)));
  1158. if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
  1159. && (iter+1) < end
  1160. && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
  1161. {
  1162. *ucs4_out++ = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
  1163. iter += 2;
  1164. }
  1165. else {
  1166. *ucs4_out++ = *iter;
  1167. iter++;
  1168. }
  1169. }
  1170. assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
  1171. _PyUnicode_GET_LENGTH(unicode)));
  1172. }
  1173. #endif
  1174. static int
  1175. unicode_check_modifiable(PyObject *unicode)
  1176. {
  1177. if (!unicode_modifiable(unicode)) {
  1178. PyErr_SetString(PyExc_SystemError,
  1179. "Cannot modify a string currently used");
  1180. return -1;
  1181. }
  1182. return 0;
  1183. }
  1184. static int
  1185. _copy_characters(PyObject *to, Py_ssize_t to_start,
  1186. PyObject *from, Py_ssize_t from_start,
  1187. Py_ssize_t how_many, int check_maxchar)
  1188. {
  1189. int from_kind, to_kind;
  1190. const void *from_data;
  1191. void *to_data;
  1192. assert(0 <= how_many);
  1193. assert(0 <= from_start);
  1194. assert(0 <= to_start);
  1195. assert(PyUnicode_Check(from));
  1196. assert(from_start + how_many <= PyUnicode_GET_LENGTH(from));
  1197. assert(PyUnicode_Check(to));
  1198. assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
  1199. if (how_many == 0)
  1200. return 0;
  1201. from_kind = PyUnicode_KIND(from);
  1202. from_data = PyUnicode_DATA(from);
  1203. to_kind = PyUnicode_KIND(to);
  1204. to_data = PyUnicode_DATA(to);
  1205. #ifdef Py_DEBUG
  1206. if (!check_maxchar
  1207. && PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to))
  1208. {
  1209. Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
  1210. Py_UCS4 ch;
  1211. Py_ssize_t i;
  1212. for (i=0; i < how_many; i++) {
  1213. ch = PyUnicode_READ(from_kind, from_data, from_start + i);
  1214. assert(ch <= to_maxchar);
  1215. }
  1216. }
  1217. #endif
  1218. if (from_kind == to_kind) {
  1219. if (check_maxchar
  1220. && !PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))
  1221. {
  1222. /* Writing Latin-1 characters into an ASCII string requires to
  1223. check that all written characters are pure ASCII */
  1224. Py_UCS4 max_char;
  1225. max_char = ucs1lib_find_max_char(from_data,
  1226. (const Py_UCS1*)from_data + how_many);
  1227. if (max_char >= 128)
  1228. return -1;
  1229. }
  1230. memcpy((char*)to_data + to_kind * to_start,
  1231. (const char*)from_data + from_kind * from_start,
  1232. to_kind * how_many);
  1233. }
  1234. else if (from_kind == PyUnicode_1BYTE_KIND
  1235. && to_kind == PyUnicode_2BYTE_KIND)
  1236. {
  1237. _PyUnicode_CONVERT_BYTES(
  1238. Py_UCS1, Py_UCS2,
  1239. PyUnicode_1BYTE_DATA(from) + from_start,
  1240. PyUnicode_1BYTE_DATA(from) + from_start + how_many,
  1241. PyUnicode_2BYTE_DATA(to) + to_start
  1242. );
  1243. }
  1244. else if (from_kind == PyUnicode_1BYTE_KIND
  1245. && to_kind == PyUnicode_4BYTE_KIND)
  1246. {
  1247. _PyUnicode_CONVERT_BYTES(
  1248. Py_UCS1, Py_UCS4,
  1249. PyUnicode_1BYTE_DATA(from) + from_start,
  1250. PyUnicode_1BYTE_DATA(from) + from_start + how_many,
  1251. PyUnicode_4BYTE_DATA(to) + to_start
  1252. );
  1253. }
  1254. else if (from_kind == PyUnicode_2BYTE_KIND
  1255. && to_kind == PyUnicode_4BYTE_KIND)
  1256. {
  1257. _PyUnicode_CONVERT_BYTES(
  1258. Py_UCS2, Py_UCS4,
  1259. PyUnicode_2BYTE_DATA(from) + from_start,
  1260. PyUnicode_2BYTE_DATA(from) + from_start + how_many,
  1261. PyUnicode_4BYTE_DATA(to) + to_start
  1262. );
  1263. }
  1264. else {
  1265. assert (PyUnicode_MAX_CHAR_VALUE(from) > PyUnicode_MAX_CHAR_VALUE(to));
  1266. if (!check_maxchar) {
  1267. if (from_kind == PyUnicode_2BYTE_KIND
  1268. && to_kind == PyUnicode_1BYTE_KIND)
  1269. {
  1270. _PyUnicode_CONVERT_BYTES(
  1271. Py_UCS2, Py_UCS1,
  1272. PyUnicode_2BYTE_DATA(from) + from_start,
  1273. PyUnicode_2BYTE_DATA(from) + from_start + how_many,
  1274. PyUnicode_1BYTE_DATA(to) + to_start
  1275. );
  1276. }
  1277. else if (from_kind == PyUnicode_4BYTE_KIND
  1278. && to_kind == PyUnicode_1BYTE_KIND)
  1279. {
  1280. _PyUnicode_CONVERT_BYTES(
  1281. Py_UCS4, Py_UCS1,
  1282. PyUnicode_4BYTE_DATA(from) + from_start,
  1283. PyUnicode_4BYTE_DATA(from) + from_start + how_many,
  1284. PyUnicode_1BYTE_DATA(to) + to_start
  1285. );
  1286. }
  1287. else if (from_kind == PyUnicode_4BYTE_KIND
  1288. && to_kind == PyUnicode_2BYTE_KIND)
  1289. {
  1290. _PyUnicode_CONVERT_BYTES(
  1291. Py_UCS4, Py_UCS2,
  1292. PyUnicode_4BYTE_DATA(from) + from_start,
  1293. PyUnicode_4BYTE_DATA(from) + from_start + how_many,
  1294. PyUnicode_2BYTE_DATA(to) + to_start
  1295. );
  1296. }
  1297. else {
  1298. Py_UNREACHABLE();
  1299. }
  1300. }
  1301. else {
  1302. const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
  1303. Py_UCS4 ch;
  1304. Py_ssize_t i;
  1305. for (i=0; i < how_many; i++) {
  1306. ch = PyUnicode_READ(from_kind, from_data, from_start + i);
  1307. if (ch > to_maxchar)
  1308. return -1;
  1309. PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
  1310. }
  1311. }
  1312. }
  1313. return 0;
  1314. }
  1315. void
  1316. _PyUnicode_FastCopyCharacters(
  1317. PyObject *to, Py_ssize_t to_start,
  1318. PyObject *from, Py_ssize_t from_start, Py_ssize_t how_many)
  1319. {
  1320. (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
  1321. }
  1322. Py_ssize_t
  1323. PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
  1324. PyObject *from, Py_ssize_t from_start,
  1325. Py_ssize_t how_many)
  1326. {
  1327. int err;
  1328. if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
  1329. PyErr_BadInternalCall();
  1330. return -1;
  1331. }
  1332. if ((size_t)from_start > (size_t)PyUnicode_GET_LENGTH(from)) {
  1333. PyErr_SetString(PyExc_IndexError, "string index out of range");
  1334. return -1;
  1335. }
  1336. if ((size_t)to_start > (size_t)PyUnicode_GET_LENGTH(to)) {
  1337. PyErr_SetString(PyExc_IndexError, "string index out of range");
  1338. return -1;
  1339. }
  1340. if (how_many < 0) {
  1341. PyErr_SetString(PyExc_SystemError, "how_many cannot be negative");
  1342. return -1;
  1343. }
  1344. how_many = Py_MIN(PyUnicode_GET_LENGTH(from)-from_start, how_many);
  1345. if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
  1346. PyErr_Format(PyExc_SystemError,
  1347. "Cannot write %zi characters at %zi "
  1348. "in a string of %zi characters",
  1349. how_many, to_start, PyUnicode_GET_LENGTH(to));
  1350. return -1;
  1351. }
  1352. if (how_many == 0)
  1353. return 0;
  1354. if (unicode_check_modifiable(to))
  1355. return -1;
  1356. err = _copy_characters(to, to_start, from, from_start, how_many, 1);
  1357. if (err) {
  1358. PyErr_Format(PyExc_SystemError,
  1359. "Cannot copy %s characters "
  1360. "into a string of %s characters",
  1361. unicode_kind_name(from),
  1362. unicode_kind_name(to));
  1363. return -1;
  1364. }
  1365. return how_many;
  1366. }
  1367. /* Find the maximum code point and count the number of surrogate pairs so a
  1368. correct string length can be computed before converting a string to UCS4.
  1369. This function counts single surrogates as a character and not as a pair.
  1370. Return 0 on success, or -1 on error. */
  1371. static int
  1372. find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
  1373. Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
  1374. {
  1375. const wchar_t *iter;
  1376. Py_UCS4 ch;
  1377. assert(num_surrogates != NULL && maxchar != NULL);
  1378. *num_surrogates = 0;
  1379. *maxchar = 0;
  1380. for (iter = begin; iter < end; ) {
  1381. #if SIZEOF_WCHAR_T == 2
  1382. if (Py_UNICODE_IS_HIGH_SURROGATE(iter[0])
  1383. && (iter+1) < end
  1384. && Py_UNICODE_IS_LOW_SURROGATE(iter[1]))
  1385. {
  1386. ch = Py_UNICODE_JOIN_SURROGATES(iter[0], iter[1]);
  1387. ++(*num_surrogates);
  1388. iter += 2;
  1389. }
  1390. else
  1391. #endif
  1392. {
  1393. ch = *iter;
  1394. iter++;
  1395. }
  1396. if (ch > *maxchar) {
  1397. *maxchar = ch;
  1398. if (*maxchar > MAX_UNICODE) {
  1399. PyErr_Format(PyExc_ValueError,
  1400. "character U+%x is not in range [U+0000; U+%x]",
  1401. ch, MAX_UNICODE);
  1402. return -1;
  1403. }
  1404. }
  1405. }
  1406. return 0;
  1407. }
  1408. static void
  1409. unicode_dealloc(PyObject *unicode)
  1410. {
  1411. #ifdef Py_DEBUG
  1412. if (!unicode_is_finalizing() && unicode_is_singleton(unicode)) {
  1413. _Py_FatalRefcountError("deallocating an Unicode singleton");
  1414. }
  1415. #endif
  1416. /* This should never get called, but we also don't want to SEGV if
  1417. * we accidentally decref an immortal string out of existence. Since
  1418. * the string is an immortal object, just re-set the reference count.
  1419. */
  1420. if (PyUnicode_CHECK_INTERNED(unicode)
  1421. || _PyUnicode_STATE(unicode).statically_allocated)
  1422. {
  1423. _Py_SetImmortal(unicode);
  1424. return;
  1425. }
  1426. if (_PyUnicode_HAS_UTF8_MEMORY(unicode)) {
  1427. PyObject_Free(_PyUnicode_UTF8(unicode));
  1428. }
  1429. if (!PyUnicode_IS_COMPACT(unicode) && _PyUnicode_DATA_ANY(unicode)) {
  1430. PyObject_Free(_PyUnicode_DATA_ANY(unicode));
  1431. }
  1432. Py_TYPE(unicode)->tp_free(unicode);
  1433. }
  1434. #ifdef Py_DEBUG
  1435. static int
  1436. unicode_is_singleton(PyObject *unicode)
  1437. {
  1438. if (unicode == &_Py_STR(empty)) {
  1439. return 1;
  1440. }
  1441. PyASCIIObject *ascii = _PyASCIIObject_CAST(unicode);
  1442. if (ascii->length == 1) {
  1443. Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
  1444. if (ch < 256 && LATIN1(ch) == unicode) {
  1445. return 1;
  1446. }
  1447. }
  1448. return 0;
  1449. }
  1450. #endif
  1451. static int
  1452. unicode_modifiable(PyObject *unicode)
  1453. {
  1454. assert(_PyUnicode_CHECK(unicode));
  1455. if (Py_REFCNT(unicode) != 1)
  1456. return 0;
  1457. if (_PyUnicode_HASH(unicode) != -1)
  1458. return 0;
  1459. if (PyUnicode_CHECK_INTERNED(unicode))
  1460. return 0;
  1461. if (!PyUnicode_CheckExact(unicode))
  1462. return 0;
  1463. #ifdef Py_DEBUG
  1464. /* singleton refcount is greater than 1 */
  1465. assert(!unicode_is_singleton(unicode));
  1466. #endif
  1467. return 1;
  1468. }
  1469. static int
  1470. unicode_resize(PyObject **p_unicode, Py_ssize_t length)
  1471. {
  1472. PyObject *unicode;
  1473. Py_ssize_t old_length;
  1474. assert(p_unicode != NULL);
  1475. unicode = *p_unicode;
  1476. assert(unicode != NULL);
  1477. assert(PyUnicode_Check(unicode));
  1478. assert(0 <= length);
  1479. old_length = PyUnicode_GET_LENGTH(unicode);
  1480. if (old_length == length)
  1481. return 0;
  1482. if (length == 0) {
  1483. PyObject *empty = unicode_new_empty();
  1484. Py_SETREF(*p_unicode, empty);
  1485. return 0;
  1486. }
  1487. if (!unicode_modifiable(unicode)) {
  1488. PyObject *copy = resize_copy(unicode, length);
  1489. if (copy == NULL)
  1490. return -1;
  1491. Py_SETREF(*p_unicode, copy);
  1492. return 0;
  1493. }
  1494. if (PyUnicode_IS_COMPACT(unicode)) {
  1495. PyObject *new_unicode = resize_compact(unicode, length);
  1496. if (new_unicode == NULL)
  1497. return -1;
  1498. *p_unicode = new_unicode;
  1499. return 0;
  1500. }
  1501. return resize_inplace(unicode, length);
  1502. }
  1503. int
  1504. PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
  1505. {
  1506. PyObject *unicode;
  1507. if (p_unicode == NULL) {
  1508. PyErr_BadInternalCall();
  1509. return -1;
  1510. }
  1511. unicode = *p_unicode;
  1512. if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
  1513. {
  1514. PyErr_BadInternalCall();
  1515. return -1;
  1516. }
  1517. return unicode_resize(p_unicode, length);
  1518. }
  1519. /* Copy an ASCII or latin1 char* string into a Python Unicode string.
  1520. WARNING: The function doesn't copy the terminating null character and
  1521. doesn't check the maximum character (may write a latin1 character in an
  1522. ASCII string). */
  1523. static void
  1524. unicode_write_cstr(PyObject *unicode, Py_ssize_t index,
  1525. const char *str, Py_ssize_t len)
  1526. {
  1527. int kind = PyUnicode_KIND(unicode);
  1528. const void *data = PyUnicode_DATA(unicode);
  1529. const char *end = str + len;
  1530. assert(index + len <= PyUnicode_GET_LENGTH(unicode));
  1531. switch (kind) {
  1532. case PyUnicode_1BYTE_KIND: {
  1533. #ifdef Py_DEBUG
  1534. if (PyUnicode_IS_ASCII(unicode)) {
  1535. Py_UCS4 maxchar = ucs1lib_find_max_char(
  1536. (const Py_UCS1*)str,
  1537. (const Py_UCS1*)str + len);
  1538. assert(maxchar < 128);
  1539. }
  1540. #endif
  1541. memcpy((char *) data + index, str, len);
  1542. break;
  1543. }
  1544. case PyUnicode_2BYTE_KIND: {
  1545. Py_UCS2 *start = (Py_UCS2 *)data + index;
  1546. Py_UCS2 *ucs2 = start;
  1547. for (; str < end; ++ucs2, ++str)
  1548. *ucs2 = (Py_UCS2)*str;
  1549. assert((ucs2 - start) <= PyUnicode_GET_LENGTH(unicode));
  1550. break;
  1551. }
  1552. case PyUnicode_4BYTE_KIND: {
  1553. Py_UCS4 *start = (Py_UCS4 *)data + index;
  1554. Py_UCS4 *ucs4 = start;
  1555. for (; str < end; ++ucs4, ++str)
  1556. *ucs4 = (Py_UCS4)*str;
  1557. assert((ucs4 - start) <= PyUnicode_GET_LENGTH(unicode));
  1558. break;
  1559. }
  1560. default:
  1561. Py_UNREACHABLE();
  1562. }
  1563. }
  1564. static PyObject*
  1565. get_latin1_char(Py_UCS1 ch)
  1566. {
  1567. return Py_NewRef(LATIN1(ch));
  1568. }
  1569. static PyObject*
  1570. unicode_char(Py_UCS4 ch)
  1571. {
  1572. PyObject *unicode;
  1573. assert(ch <= MAX_UNICODE);
  1574. if (ch < 256) {
  1575. return get_latin1_char(ch);
  1576. }
  1577. unicode = PyUnicode_New(1, ch);
  1578. if (unicode == NULL)
  1579. return NULL;
  1580. assert(PyUnicode_KIND(unicode) != PyUnicode_1BYTE_KIND);
  1581. if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
  1582. PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;
  1583. } else {
  1584. assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
  1585. PyUnicode_4BYTE_DATA(unicode)[0] = ch;
  1586. }
  1587. assert(_PyUnicode_CheckConsistency(unicode, 1));
  1588. return unicode;
  1589. }
  1590. PyObject *
  1591. PyUnicode_FromWideChar(const wchar_t *u, Py_ssize_t size)
  1592. {
  1593. PyObject *unicode;
  1594. Py_UCS4 maxchar = 0;
  1595. Py_ssize_t num_surrogates;
  1596. if (u == NULL && size != 0) {
  1597. PyErr_BadInternalCall();
  1598. return NULL;
  1599. }
  1600. if (size == -1) {
  1601. size = wcslen(u);
  1602. }
  1603. /* If the Unicode data is known at construction time, we can apply
  1604. some optimizations which share commonly used objects. */
  1605. /* Optimization for empty strings */
  1606. if (size == 0)
  1607. _Py_RETURN_UNICODE_EMPTY();
  1608. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  1609. /* Oracle Solaris uses non-Unicode internal wchar_t form for
  1610. non-Unicode locales and hence needs conversion to UCS-4 first. */
  1611. if (_Py_LocaleUsesNonUnicodeWchar()) {
  1612. wchar_t* converted = _Py_DecodeNonUnicodeWchar(u, size);
  1613. if (!converted) {
  1614. return NULL;
  1615. }
  1616. PyObject *unicode = _PyUnicode_FromUCS4(converted, size);
  1617. PyMem_Free(converted);
  1618. return unicode;
  1619. }
  1620. #endif
  1621. /* Single character Unicode objects in the Latin-1 range are
  1622. shared when using this constructor */
  1623. if (size == 1 && (Py_UCS4)*u < 256)
  1624. return get_latin1_char((unsigned char)*u);
  1625. /* If not empty and not single character, copy the Unicode data
  1626. into the new object */
  1627. if (find_maxchar_surrogates(u, u + size,
  1628. &maxchar, &num_surrogates) == -1)
  1629. return NULL;
  1630. unicode = PyUnicode_New(size - num_surrogates, maxchar);
  1631. if (!unicode)
  1632. return NULL;
  1633. switch (PyUnicode_KIND(unicode)) {
  1634. case PyUnicode_1BYTE_KIND:
  1635. _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
  1636. u, u + size, PyUnicode_1BYTE_DATA(unicode));
  1637. break;
  1638. case PyUnicode_2BYTE_KIND:
  1639. #if Py_UNICODE_SIZE == 2
  1640. memcpy(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
  1641. #else
  1642. _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
  1643. u, u + size, PyUnicode_2BYTE_DATA(unicode));
  1644. #endif
  1645. break;
  1646. case PyUnicode_4BYTE_KIND:
  1647. #if SIZEOF_WCHAR_T == 2
  1648. /* This is the only case which has to process surrogates, thus
  1649. a simple copy loop is not enough and we need a function. */
  1650. unicode_convert_wchar_to_ucs4(u, u + size, unicode);
  1651. #else
  1652. assert(num_surrogates == 0);
  1653. memcpy(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
  1654. #endif
  1655. break;
  1656. default:
  1657. Py_UNREACHABLE();
  1658. }
  1659. return unicode_result(unicode);
  1660. }
  1661. PyObject *
  1662. PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
  1663. {
  1664. if (size < 0) {
  1665. PyErr_SetString(PyExc_SystemError,
  1666. "Negative size passed to PyUnicode_FromStringAndSize");
  1667. return NULL;
  1668. }
  1669. if (u != NULL) {
  1670. return PyUnicode_DecodeUTF8Stateful(u, size, NULL, NULL);
  1671. }
  1672. if (size > 0) {
  1673. PyErr_SetString(PyExc_SystemError,
  1674. "NULL string with positive size with NULL passed to PyUnicode_FromStringAndSize");
  1675. return NULL;
  1676. }
  1677. return unicode_new_empty();
  1678. }
  1679. PyObject *
  1680. PyUnicode_FromString(const char *u)
  1681. {
  1682. #if defined(__has_feature)
  1683. # if __has_feature(memory_sanitizer)
  1684. __msan_unpoison_string(u);
  1685. # endif
  1686. #endif
  1687. size_t size = strlen(u);
  1688. if (size > PY_SSIZE_T_MAX) {
  1689. PyErr_SetString(PyExc_OverflowError, "input too long");
  1690. return NULL;
  1691. }
  1692. return PyUnicode_DecodeUTF8Stateful(u, (Py_ssize_t)size, NULL, NULL);
  1693. }
  1694. PyObject *
  1695. _PyUnicode_FromId(_Py_Identifier *id)
  1696. {
  1697. PyInterpreterState *interp = _PyInterpreterState_GET();
  1698. struct _Py_unicode_ids *ids = &interp->unicode.ids;
  1699. Py_ssize_t index = _Py_atomic_size_get(&id->index);
  1700. if (index < 0) {
  1701. struct _Py_unicode_runtime_ids *rt_ids = &interp->runtime->unicode_state.ids;
  1702. PyThread_acquire_lock(rt_ids->lock, WAIT_LOCK);
  1703. // Check again to detect concurrent access. Another thread can have
  1704. // initialized the index while this thread waited for the lock.
  1705. index = _Py_atomic_size_get(&id->index);
  1706. if (index < 0) {
  1707. assert(rt_ids->next_index < PY_SSIZE_T_MAX);
  1708. index = rt_ids->next_index;
  1709. rt_ids->next_index++;
  1710. _Py_atomic_size_set(&id->index, index);
  1711. }
  1712. PyThread_release_lock(rt_ids->lock);
  1713. }
  1714. assert(index >= 0);
  1715. PyObject *obj;
  1716. if (index < ids->size) {
  1717. obj = ids->array[index];
  1718. if (obj) {
  1719. // Return a borrowed reference
  1720. return obj;
  1721. }
  1722. }
  1723. obj = PyUnicode_DecodeUTF8Stateful(id->string, strlen(id->string),
  1724. NULL, NULL);
  1725. if (!obj) {
  1726. return NULL;
  1727. }
  1728. PyUnicode_InternInPlace(&obj);
  1729. if (index >= ids->size) {
  1730. // Overallocate to reduce the number of realloc
  1731. Py_ssize_t new_size = Py_MAX(index * 2, 16);
  1732. Py_ssize_t item_size = sizeof(ids->array[0]);
  1733. PyObject **new_array = PyMem_Realloc(ids->array, new_size * item_size);
  1734. if (new_array == NULL) {
  1735. PyErr_NoMemory();
  1736. return NULL;
  1737. }
  1738. memset(&new_array[ids->size], 0, (new_size - ids->size) * item_size);
  1739. ids->array = new_array;
  1740. ids->size = new_size;
  1741. }
  1742. // The array stores a strong reference
  1743. ids->array[index] = obj;
  1744. // Return a borrowed reference
  1745. return obj;
  1746. }
  1747. static void
  1748. unicode_clear_identifiers(struct _Py_unicode_state *state)
  1749. {
  1750. struct _Py_unicode_ids *ids = &state->ids;
  1751. for (Py_ssize_t i=0; i < ids->size; i++) {
  1752. Py_XDECREF(ids->array[i]);
  1753. }
  1754. ids->size = 0;
  1755. PyMem_Free(ids->array);
  1756. ids->array = NULL;
  1757. // Don't reset _PyRuntime next_index: _Py_Identifier.id remains valid
  1758. // after Py_Finalize().
  1759. }
  1760. /* Internal function, doesn't check maximum character */
  1761. PyObject*
  1762. _PyUnicode_FromASCII(const char *buffer, Py_ssize_t size)
  1763. {
  1764. const unsigned char *s = (const unsigned char *)buffer;
  1765. PyObject *unicode;
  1766. if (size == 1) {
  1767. #ifdef Py_DEBUG
  1768. assert((unsigned char)s[0] < 128);
  1769. #endif
  1770. return get_latin1_char(s[0]);
  1771. }
  1772. unicode = PyUnicode_New(size, 127);
  1773. if (!unicode)
  1774. return NULL;
  1775. memcpy(PyUnicode_1BYTE_DATA(unicode), s, size);
  1776. assert(_PyUnicode_CheckConsistency(unicode, 1));
  1777. return unicode;
  1778. }
  1779. static Py_UCS4
  1780. kind_maxchar_limit(int kind)
  1781. {
  1782. switch (kind) {
  1783. case PyUnicode_1BYTE_KIND:
  1784. return 0x80;
  1785. case PyUnicode_2BYTE_KIND:
  1786. return 0x100;
  1787. case PyUnicode_4BYTE_KIND:
  1788. return 0x10000;
  1789. default:
  1790. Py_UNREACHABLE();
  1791. }
  1792. }
  1793. static PyObject*
  1794. _PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size)
  1795. {
  1796. PyObject *res;
  1797. unsigned char max_char;
  1798. if (size == 0) {
  1799. _Py_RETURN_UNICODE_EMPTY();
  1800. }
  1801. assert(size > 0);
  1802. if (size == 1) {
  1803. return get_latin1_char(u[0]);
  1804. }
  1805. max_char = ucs1lib_find_max_char(u, u + size);
  1806. res = PyUnicode_New(size, max_char);
  1807. if (!res)
  1808. return NULL;
  1809. memcpy(PyUnicode_1BYTE_DATA(res), u, size);
  1810. assert(_PyUnicode_CheckConsistency(res, 1));
  1811. return res;
  1812. }
  1813. static PyObject*
  1814. _PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
  1815. {
  1816. PyObject *res;
  1817. Py_UCS2 max_char;
  1818. if (size == 0)
  1819. _Py_RETURN_UNICODE_EMPTY();
  1820. assert(size > 0);
  1821. if (size == 1)
  1822. return unicode_char(u[0]);
  1823. max_char = ucs2lib_find_max_char(u, u + size);
  1824. res = PyUnicode_New(size, max_char);
  1825. if (!res)
  1826. return NULL;
  1827. if (max_char >= 256)
  1828. memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
  1829. else {
  1830. _PyUnicode_CONVERT_BYTES(
  1831. Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
  1832. }
  1833. assert(_PyUnicode_CheckConsistency(res, 1));
  1834. return res;
  1835. }
  1836. static PyObject*
  1837. _PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
  1838. {
  1839. PyObject *res;
  1840. Py_UCS4 max_char;
  1841. if (size == 0)
  1842. _Py_RETURN_UNICODE_EMPTY();
  1843. assert(size > 0);
  1844. if (size == 1)
  1845. return unicode_char(u[0]);
  1846. max_char = ucs4lib_find_max_char(u, u + size);
  1847. res = PyUnicode_New(size, max_char);
  1848. if (!res)
  1849. return NULL;
  1850. if (max_char < 256)
  1851. _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
  1852. PyUnicode_1BYTE_DATA(res));
  1853. else if (max_char < 0x10000)
  1854. _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
  1855. PyUnicode_2BYTE_DATA(res));
  1856. else
  1857. memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
  1858. assert(_PyUnicode_CheckConsistency(res, 1));
  1859. return res;
  1860. }
  1861. PyObject*
  1862. PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
  1863. {
  1864. if (size < 0) {
  1865. PyErr_SetString(PyExc_ValueError, "size must be positive");
  1866. return NULL;
  1867. }
  1868. switch (kind) {
  1869. case PyUnicode_1BYTE_KIND:
  1870. return _PyUnicode_FromUCS1(buffer, size);
  1871. case PyUnicode_2BYTE_KIND:
  1872. return _PyUnicode_FromUCS2(buffer, size);
  1873. case PyUnicode_4BYTE_KIND:
  1874. return _PyUnicode_FromUCS4(buffer, size);
  1875. default:
  1876. PyErr_SetString(PyExc_SystemError, "invalid kind");
  1877. return NULL;
  1878. }
  1879. }
  1880. Py_UCS4
  1881. _PyUnicode_FindMaxChar(PyObject *unicode, Py_ssize_t start, Py_ssize_t end)
  1882. {
  1883. int kind;
  1884. const void *startptr, *endptr;
  1885. assert(0 <= start);
  1886. assert(end <= PyUnicode_GET_LENGTH(unicode));
  1887. assert(start <= end);
  1888. if (start == 0 && end == PyUnicode_GET_LENGTH(unicode))
  1889. return PyUnicode_MAX_CHAR_VALUE(unicode);
  1890. if (start == end)
  1891. return 127;
  1892. if (PyUnicode_IS_ASCII(unicode))
  1893. return 127;
  1894. kind = PyUnicode_KIND(unicode);
  1895. startptr = PyUnicode_DATA(unicode);
  1896. endptr = (char *)startptr + end * kind;
  1897. startptr = (char *)startptr + start * kind;
  1898. switch(kind) {
  1899. case PyUnicode_1BYTE_KIND:
  1900. return ucs1lib_find_max_char(startptr, endptr);
  1901. case PyUnicode_2BYTE_KIND:
  1902. return ucs2lib_find_max_char(startptr, endptr);
  1903. case PyUnicode_4BYTE_KIND:
  1904. return ucs4lib_find_max_char(startptr, endptr);
  1905. default:
  1906. Py_UNREACHABLE();
  1907. }
  1908. }
  1909. /* Ensure that a string uses the most efficient storage, if it is not the
  1910. case: create a new string with of the right kind. Write NULL into *p_unicode
  1911. on error. */
  1912. static void
  1913. unicode_adjust_maxchar(PyObject **p_unicode)
  1914. {
  1915. PyObject *unicode, *copy;
  1916. Py_UCS4 max_char;
  1917. Py_ssize_t len;
  1918. int kind;
  1919. assert(p_unicode != NULL);
  1920. unicode = *p_unicode;
  1921. if (PyUnicode_IS_ASCII(unicode))
  1922. return;
  1923. len = PyUnicode_GET_LENGTH(unicode);
  1924. kind = PyUnicode_KIND(unicode);
  1925. if (kind == PyUnicode_1BYTE_KIND) {
  1926. const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
  1927. max_char = ucs1lib_find_max_char(u, u + len);
  1928. if (max_char >= 128)
  1929. return;
  1930. }
  1931. else if (kind == PyUnicode_2BYTE_KIND) {
  1932. const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
  1933. max_char = ucs2lib_find_max_char(u, u + len);
  1934. if (max_char >= 256)
  1935. return;
  1936. }
  1937. else if (kind == PyUnicode_4BYTE_KIND) {
  1938. const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
  1939. max_char = ucs4lib_find_max_char(u, u + len);
  1940. if (max_char >= 0x10000)
  1941. return;
  1942. }
  1943. else
  1944. Py_UNREACHABLE();
  1945. copy = PyUnicode_New(len, max_char);
  1946. if (copy != NULL)
  1947. _PyUnicode_FastCopyCharacters(copy, 0, unicode, 0, len);
  1948. Py_DECREF(unicode);
  1949. *p_unicode = copy;
  1950. }
  1951. PyObject*
  1952. _PyUnicode_Copy(PyObject *unicode)
  1953. {
  1954. Py_ssize_t length;
  1955. PyObject *copy;
  1956. if (!PyUnicode_Check(unicode)) {
  1957. PyErr_BadInternalCall();
  1958. return NULL;
  1959. }
  1960. length = PyUnicode_GET_LENGTH(unicode);
  1961. copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
  1962. if (!copy)
  1963. return NULL;
  1964. assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
  1965. memcpy(PyUnicode_DATA(copy), PyUnicode_DATA(unicode),
  1966. length * PyUnicode_KIND(unicode));
  1967. assert(_PyUnicode_CheckConsistency(copy, 1));
  1968. return copy;
  1969. }
  1970. /* Widen Unicode objects to larger buffers. Don't write terminating null
  1971. character. Return NULL on error. */
  1972. static void*
  1973. unicode_askind(int skind, void const *data, Py_ssize_t len, int kind)
  1974. {
  1975. void *result;
  1976. assert(skind < kind);
  1977. switch (kind) {
  1978. case PyUnicode_2BYTE_KIND:
  1979. result = PyMem_New(Py_UCS2, len);
  1980. if (!result)
  1981. return PyErr_NoMemory();
  1982. assert(skind == PyUnicode_1BYTE_KIND);
  1983. _PyUnicode_CONVERT_BYTES(
  1984. Py_UCS1, Py_UCS2,
  1985. (const Py_UCS1 *)data,
  1986. ((const Py_UCS1 *)data) + len,
  1987. result);
  1988. return result;
  1989. case PyUnicode_4BYTE_KIND:
  1990. result = PyMem_New(Py_UCS4, len);
  1991. if (!result)
  1992. return PyErr_NoMemory();
  1993. if (skind == PyUnicode_2BYTE_KIND) {
  1994. _PyUnicode_CONVERT_BYTES(
  1995. Py_UCS2, Py_UCS4,
  1996. (const Py_UCS2 *)data,
  1997. ((const Py_UCS2 *)data) + len,
  1998. result);
  1999. }
  2000. else {
  2001. assert(skind == PyUnicode_1BYTE_KIND);
  2002. _PyUnicode_CONVERT_BYTES(
  2003. Py_UCS1, Py_UCS4,
  2004. (const Py_UCS1 *)data,
  2005. ((const Py_UCS1 *)data) + len,
  2006. result);
  2007. }
  2008. return result;
  2009. default:
  2010. Py_UNREACHABLE();
  2011. return NULL;
  2012. }
  2013. }
  2014. static Py_UCS4*
  2015. as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
  2016. int copy_null)
  2017. {
  2018. int kind;
  2019. const void *data;
  2020. Py_ssize_t len, targetlen;
  2021. kind = PyUnicode_KIND(string);
  2022. data = PyUnicode_DATA(string);
  2023. len = PyUnicode_GET_LENGTH(string);
  2024. targetlen = len;
  2025. if (copy_null)
  2026. targetlen++;
  2027. if (!target) {
  2028. target = PyMem_New(Py_UCS4, targetlen);
  2029. if (!target) {
  2030. PyErr_NoMemory();
  2031. return NULL;
  2032. }
  2033. }
  2034. else {
  2035. if (targetsize < targetlen) {
  2036. PyErr_Format(PyExc_SystemError,
  2037. "string is longer than the buffer");
  2038. if (copy_null && 0 < targetsize)
  2039. target[0] = 0;
  2040. return NULL;
  2041. }
  2042. }
  2043. if (kind == PyUnicode_1BYTE_KIND) {
  2044. const Py_UCS1 *start = (const Py_UCS1 *) data;
  2045. _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
  2046. }
  2047. else if (kind == PyUnicode_2BYTE_KIND) {
  2048. const Py_UCS2 *start = (const Py_UCS2 *) data;
  2049. _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
  2050. }
  2051. else if (kind == PyUnicode_4BYTE_KIND) {
  2052. memcpy(target, data, len * sizeof(Py_UCS4));
  2053. }
  2054. else {
  2055. Py_UNREACHABLE();
  2056. }
  2057. if (copy_null)
  2058. target[len] = 0;
  2059. return target;
  2060. }
  2061. Py_UCS4*
  2062. PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
  2063. int copy_null)
  2064. {
  2065. if (target == NULL || targetsize < 0) {
  2066. PyErr_BadInternalCall();
  2067. return NULL;
  2068. }
  2069. return as_ucs4(string, target, targetsize, copy_null);
  2070. }
  2071. Py_UCS4*
  2072. PyUnicode_AsUCS4Copy(PyObject *string)
  2073. {
  2074. return as_ucs4(string, NULL, 0, 1);
  2075. }
  2076. /* maximum number of characters required for output of %jo or %jd or %p.
  2077. We need at most ceil(log8(256)*sizeof(intmax_t)) digits,
  2078. plus 1 for the sign, plus 2 for the 0x prefix (for %p),
  2079. plus 1 for the terminal NUL. */
  2080. #define MAX_INTMAX_CHARS (5 + (sizeof(intmax_t)*8-1) / 3)
  2081. static int
  2082. unicode_fromformat_write_str(_PyUnicodeWriter *writer, PyObject *str,
  2083. Py_ssize_t width, Py_ssize_t precision, int flags)
  2084. {
  2085. Py_ssize_t length, fill, arglen;
  2086. Py_UCS4 maxchar;
  2087. length = PyUnicode_GET_LENGTH(str);
  2088. if ((precision == -1 || precision >= length)
  2089. && width <= length)
  2090. return _PyUnicodeWriter_WriteStr(writer, str);
  2091. if (precision != -1)
  2092. length = Py_MIN(precision, length);
  2093. arglen = Py_MAX(length, width);
  2094. if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
  2095. maxchar = _PyUnicode_FindMaxChar(str, 0, length);
  2096. else
  2097. maxchar = writer->maxchar;
  2098. if (_PyUnicodeWriter_Prepare(writer, arglen, maxchar) == -1)
  2099. return -1;
  2100. fill = Py_MAX(width - length, 0);
  2101. if (fill && !(flags & F_LJUST)) {
  2102. if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
  2103. return -1;
  2104. writer->pos += fill;
  2105. }
  2106. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  2107. str, 0, length);
  2108. writer->pos += length;
  2109. if (fill && (flags & F_LJUST)) {
  2110. if (PyUnicode_Fill(writer->buffer, writer->pos, fill, ' ') == -1)
  2111. return -1;
  2112. writer->pos += fill;
  2113. }
  2114. return 0;
  2115. }
  2116. static int
  2117. unicode_fromformat_write_cstr(_PyUnicodeWriter *writer, const char *str,
  2118. Py_ssize_t width, Py_ssize_t precision, int flags)
  2119. {
  2120. /* UTF-8 */
  2121. Py_ssize_t length;
  2122. PyObject *unicode;
  2123. int res;
  2124. if (precision == -1) {
  2125. length = strlen(str);
  2126. }
  2127. else {
  2128. length = 0;
  2129. while (length < precision && str[length]) {
  2130. length++;
  2131. }
  2132. }
  2133. unicode = PyUnicode_DecodeUTF8Stateful(str, length, "replace", NULL);
  2134. if (unicode == NULL)
  2135. return -1;
  2136. res = unicode_fromformat_write_str(writer, unicode, width, -1, flags);
  2137. Py_DECREF(unicode);
  2138. return res;
  2139. }
  2140. static int
  2141. unicode_fromformat_write_wcstr(_PyUnicodeWriter *writer, const wchar_t *str,
  2142. Py_ssize_t width, Py_ssize_t precision, int flags)
  2143. {
  2144. /* UTF-8 */
  2145. Py_ssize_t length;
  2146. PyObject *unicode;
  2147. int res;
  2148. if (precision == -1) {
  2149. length = wcslen(str);
  2150. }
  2151. else {
  2152. length = 0;
  2153. while (length < precision && str[length]) {
  2154. length++;
  2155. }
  2156. }
  2157. unicode = PyUnicode_FromWideChar(str, length);
  2158. if (unicode == NULL)
  2159. return -1;
  2160. res = unicode_fromformat_write_str(writer, unicode, width, -1, flags);
  2161. Py_DECREF(unicode);
  2162. return res;
  2163. }
  2164. #define F_LONG 1
  2165. #define F_LONGLONG 2
  2166. #define F_SIZE 3
  2167. #define F_PTRDIFF 4
  2168. #define F_INTMAX 5
  2169. static const char * const formats[] = {"%d", "%ld", "%lld", "%zd", "%td", "%jd"};
  2170. static const char * const formats_o[] = {"%o", "%lo", "%llo", "%zo", "%to", "%jo"};
  2171. static const char * const formats_u[] = {"%u", "%lu", "%llu", "%zu", "%tu", "%ju"};
  2172. static const char * const formats_x[] = {"%x", "%lx", "%llx", "%zx", "%tx", "%jx"};
  2173. static const char * const formats_X[] = {"%X", "%lX", "%llX", "%zX", "%tX", "%jX"};
  2174. static const char*
  2175. unicode_fromformat_arg(_PyUnicodeWriter *writer,
  2176. const char *f, va_list *vargs)
  2177. {
  2178. const char *p;
  2179. Py_ssize_t len;
  2180. int flags = 0;
  2181. Py_ssize_t width;
  2182. Py_ssize_t precision;
  2183. p = f;
  2184. f++;
  2185. if (*f == '%') {
  2186. if (_PyUnicodeWriter_WriteCharInline(writer, '%') < 0)
  2187. return NULL;
  2188. f++;
  2189. return f;
  2190. }
  2191. /* Parse flags. Example: "%-i" => flags=F_LJUST. */
  2192. /* Flags '+', ' ' and '#' are not particularly useful.
  2193. * They are not worth the implementation and maintenance costs.
  2194. * In addition, '#' should add "0" for "o" conversions for compatibility
  2195. * with printf, but it would confuse Python users. */
  2196. while (1) {
  2197. switch (*f++) {
  2198. case '-': flags |= F_LJUST; continue;
  2199. case '0': flags |= F_ZERO; continue;
  2200. }
  2201. f--;
  2202. break;
  2203. }
  2204. /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
  2205. width = -1;
  2206. if (*f == '*') {
  2207. width = va_arg(*vargs, int);
  2208. if (width < 0) {
  2209. flags |= F_LJUST;
  2210. width = -width;
  2211. }
  2212. f++;
  2213. }
  2214. else if (Py_ISDIGIT((unsigned)*f)) {
  2215. width = *f - '0';
  2216. f++;
  2217. while (Py_ISDIGIT((unsigned)*f)) {
  2218. if (width > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
  2219. PyErr_SetString(PyExc_ValueError,
  2220. "width too big");
  2221. return NULL;
  2222. }
  2223. width = (width * 10) + (*f - '0');
  2224. f++;
  2225. }
  2226. }
  2227. precision = -1;
  2228. if (*f == '.') {
  2229. f++;
  2230. if (*f == '*') {
  2231. precision = va_arg(*vargs, int);
  2232. if (precision < 0) {
  2233. precision = -2;
  2234. }
  2235. f++;
  2236. }
  2237. else if (Py_ISDIGIT((unsigned)*f)) {
  2238. precision = (*f - '0');
  2239. f++;
  2240. while (Py_ISDIGIT((unsigned)*f)) {
  2241. if (precision > (PY_SSIZE_T_MAX - ((int)*f - '0')) / 10) {
  2242. PyErr_SetString(PyExc_ValueError,
  2243. "precision too big");
  2244. return NULL;
  2245. }
  2246. precision = (precision * 10) + (*f - '0');
  2247. f++;
  2248. }
  2249. }
  2250. }
  2251. int sizemod = 0;
  2252. if (*f == 'l') {
  2253. if (f[1] == 'l') {
  2254. sizemod = F_LONGLONG;
  2255. f += 2;
  2256. }
  2257. else {
  2258. sizemod = F_LONG;
  2259. ++f;
  2260. }
  2261. }
  2262. else if (*f == 'z') {
  2263. sizemod = F_SIZE;
  2264. ++f;
  2265. }
  2266. else if (*f == 't') {
  2267. sizemod = F_PTRDIFF;
  2268. ++f;
  2269. }
  2270. else if (*f == 'j') {
  2271. sizemod = F_INTMAX;
  2272. ++f;
  2273. }
  2274. if (f[0] != '\0' && f[1] == '\0')
  2275. writer->overallocate = 0;
  2276. switch (*f) {
  2277. case 'd': case 'i': case 'o': case 'u': case 'x': case 'X':
  2278. break;
  2279. case 'c': case 'p':
  2280. if (sizemod || width >= 0 || precision >= 0) goto invalid_format;
  2281. break;
  2282. case 's':
  2283. case 'V':
  2284. if (sizemod && sizemod != F_LONG) goto invalid_format;
  2285. break;
  2286. default:
  2287. if (sizemod) goto invalid_format;
  2288. break;
  2289. }
  2290. switch (*f) {
  2291. case 'c':
  2292. {
  2293. int ordinal = va_arg(*vargs, int);
  2294. if (ordinal < 0 || ordinal > MAX_UNICODE) {
  2295. PyErr_SetString(PyExc_OverflowError,
  2296. "character argument not in range(0x110000)");
  2297. return NULL;
  2298. }
  2299. if (_PyUnicodeWriter_WriteCharInline(writer, ordinal) < 0)
  2300. return NULL;
  2301. break;
  2302. }
  2303. case 'd': case 'i':
  2304. case 'o': case 'u': case 'x': case 'X':
  2305. {
  2306. /* used by sprintf */
  2307. char buffer[MAX_INTMAX_CHARS];
  2308. const char *fmt = NULL;
  2309. switch (*f) {
  2310. case 'o': fmt = formats_o[sizemod]; break;
  2311. case 'u': fmt = formats_u[sizemod]; break;
  2312. case 'x': fmt = formats_x[sizemod]; break;
  2313. case 'X': fmt = formats_X[sizemod]; break;
  2314. default: fmt = formats[sizemod]; break;
  2315. }
  2316. int issigned = (*f == 'd' || *f == 'i');
  2317. switch (sizemod) {
  2318. case F_LONG:
  2319. len = issigned ?
  2320. sprintf(buffer, fmt, va_arg(*vargs, long)) :
  2321. sprintf(buffer, fmt, va_arg(*vargs, unsigned long));
  2322. break;
  2323. case F_LONGLONG:
  2324. len = issigned ?
  2325. sprintf(buffer, fmt, va_arg(*vargs, long long)) :
  2326. sprintf(buffer, fmt, va_arg(*vargs, unsigned long long));
  2327. break;
  2328. case F_SIZE:
  2329. len = issigned ?
  2330. sprintf(buffer, fmt, va_arg(*vargs, Py_ssize_t)) :
  2331. sprintf(buffer, fmt, va_arg(*vargs, size_t));
  2332. break;
  2333. case F_PTRDIFF:
  2334. len = sprintf(buffer, fmt, va_arg(*vargs, ptrdiff_t));
  2335. break;
  2336. case F_INTMAX:
  2337. len = issigned ?
  2338. sprintf(buffer, fmt, va_arg(*vargs, intmax_t)) :
  2339. sprintf(buffer, fmt, va_arg(*vargs, uintmax_t));
  2340. break;
  2341. default:
  2342. len = issigned ?
  2343. sprintf(buffer, fmt, va_arg(*vargs, int)) :
  2344. sprintf(buffer, fmt, va_arg(*vargs, unsigned int));
  2345. break;
  2346. }
  2347. assert(len >= 0);
  2348. int sign = (buffer[0] == '-');
  2349. len -= sign;
  2350. precision = Py_MAX(precision, len);
  2351. width = Py_MAX(width, precision + sign);
  2352. if ((flags & F_ZERO) && !(flags & F_LJUST)) {
  2353. precision = width - sign;
  2354. }
  2355. Py_ssize_t spacepad = Py_MAX(width - precision - sign, 0);
  2356. Py_ssize_t zeropad = Py_MAX(precision - len, 0);
  2357. if (_PyUnicodeWriter_Prepare(writer, width, 127) == -1)
  2358. return NULL;
  2359. if (spacepad && !(flags & F_LJUST)) {
  2360. if (PyUnicode_Fill(writer->buffer, writer->pos, spacepad, ' ') == -1)
  2361. return NULL;
  2362. writer->pos += spacepad;
  2363. }
  2364. if (sign) {
  2365. if (_PyUnicodeWriter_WriteChar(writer, '-') == -1)
  2366. return NULL;
  2367. }
  2368. if (zeropad) {
  2369. if (PyUnicode_Fill(writer->buffer, writer->pos, zeropad, '0') == -1)
  2370. return NULL;
  2371. writer->pos += zeropad;
  2372. }
  2373. if (_PyUnicodeWriter_WriteASCIIString(writer, &buffer[sign], len) < 0)
  2374. return NULL;
  2375. if (spacepad && (flags & F_LJUST)) {
  2376. if (PyUnicode_Fill(writer->buffer, writer->pos, spacepad, ' ') == -1)
  2377. return NULL;
  2378. writer->pos += spacepad;
  2379. }
  2380. break;
  2381. }
  2382. case 'p':
  2383. {
  2384. char number[MAX_INTMAX_CHARS];
  2385. len = sprintf(number, "%p", va_arg(*vargs, void*));
  2386. assert(len >= 0);
  2387. /* %p is ill-defined: ensure leading 0x. */
  2388. if (number[1] == 'X')
  2389. number[1] = 'x';
  2390. else if (number[1] != 'x') {
  2391. memmove(number + 2, number,
  2392. strlen(number) + 1);
  2393. number[0] = '0';
  2394. number[1] = 'x';
  2395. len += 2;
  2396. }
  2397. if (_PyUnicodeWriter_WriteASCIIString(writer, number, len) < 0)
  2398. return NULL;
  2399. break;
  2400. }
  2401. case 's':
  2402. {
  2403. if (sizemod) {
  2404. const wchar_t *s = va_arg(*vargs, const wchar_t*);
  2405. if (unicode_fromformat_write_wcstr(writer, s, width, precision, flags) < 0)
  2406. return NULL;
  2407. }
  2408. else {
  2409. /* UTF-8 */
  2410. const char *s = va_arg(*vargs, const char*);
  2411. if (unicode_fromformat_write_cstr(writer, s, width, precision, flags) < 0)
  2412. return NULL;
  2413. }
  2414. break;
  2415. }
  2416. case 'U':
  2417. {
  2418. PyObject *obj = va_arg(*vargs, PyObject *);
  2419. assert(obj && _PyUnicode_CHECK(obj));
  2420. if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
  2421. return NULL;
  2422. break;
  2423. }
  2424. case 'V':
  2425. {
  2426. PyObject *obj = va_arg(*vargs, PyObject *);
  2427. const char *str;
  2428. const wchar_t *wstr;
  2429. if (sizemod) {
  2430. wstr = va_arg(*vargs, const wchar_t*);
  2431. }
  2432. else {
  2433. str = va_arg(*vargs, const char *);
  2434. }
  2435. if (obj) {
  2436. assert(_PyUnicode_CHECK(obj));
  2437. if (unicode_fromformat_write_str(writer, obj, width, precision, flags) == -1)
  2438. return NULL;
  2439. }
  2440. else if (sizemod) {
  2441. assert(wstr != NULL);
  2442. if (unicode_fromformat_write_wcstr(writer, wstr, width, precision, flags) < 0)
  2443. return NULL;
  2444. }
  2445. else {
  2446. assert(str != NULL);
  2447. if (unicode_fromformat_write_cstr(writer, str, width, precision, flags) < 0)
  2448. return NULL;
  2449. }
  2450. break;
  2451. }
  2452. case 'S':
  2453. {
  2454. PyObject *obj = va_arg(*vargs, PyObject *);
  2455. PyObject *str;
  2456. assert(obj);
  2457. str = PyObject_Str(obj);
  2458. if (!str)
  2459. return NULL;
  2460. if (unicode_fromformat_write_str(writer, str, width, precision, flags) == -1) {
  2461. Py_DECREF(str);
  2462. return NULL;
  2463. }
  2464. Py_DECREF(str);
  2465. break;
  2466. }
  2467. case 'R':
  2468. {
  2469. PyObject *obj = va_arg(*vargs, PyObject *);
  2470. PyObject *repr;
  2471. assert(obj);
  2472. repr = PyObject_Repr(obj);
  2473. if (!repr)
  2474. return NULL;
  2475. if (unicode_fromformat_write_str(writer, repr, width, precision, flags) == -1) {
  2476. Py_DECREF(repr);
  2477. return NULL;
  2478. }
  2479. Py_DECREF(repr);
  2480. break;
  2481. }
  2482. case 'A':
  2483. {
  2484. PyObject *obj = va_arg(*vargs, PyObject *);
  2485. PyObject *ascii;
  2486. assert(obj);
  2487. ascii = PyObject_ASCII(obj);
  2488. if (!ascii)
  2489. return NULL;
  2490. if (unicode_fromformat_write_str(writer, ascii, width, precision, flags) == -1) {
  2491. Py_DECREF(ascii);
  2492. return NULL;
  2493. }
  2494. Py_DECREF(ascii);
  2495. break;
  2496. }
  2497. default:
  2498. invalid_format:
  2499. PyErr_Format(PyExc_SystemError, "invalid format string: %s", p);
  2500. return NULL;
  2501. }
  2502. f++;
  2503. return f;
  2504. }
  2505. PyObject *
  2506. PyUnicode_FromFormatV(const char *format, va_list vargs)
  2507. {
  2508. va_list vargs2;
  2509. const char *f;
  2510. _PyUnicodeWriter writer;
  2511. _PyUnicodeWriter_Init(&writer);
  2512. writer.min_length = strlen(format) + 100;
  2513. writer.overallocate = 1;
  2514. // Copy varags to be able to pass a reference to a subfunction.
  2515. va_copy(vargs2, vargs);
  2516. for (f = format; *f; ) {
  2517. if (*f == '%') {
  2518. f = unicode_fromformat_arg(&writer, f, &vargs2);
  2519. if (f == NULL)
  2520. goto fail;
  2521. }
  2522. else {
  2523. const char *p;
  2524. Py_ssize_t len;
  2525. p = f;
  2526. do
  2527. {
  2528. if ((unsigned char)*p > 127) {
  2529. PyErr_Format(PyExc_ValueError,
  2530. "PyUnicode_FromFormatV() expects an ASCII-encoded format "
  2531. "string, got a non-ASCII byte: 0x%02x",
  2532. (unsigned char)*p);
  2533. goto fail;
  2534. }
  2535. p++;
  2536. }
  2537. while (*p != '\0' && *p != '%');
  2538. len = p - f;
  2539. if (*p == '\0')
  2540. writer.overallocate = 0;
  2541. if (_PyUnicodeWriter_WriteASCIIString(&writer, f, len) < 0)
  2542. goto fail;
  2543. f = p;
  2544. }
  2545. }
  2546. va_end(vargs2);
  2547. return _PyUnicodeWriter_Finish(&writer);
  2548. fail:
  2549. va_end(vargs2);
  2550. _PyUnicodeWriter_Dealloc(&writer);
  2551. return NULL;
  2552. }
  2553. PyObject *
  2554. PyUnicode_FromFormat(const char *format, ...)
  2555. {
  2556. PyObject* ret;
  2557. va_list vargs;
  2558. va_start(vargs, format);
  2559. ret = PyUnicode_FromFormatV(format, vargs);
  2560. va_end(vargs);
  2561. return ret;
  2562. }
  2563. static Py_ssize_t
  2564. unicode_get_widechar_size(PyObject *unicode)
  2565. {
  2566. Py_ssize_t res;
  2567. assert(unicode != NULL);
  2568. assert(_PyUnicode_CHECK(unicode));
  2569. res = _PyUnicode_LENGTH(unicode);
  2570. #if SIZEOF_WCHAR_T == 2
  2571. if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
  2572. const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
  2573. const Py_UCS4 *end = s + res;
  2574. for (; s < end; ++s) {
  2575. if (*s > 0xFFFF) {
  2576. ++res;
  2577. }
  2578. }
  2579. }
  2580. #endif
  2581. return res;
  2582. }
  2583. static void
  2584. unicode_copy_as_widechar(PyObject *unicode, wchar_t *w, Py_ssize_t size)
  2585. {
  2586. assert(unicode != NULL);
  2587. assert(_PyUnicode_CHECK(unicode));
  2588. if (PyUnicode_KIND(unicode) == sizeof(wchar_t)) {
  2589. memcpy(w, PyUnicode_DATA(unicode), size * sizeof(wchar_t));
  2590. return;
  2591. }
  2592. if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
  2593. const Py_UCS1 *s = PyUnicode_1BYTE_DATA(unicode);
  2594. for (; size--; ++s, ++w) {
  2595. *w = *s;
  2596. }
  2597. }
  2598. else {
  2599. #if SIZEOF_WCHAR_T == 4
  2600. assert(PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND);
  2601. const Py_UCS2 *s = PyUnicode_2BYTE_DATA(unicode);
  2602. for (; size--; ++s, ++w) {
  2603. *w = *s;
  2604. }
  2605. #else
  2606. assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
  2607. const Py_UCS4 *s = PyUnicode_4BYTE_DATA(unicode);
  2608. for (; size--; ++s, ++w) {
  2609. Py_UCS4 ch = *s;
  2610. if (ch > 0xFFFF) {
  2611. assert(ch <= MAX_UNICODE);
  2612. /* encode surrogate pair in this case */
  2613. *w++ = Py_UNICODE_HIGH_SURROGATE(ch);
  2614. if (!size--)
  2615. break;
  2616. *w = Py_UNICODE_LOW_SURROGATE(ch);
  2617. }
  2618. else {
  2619. *w = ch;
  2620. }
  2621. }
  2622. #endif
  2623. }
  2624. }
  2625. #ifdef HAVE_WCHAR_H
  2626. /* Convert a Unicode object to a wide character string.
  2627. - If w is NULL: return the number of wide characters (including the null
  2628. character) required to convert the unicode object. Ignore size argument.
  2629. - Otherwise: return the number of wide characters (excluding the null
  2630. character) written into w. Write at most size wide characters (including
  2631. the null character). */
  2632. Py_ssize_t
  2633. PyUnicode_AsWideChar(PyObject *unicode,
  2634. wchar_t *w,
  2635. Py_ssize_t size)
  2636. {
  2637. Py_ssize_t res;
  2638. if (unicode == NULL) {
  2639. PyErr_BadInternalCall();
  2640. return -1;
  2641. }
  2642. if (!PyUnicode_Check(unicode)) {
  2643. PyErr_BadArgument();
  2644. return -1;
  2645. }
  2646. res = unicode_get_widechar_size(unicode);
  2647. if (w == NULL) {
  2648. return res + 1;
  2649. }
  2650. if (size > res) {
  2651. size = res + 1;
  2652. }
  2653. else {
  2654. res = size;
  2655. }
  2656. unicode_copy_as_widechar(unicode, w, size);
  2657. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  2658. /* Oracle Solaris uses non-Unicode internal wchar_t form for
  2659. non-Unicode locales and hence needs conversion first. */
  2660. if (_Py_LocaleUsesNonUnicodeWchar()) {
  2661. if (_Py_EncodeNonUnicodeWchar_InPlace(w, size) < 0) {
  2662. return -1;
  2663. }
  2664. }
  2665. #endif
  2666. return res;
  2667. }
  2668. wchar_t*
  2669. PyUnicode_AsWideCharString(PyObject *unicode,
  2670. Py_ssize_t *size)
  2671. {
  2672. wchar_t *buffer;
  2673. Py_ssize_t buflen;
  2674. if (unicode == NULL) {
  2675. PyErr_BadInternalCall();
  2676. return NULL;
  2677. }
  2678. if (!PyUnicode_Check(unicode)) {
  2679. PyErr_BadArgument();
  2680. return NULL;
  2681. }
  2682. buflen = unicode_get_widechar_size(unicode);
  2683. buffer = (wchar_t *) PyMem_New(wchar_t, (buflen + 1));
  2684. if (buffer == NULL) {
  2685. PyErr_NoMemory();
  2686. return NULL;
  2687. }
  2688. unicode_copy_as_widechar(unicode, buffer, buflen + 1);
  2689. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  2690. /* Oracle Solaris uses non-Unicode internal wchar_t form for
  2691. non-Unicode locales and hence needs conversion first. */
  2692. if (_Py_LocaleUsesNonUnicodeWchar()) {
  2693. if (_Py_EncodeNonUnicodeWchar_InPlace(buffer, (buflen + 1)) < 0) {
  2694. return NULL;
  2695. }
  2696. }
  2697. #endif
  2698. if (size != NULL) {
  2699. *size = buflen;
  2700. }
  2701. else if (wcslen(buffer) != (size_t)buflen) {
  2702. PyMem_Free(buffer);
  2703. PyErr_SetString(PyExc_ValueError,
  2704. "embedded null character");
  2705. return NULL;
  2706. }
  2707. return buffer;
  2708. }
  2709. #endif /* HAVE_WCHAR_H */
  2710. int
  2711. _PyUnicode_WideCharString_Converter(PyObject *obj, void *ptr)
  2712. {
  2713. wchar_t **p = (wchar_t **)ptr;
  2714. if (obj == NULL) {
  2715. PyMem_Free(*p);
  2716. *p = NULL;
  2717. return 1;
  2718. }
  2719. if (PyUnicode_Check(obj)) {
  2720. *p = PyUnicode_AsWideCharString(obj, NULL);
  2721. if (*p == NULL) {
  2722. return 0;
  2723. }
  2724. return Py_CLEANUP_SUPPORTED;
  2725. }
  2726. PyErr_Format(PyExc_TypeError,
  2727. "argument must be str, not %.50s",
  2728. Py_TYPE(obj)->tp_name);
  2729. return 0;
  2730. }
  2731. int
  2732. _PyUnicode_WideCharString_Opt_Converter(PyObject *obj, void *ptr)
  2733. {
  2734. wchar_t **p = (wchar_t **)ptr;
  2735. if (obj == NULL) {
  2736. PyMem_Free(*p);
  2737. *p = NULL;
  2738. return 1;
  2739. }
  2740. if (obj == Py_None) {
  2741. *p = NULL;
  2742. return 1;
  2743. }
  2744. if (PyUnicode_Check(obj)) {
  2745. *p = PyUnicode_AsWideCharString(obj, NULL);
  2746. if (*p == NULL) {
  2747. return 0;
  2748. }
  2749. return Py_CLEANUP_SUPPORTED;
  2750. }
  2751. PyErr_Format(PyExc_TypeError,
  2752. "argument must be str or None, not %.50s",
  2753. Py_TYPE(obj)->tp_name);
  2754. return 0;
  2755. }
  2756. PyObject *
  2757. PyUnicode_FromOrdinal(int ordinal)
  2758. {
  2759. if (ordinal < 0 || ordinal > MAX_UNICODE) {
  2760. PyErr_SetString(PyExc_ValueError,
  2761. "chr() arg not in range(0x110000)");
  2762. return NULL;
  2763. }
  2764. return unicode_char((Py_UCS4)ordinal);
  2765. }
  2766. PyObject *
  2767. PyUnicode_FromObject(PyObject *obj)
  2768. {
  2769. /* XXX Perhaps we should make this API an alias of
  2770. PyObject_Str() instead ?! */
  2771. if (PyUnicode_CheckExact(obj)) {
  2772. return Py_NewRef(obj);
  2773. }
  2774. if (PyUnicode_Check(obj)) {
  2775. /* For a Unicode subtype that's not a Unicode object,
  2776. return a true Unicode object with the same data. */
  2777. return _PyUnicode_Copy(obj);
  2778. }
  2779. PyErr_Format(PyExc_TypeError,
  2780. "Can't convert '%.100s' object to str implicitly",
  2781. Py_TYPE(obj)->tp_name);
  2782. return NULL;
  2783. }
  2784. PyObject *
  2785. PyUnicode_FromEncodedObject(PyObject *obj,
  2786. const char *encoding,
  2787. const char *errors)
  2788. {
  2789. Py_buffer buffer;
  2790. PyObject *v;
  2791. if (obj == NULL) {
  2792. PyErr_BadInternalCall();
  2793. return NULL;
  2794. }
  2795. /* Decoding bytes objects is the most common case and should be fast */
  2796. if (PyBytes_Check(obj)) {
  2797. if (PyBytes_GET_SIZE(obj) == 0) {
  2798. if (unicode_check_encoding_errors(encoding, errors) < 0) {
  2799. return NULL;
  2800. }
  2801. _Py_RETURN_UNICODE_EMPTY();
  2802. }
  2803. return PyUnicode_Decode(
  2804. PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
  2805. encoding, errors);
  2806. }
  2807. if (PyUnicode_Check(obj)) {
  2808. PyErr_SetString(PyExc_TypeError,
  2809. "decoding str is not supported");
  2810. return NULL;
  2811. }
  2812. /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
  2813. if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
  2814. PyErr_Format(PyExc_TypeError,
  2815. "decoding to str: need a bytes-like object, %.80s found",
  2816. Py_TYPE(obj)->tp_name);
  2817. return NULL;
  2818. }
  2819. if (buffer.len == 0) {
  2820. PyBuffer_Release(&buffer);
  2821. if (unicode_check_encoding_errors(encoding, errors) < 0) {
  2822. return NULL;
  2823. }
  2824. _Py_RETURN_UNICODE_EMPTY();
  2825. }
  2826. v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
  2827. PyBuffer_Release(&buffer);
  2828. return v;
  2829. }
  2830. /* Normalize an encoding name: similar to encodings.normalize_encoding(), but
  2831. also convert to lowercase. Return 1 on success, or 0 on error (encoding is
  2832. longer than lower_len-1). */
  2833. int
  2834. _Py_normalize_encoding(const char *encoding,
  2835. char *lower,
  2836. size_t lower_len)
  2837. {
  2838. const char *e;
  2839. char *l;
  2840. char *l_end;
  2841. int punct;
  2842. assert(encoding != NULL);
  2843. e = encoding;
  2844. l = lower;
  2845. l_end = &lower[lower_len - 1];
  2846. punct = 0;
  2847. while (1) {
  2848. char c = *e;
  2849. if (c == 0) {
  2850. break;
  2851. }
  2852. if (Py_ISALNUM(c) || c == '.') {
  2853. if (punct && l != lower) {
  2854. if (l == l_end) {
  2855. return 0;
  2856. }
  2857. *l++ = '_';
  2858. }
  2859. punct = 0;
  2860. if (l == l_end) {
  2861. return 0;
  2862. }
  2863. *l++ = Py_TOLOWER(c);
  2864. }
  2865. else {
  2866. punct = 1;
  2867. }
  2868. e++;
  2869. }
  2870. *l = '\0';
  2871. return 1;
  2872. }
  2873. PyObject *
  2874. PyUnicode_Decode(const char *s,
  2875. Py_ssize_t size,
  2876. const char *encoding,
  2877. const char *errors)
  2878. {
  2879. PyObject *buffer = NULL, *unicode;
  2880. Py_buffer info;
  2881. char buflower[11]; /* strlen("iso-8859-1\0") == 11, longest shortcut */
  2882. if (unicode_check_encoding_errors(encoding, errors) < 0) {
  2883. return NULL;
  2884. }
  2885. if (size == 0) {
  2886. _Py_RETURN_UNICODE_EMPTY();
  2887. }
  2888. if (encoding == NULL) {
  2889. return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
  2890. }
  2891. /* Shortcuts for common default encodings */
  2892. if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
  2893. char *lower = buflower;
  2894. /* Fast paths */
  2895. if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
  2896. lower += 3;
  2897. if (*lower == '_') {
  2898. /* Match "utf8" and "utf_8" */
  2899. lower++;
  2900. }
  2901. if (lower[0] == '8' && lower[1] == 0) {
  2902. return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
  2903. }
  2904. else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
  2905. return PyUnicode_DecodeUTF16(s, size, errors, 0);
  2906. }
  2907. else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
  2908. return PyUnicode_DecodeUTF32(s, size, errors, 0);
  2909. }
  2910. }
  2911. else {
  2912. if (strcmp(lower, "ascii") == 0
  2913. || strcmp(lower, "us_ascii") == 0) {
  2914. return PyUnicode_DecodeASCII(s, size, errors);
  2915. }
  2916. #ifdef MS_WINDOWS
  2917. else if (strcmp(lower, "mbcs") == 0) {
  2918. return PyUnicode_DecodeMBCS(s, size, errors);
  2919. }
  2920. #endif
  2921. else if (strcmp(lower, "latin1") == 0
  2922. || strcmp(lower, "latin_1") == 0
  2923. || strcmp(lower, "iso_8859_1") == 0
  2924. || strcmp(lower, "iso8859_1") == 0) {
  2925. return PyUnicode_DecodeLatin1(s, size, errors);
  2926. }
  2927. }
  2928. }
  2929. /* Decode via the codec registry */
  2930. buffer = NULL;
  2931. if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
  2932. goto onError;
  2933. buffer = PyMemoryView_FromBuffer(&info);
  2934. if (buffer == NULL)
  2935. goto onError;
  2936. unicode = _PyCodec_DecodeText(buffer, encoding, errors);
  2937. if (unicode == NULL)
  2938. goto onError;
  2939. if (!PyUnicode_Check(unicode)) {
  2940. PyErr_Format(PyExc_TypeError,
  2941. "'%.400s' decoder returned '%.400s' instead of 'str'; "
  2942. "use codecs.decode() to decode to arbitrary types",
  2943. encoding,
  2944. Py_TYPE(unicode)->tp_name);
  2945. Py_DECREF(unicode);
  2946. goto onError;
  2947. }
  2948. Py_DECREF(buffer);
  2949. return unicode_result(unicode);
  2950. onError:
  2951. Py_XDECREF(buffer);
  2952. return NULL;
  2953. }
  2954. PyObject *
  2955. PyUnicode_AsDecodedObject(PyObject *unicode,
  2956. const char *encoding,
  2957. const char *errors)
  2958. {
  2959. if (!PyUnicode_Check(unicode)) {
  2960. PyErr_BadArgument();
  2961. return NULL;
  2962. }
  2963. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  2964. "PyUnicode_AsDecodedObject() is deprecated; "
  2965. "use PyCodec_Decode() to decode from str", 1) < 0)
  2966. return NULL;
  2967. if (encoding == NULL)
  2968. encoding = PyUnicode_GetDefaultEncoding();
  2969. /* Decode via the codec registry */
  2970. return PyCodec_Decode(unicode, encoding, errors);
  2971. }
  2972. PyObject *
  2973. PyUnicode_AsDecodedUnicode(PyObject *unicode,
  2974. const char *encoding,
  2975. const char *errors)
  2976. {
  2977. PyObject *v;
  2978. if (!PyUnicode_Check(unicode)) {
  2979. PyErr_BadArgument();
  2980. goto onError;
  2981. }
  2982. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  2983. "PyUnicode_AsDecodedUnicode() is deprecated; "
  2984. "use PyCodec_Decode() to decode from str to str", 1) < 0)
  2985. return NULL;
  2986. if (encoding == NULL)
  2987. encoding = PyUnicode_GetDefaultEncoding();
  2988. /* Decode via the codec registry */
  2989. v = PyCodec_Decode(unicode, encoding, errors);
  2990. if (v == NULL)
  2991. goto onError;
  2992. if (!PyUnicode_Check(v)) {
  2993. PyErr_Format(PyExc_TypeError,
  2994. "'%.400s' decoder returned '%.400s' instead of 'str'; "
  2995. "use codecs.decode() to decode to arbitrary types",
  2996. encoding,
  2997. Py_TYPE(unicode)->tp_name);
  2998. Py_DECREF(v);
  2999. goto onError;
  3000. }
  3001. return unicode_result(v);
  3002. onError:
  3003. return NULL;
  3004. }
  3005. PyObject *
  3006. PyUnicode_AsEncodedObject(PyObject *unicode,
  3007. const char *encoding,
  3008. const char *errors)
  3009. {
  3010. PyObject *v;
  3011. if (!PyUnicode_Check(unicode)) {
  3012. PyErr_BadArgument();
  3013. goto onError;
  3014. }
  3015. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  3016. "PyUnicode_AsEncodedObject() is deprecated; "
  3017. "use PyUnicode_AsEncodedString() to encode from str to bytes "
  3018. "or PyCodec_Encode() for generic encoding", 1) < 0)
  3019. return NULL;
  3020. if (encoding == NULL)
  3021. encoding = PyUnicode_GetDefaultEncoding();
  3022. /* Encode via the codec registry */
  3023. v = PyCodec_Encode(unicode, encoding, errors);
  3024. if (v == NULL)
  3025. goto onError;
  3026. return v;
  3027. onError:
  3028. return NULL;
  3029. }
  3030. static PyObject *
  3031. unicode_encode_locale(PyObject *unicode, _Py_error_handler error_handler,
  3032. int current_locale)
  3033. {
  3034. Py_ssize_t wlen;
  3035. wchar_t *wstr = PyUnicode_AsWideCharString(unicode, &wlen);
  3036. if (wstr == NULL) {
  3037. return NULL;
  3038. }
  3039. if ((size_t)wlen != wcslen(wstr)) {
  3040. PyErr_SetString(PyExc_ValueError, "embedded null character");
  3041. PyMem_Free(wstr);
  3042. return NULL;
  3043. }
  3044. char *str;
  3045. size_t error_pos;
  3046. const char *reason;
  3047. int res = _Py_EncodeLocaleEx(wstr, &str, &error_pos, &reason,
  3048. current_locale, error_handler);
  3049. PyMem_Free(wstr);
  3050. if (res != 0) {
  3051. if (res == -2) {
  3052. PyObject *exc;
  3053. exc = PyObject_CallFunction(PyExc_UnicodeEncodeError, "sOnns",
  3054. "locale", unicode,
  3055. (Py_ssize_t)error_pos,
  3056. (Py_ssize_t)(error_pos+1),
  3057. reason);
  3058. if (exc != NULL) {
  3059. PyCodec_StrictErrors(exc);
  3060. Py_DECREF(exc);
  3061. }
  3062. }
  3063. else if (res == -3) {
  3064. PyErr_SetString(PyExc_ValueError, "unsupported error handler");
  3065. }
  3066. else {
  3067. PyErr_NoMemory();
  3068. }
  3069. return NULL;
  3070. }
  3071. PyObject *bytes = PyBytes_FromString(str);
  3072. PyMem_RawFree(str);
  3073. return bytes;
  3074. }
  3075. PyObject *
  3076. PyUnicode_EncodeLocale(PyObject *unicode, const char *errors)
  3077. {
  3078. _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
  3079. return unicode_encode_locale(unicode, error_handler, 1);
  3080. }
  3081. PyObject *
  3082. PyUnicode_EncodeFSDefault(PyObject *unicode)
  3083. {
  3084. PyInterpreterState *interp = _PyInterpreterState_GET();
  3085. struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
  3086. if (fs_codec->utf8) {
  3087. return unicode_encode_utf8(unicode,
  3088. fs_codec->error_handler,
  3089. fs_codec->errors);
  3090. }
  3091. #ifndef _Py_FORCE_UTF8_FS_ENCODING
  3092. else if (fs_codec->encoding) {
  3093. return PyUnicode_AsEncodedString(unicode,
  3094. fs_codec->encoding,
  3095. fs_codec->errors);
  3096. }
  3097. #endif
  3098. else {
  3099. /* Before _PyUnicode_InitEncodings() is called, the Python codec
  3100. machinery is not ready and so cannot be used:
  3101. use wcstombs() in this case. */
  3102. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  3103. const wchar_t *filesystem_errors = config->filesystem_errors;
  3104. assert(filesystem_errors != NULL);
  3105. _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
  3106. assert(errors != _Py_ERROR_UNKNOWN);
  3107. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  3108. return unicode_encode_utf8(unicode, errors, NULL);
  3109. #else
  3110. return unicode_encode_locale(unicode, errors, 0);
  3111. #endif
  3112. }
  3113. }
  3114. PyObject *
  3115. PyUnicode_AsEncodedString(PyObject *unicode,
  3116. const char *encoding,
  3117. const char *errors)
  3118. {
  3119. PyObject *v;
  3120. char buflower[11]; /* strlen("iso_8859_1\0") == 11, longest shortcut */
  3121. if (!PyUnicode_Check(unicode)) {
  3122. PyErr_BadArgument();
  3123. return NULL;
  3124. }
  3125. if (unicode_check_encoding_errors(encoding, errors) < 0) {
  3126. return NULL;
  3127. }
  3128. if (encoding == NULL) {
  3129. return _PyUnicode_AsUTF8String(unicode, errors);
  3130. }
  3131. /* Shortcuts for common default encodings */
  3132. if (_Py_normalize_encoding(encoding, buflower, sizeof(buflower))) {
  3133. char *lower = buflower;
  3134. /* Fast paths */
  3135. if (lower[0] == 'u' && lower[1] == 't' && lower[2] == 'f') {
  3136. lower += 3;
  3137. if (*lower == '_') {
  3138. /* Match "utf8" and "utf_8" */
  3139. lower++;
  3140. }
  3141. if (lower[0] == '8' && lower[1] == 0) {
  3142. return _PyUnicode_AsUTF8String(unicode, errors);
  3143. }
  3144. else if (lower[0] == '1' && lower[1] == '6' && lower[2] == 0) {
  3145. return _PyUnicode_EncodeUTF16(unicode, errors, 0);
  3146. }
  3147. else if (lower[0] == '3' && lower[1] == '2' && lower[2] == 0) {
  3148. return _PyUnicode_EncodeUTF32(unicode, errors, 0);
  3149. }
  3150. }
  3151. else {
  3152. if (strcmp(lower, "ascii") == 0
  3153. || strcmp(lower, "us_ascii") == 0) {
  3154. return _PyUnicode_AsASCIIString(unicode, errors);
  3155. }
  3156. #ifdef MS_WINDOWS
  3157. else if (strcmp(lower, "mbcs") == 0) {
  3158. return PyUnicode_EncodeCodePage(CP_ACP, unicode, errors);
  3159. }
  3160. #endif
  3161. else if (strcmp(lower, "latin1") == 0 ||
  3162. strcmp(lower, "latin_1") == 0 ||
  3163. strcmp(lower, "iso_8859_1") == 0 ||
  3164. strcmp(lower, "iso8859_1") == 0) {
  3165. return _PyUnicode_AsLatin1String(unicode, errors);
  3166. }
  3167. }
  3168. }
  3169. /* Encode via the codec registry */
  3170. v = _PyCodec_EncodeText(unicode, encoding, errors);
  3171. if (v == NULL)
  3172. return NULL;
  3173. /* The normal path */
  3174. if (PyBytes_Check(v))
  3175. return v;
  3176. /* If the codec returns a buffer, raise a warning and convert to bytes */
  3177. if (PyByteArray_Check(v)) {
  3178. int error;
  3179. PyObject *b;
  3180. error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
  3181. "encoder %s returned bytearray instead of bytes; "
  3182. "use codecs.encode() to encode to arbitrary types",
  3183. encoding);
  3184. if (error) {
  3185. Py_DECREF(v);
  3186. return NULL;
  3187. }
  3188. b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v),
  3189. PyByteArray_GET_SIZE(v));
  3190. Py_DECREF(v);
  3191. return b;
  3192. }
  3193. PyErr_Format(PyExc_TypeError,
  3194. "'%.400s' encoder returned '%.400s' instead of 'bytes'; "
  3195. "use codecs.encode() to encode to arbitrary types",
  3196. encoding,
  3197. Py_TYPE(v)->tp_name);
  3198. Py_DECREF(v);
  3199. return NULL;
  3200. }
  3201. PyObject *
  3202. PyUnicode_AsEncodedUnicode(PyObject *unicode,
  3203. const char *encoding,
  3204. const char *errors)
  3205. {
  3206. PyObject *v;
  3207. if (!PyUnicode_Check(unicode)) {
  3208. PyErr_BadArgument();
  3209. goto onError;
  3210. }
  3211. if (PyErr_WarnEx(PyExc_DeprecationWarning,
  3212. "PyUnicode_AsEncodedUnicode() is deprecated; "
  3213. "use PyCodec_Encode() to encode from str to str", 1) < 0)
  3214. return NULL;
  3215. if (encoding == NULL)
  3216. encoding = PyUnicode_GetDefaultEncoding();
  3217. /* Encode via the codec registry */
  3218. v = PyCodec_Encode(unicode, encoding, errors);
  3219. if (v == NULL)
  3220. goto onError;
  3221. if (!PyUnicode_Check(v)) {
  3222. PyErr_Format(PyExc_TypeError,
  3223. "'%.400s' encoder returned '%.400s' instead of 'str'; "
  3224. "use codecs.encode() to encode to arbitrary types",
  3225. encoding,
  3226. Py_TYPE(v)->tp_name);
  3227. Py_DECREF(v);
  3228. goto onError;
  3229. }
  3230. return v;
  3231. onError:
  3232. return NULL;
  3233. }
  3234. static PyObject*
  3235. unicode_decode_locale(const char *str, Py_ssize_t len,
  3236. _Py_error_handler errors, int current_locale)
  3237. {
  3238. if (str[len] != '\0' || (size_t)len != strlen(str)) {
  3239. PyErr_SetString(PyExc_ValueError, "embedded null byte");
  3240. return NULL;
  3241. }
  3242. wchar_t *wstr;
  3243. size_t wlen;
  3244. const char *reason;
  3245. int res = _Py_DecodeLocaleEx(str, &wstr, &wlen, &reason,
  3246. current_locale, errors);
  3247. if (res != 0) {
  3248. if (res == -2) {
  3249. PyObject *exc;
  3250. exc = PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
  3251. "locale", str, len,
  3252. (Py_ssize_t)wlen,
  3253. (Py_ssize_t)(wlen + 1),
  3254. reason);
  3255. if (exc != NULL) {
  3256. PyCodec_StrictErrors(exc);
  3257. Py_DECREF(exc);
  3258. }
  3259. }
  3260. else if (res == -3) {
  3261. PyErr_SetString(PyExc_ValueError, "unsupported error handler");
  3262. }
  3263. else {
  3264. PyErr_NoMemory();
  3265. }
  3266. return NULL;
  3267. }
  3268. PyObject *unicode = PyUnicode_FromWideChar(wstr, wlen);
  3269. PyMem_RawFree(wstr);
  3270. return unicode;
  3271. }
  3272. PyObject*
  3273. PyUnicode_DecodeLocaleAndSize(const char *str, Py_ssize_t len,
  3274. const char *errors)
  3275. {
  3276. _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
  3277. return unicode_decode_locale(str, len, error_handler, 1);
  3278. }
  3279. PyObject*
  3280. PyUnicode_DecodeLocale(const char *str, const char *errors)
  3281. {
  3282. Py_ssize_t size = (Py_ssize_t)strlen(str);
  3283. _Py_error_handler error_handler = _Py_GetErrorHandler(errors);
  3284. return unicode_decode_locale(str, size, error_handler, 1);
  3285. }
  3286. PyObject*
  3287. PyUnicode_DecodeFSDefault(const char *s) {
  3288. Py_ssize_t size = (Py_ssize_t)strlen(s);
  3289. return PyUnicode_DecodeFSDefaultAndSize(s, size);
  3290. }
  3291. PyObject*
  3292. PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
  3293. {
  3294. PyInterpreterState *interp = _PyInterpreterState_GET();
  3295. struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
  3296. if (fs_codec->utf8) {
  3297. return unicode_decode_utf8(s, size,
  3298. fs_codec->error_handler,
  3299. fs_codec->errors,
  3300. NULL);
  3301. }
  3302. #ifndef _Py_FORCE_UTF8_FS_ENCODING
  3303. else if (fs_codec->encoding) {
  3304. return PyUnicode_Decode(s, size,
  3305. fs_codec->encoding,
  3306. fs_codec->errors);
  3307. }
  3308. #endif
  3309. else {
  3310. /* Before _PyUnicode_InitEncodings() is called, the Python codec
  3311. machinery is not ready and so cannot be used:
  3312. use mbstowcs() in this case. */
  3313. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  3314. const wchar_t *filesystem_errors = config->filesystem_errors;
  3315. assert(filesystem_errors != NULL);
  3316. _Py_error_handler errors = get_error_handler_wide(filesystem_errors);
  3317. assert(errors != _Py_ERROR_UNKNOWN);
  3318. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  3319. return unicode_decode_utf8(s, size, errors, NULL, NULL);
  3320. #else
  3321. return unicode_decode_locale(s, size, errors, 0);
  3322. #endif
  3323. }
  3324. }
  3325. int
  3326. PyUnicode_FSConverter(PyObject* arg, void* addr)
  3327. {
  3328. PyObject *path = NULL;
  3329. PyObject *output = NULL;
  3330. Py_ssize_t size;
  3331. const char *data;
  3332. if (arg == NULL) {
  3333. Py_DECREF(*(PyObject**)addr);
  3334. *(PyObject**)addr = NULL;
  3335. return 1;
  3336. }
  3337. path = PyOS_FSPath(arg);
  3338. if (path == NULL) {
  3339. return 0;
  3340. }
  3341. if (PyBytes_Check(path)) {
  3342. output = path;
  3343. }
  3344. else { // PyOS_FSPath() guarantees its returned value is bytes or str.
  3345. output = PyUnicode_EncodeFSDefault(path);
  3346. Py_DECREF(path);
  3347. if (!output) {
  3348. return 0;
  3349. }
  3350. assert(PyBytes_Check(output));
  3351. }
  3352. size = PyBytes_GET_SIZE(output);
  3353. data = PyBytes_AS_STRING(output);
  3354. if ((size_t)size != strlen(data)) {
  3355. PyErr_SetString(PyExc_ValueError, "embedded null byte");
  3356. Py_DECREF(output);
  3357. return 0;
  3358. }
  3359. *(PyObject**)addr = output;
  3360. return Py_CLEANUP_SUPPORTED;
  3361. }
  3362. int
  3363. PyUnicode_FSDecoder(PyObject* arg, void* addr)
  3364. {
  3365. if (arg == NULL) {
  3366. Py_DECREF(*(PyObject**)addr);
  3367. *(PyObject**)addr = NULL;
  3368. return 1;
  3369. }
  3370. PyObject *path = PyOS_FSPath(arg);
  3371. if (path == NULL) {
  3372. return 0;
  3373. }
  3374. PyObject *output = NULL;
  3375. if (PyUnicode_Check(path)) {
  3376. output = path;
  3377. }
  3378. else if (PyBytes_Check(path)) {
  3379. output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(path),
  3380. PyBytes_GET_SIZE(path));
  3381. Py_DECREF(path);
  3382. if (!output) {
  3383. return 0;
  3384. }
  3385. }
  3386. else {
  3387. PyErr_Format(PyExc_TypeError,
  3388. "path should be string, bytes, or os.PathLike, not %.200s",
  3389. Py_TYPE(arg)->tp_name);
  3390. Py_DECREF(path);
  3391. return 0;
  3392. }
  3393. if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
  3394. PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
  3395. PyErr_SetString(PyExc_ValueError, "embedded null character");
  3396. Py_DECREF(output);
  3397. return 0;
  3398. }
  3399. *(PyObject**)addr = output;
  3400. return Py_CLEANUP_SUPPORTED;
  3401. }
  3402. static int unicode_fill_utf8(PyObject *unicode);
  3403. const char *
  3404. PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
  3405. {
  3406. if (!PyUnicode_Check(unicode)) {
  3407. PyErr_BadArgument();
  3408. return NULL;
  3409. }
  3410. if (PyUnicode_UTF8(unicode) == NULL) {
  3411. if (unicode_fill_utf8(unicode) == -1) {
  3412. return NULL;
  3413. }
  3414. }
  3415. if (psize)
  3416. *psize = PyUnicode_UTF8_LENGTH(unicode);
  3417. return PyUnicode_UTF8(unicode);
  3418. }
  3419. const char *
  3420. PyUnicode_AsUTF8(PyObject *unicode)
  3421. {
  3422. return PyUnicode_AsUTF8AndSize(unicode, NULL);
  3423. }
  3424. /*
  3425. PyUnicode_GetSize() has been deprecated since Python 3.3
  3426. because it returned length of Py_UNICODE.
  3427. But this function is part of stable abi, because it don't
  3428. include Py_UNICODE in signature and it was not excluded from
  3429. stable abi in PEP 384.
  3430. */
  3431. PyAPI_FUNC(Py_ssize_t)
  3432. PyUnicode_GetSize(PyObject *unicode)
  3433. {
  3434. PyErr_SetString(PyExc_RuntimeError,
  3435. "PyUnicode_GetSize has been removed.");
  3436. return -1;
  3437. }
  3438. Py_ssize_t
  3439. PyUnicode_GetLength(PyObject *unicode)
  3440. {
  3441. if (!PyUnicode_Check(unicode)) {
  3442. PyErr_BadArgument();
  3443. return -1;
  3444. }
  3445. return PyUnicode_GET_LENGTH(unicode);
  3446. }
  3447. Py_UCS4
  3448. PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
  3449. {
  3450. const void *data;
  3451. int kind;
  3452. if (!PyUnicode_Check(unicode)) {
  3453. PyErr_BadArgument();
  3454. return (Py_UCS4)-1;
  3455. }
  3456. if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
  3457. PyErr_SetString(PyExc_IndexError, "string index out of range");
  3458. return (Py_UCS4)-1;
  3459. }
  3460. data = PyUnicode_DATA(unicode);
  3461. kind = PyUnicode_KIND(unicode);
  3462. return PyUnicode_READ(kind, data, index);
  3463. }
  3464. int
  3465. PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
  3466. {
  3467. if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
  3468. PyErr_BadArgument();
  3469. return -1;
  3470. }
  3471. if (index < 0 || index >= PyUnicode_GET_LENGTH(unicode)) {
  3472. PyErr_SetString(PyExc_IndexError, "string index out of range");
  3473. return -1;
  3474. }
  3475. if (unicode_check_modifiable(unicode))
  3476. return -1;
  3477. if (ch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
  3478. PyErr_SetString(PyExc_ValueError, "character out of range");
  3479. return -1;
  3480. }
  3481. PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
  3482. index, ch);
  3483. return 0;
  3484. }
  3485. const char *
  3486. PyUnicode_GetDefaultEncoding(void)
  3487. {
  3488. return "utf-8";
  3489. }
  3490. /* create or adjust a UnicodeDecodeError */
  3491. static void
  3492. make_decode_exception(PyObject **exceptionObject,
  3493. const char *encoding,
  3494. const char *input, Py_ssize_t length,
  3495. Py_ssize_t startpos, Py_ssize_t endpos,
  3496. const char *reason)
  3497. {
  3498. if (*exceptionObject == NULL) {
  3499. *exceptionObject = PyUnicodeDecodeError_Create(
  3500. encoding, input, length, startpos, endpos, reason);
  3501. }
  3502. else {
  3503. if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
  3504. goto onError;
  3505. if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
  3506. goto onError;
  3507. if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
  3508. goto onError;
  3509. }
  3510. return;
  3511. onError:
  3512. Py_CLEAR(*exceptionObject);
  3513. }
  3514. #ifdef MS_WINDOWS
  3515. static int
  3516. widechar_resize(wchar_t **buf, Py_ssize_t *size, Py_ssize_t newsize)
  3517. {
  3518. if (newsize > *size) {
  3519. wchar_t *newbuf = *buf;
  3520. if (PyMem_Resize(newbuf, wchar_t, newsize) == NULL) {
  3521. PyErr_NoMemory();
  3522. return -1;
  3523. }
  3524. *buf = newbuf;
  3525. }
  3526. *size = newsize;
  3527. return 0;
  3528. }
  3529. /* error handling callback helper:
  3530. build arguments, call the callback and check the arguments,
  3531. if no exception occurred, copy the replacement to the output
  3532. and adjust various state variables.
  3533. return 0 on success, -1 on error
  3534. */
  3535. static int
  3536. unicode_decode_call_errorhandler_wchar(
  3537. const char *errors, PyObject **errorHandler,
  3538. const char *encoding, const char *reason,
  3539. const char **input, const char **inend, Py_ssize_t *startinpos,
  3540. Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
  3541. wchar_t **buf, Py_ssize_t *bufsize, Py_ssize_t *outpos)
  3542. {
  3543. static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
  3544. PyObject *restuple = NULL;
  3545. PyObject *repunicode = NULL;
  3546. Py_ssize_t outsize;
  3547. Py_ssize_t insize;
  3548. Py_ssize_t requiredsize;
  3549. Py_ssize_t newpos;
  3550. PyObject *inputobj = NULL;
  3551. Py_ssize_t repwlen;
  3552. if (*errorHandler == NULL) {
  3553. *errorHandler = PyCodec_LookupError(errors);
  3554. if (*errorHandler == NULL)
  3555. goto onError;
  3556. }
  3557. make_decode_exception(exceptionObject,
  3558. encoding,
  3559. *input, *inend - *input,
  3560. *startinpos, *endinpos,
  3561. reason);
  3562. if (*exceptionObject == NULL)
  3563. goto onError;
  3564. restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
  3565. if (restuple == NULL)
  3566. goto onError;
  3567. if (!PyTuple_Check(restuple)) {
  3568. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  3569. goto onError;
  3570. }
  3571. if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
  3572. goto onError;
  3573. /* Copy back the bytes variables, which might have been modified by the
  3574. callback */
  3575. inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
  3576. if (!inputobj)
  3577. goto onError;
  3578. *input = PyBytes_AS_STRING(inputobj);
  3579. insize = PyBytes_GET_SIZE(inputobj);
  3580. *inend = *input + insize;
  3581. /* we can DECREF safely, as the exception has another reference,
  3582. so the object won't go away. */
  3583. Py_DECREF(inputobj);
  3584. if (newpos<0)
  3585. newpos = insize+newpos;
  3586. if (newpos<0 || newpos>insize) {
  3587. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
  3588. goto onError;
  3589. }
  3590. repwlen = PyUnicode_AsWideChar(repunicode, NULL, 0);
  3591. if (repwlen < 0)
  3592. goto onError;
  3593. repwlen--;
  3594. /* need more space? (at least enough for what we
  3595. have+the replacement+the rest of the string (starting
  3596. at the new input position), so we won't have to check space
  3597. when there are no errors in the rest of the string) */
  3598. requiredsize = *outpos;
  3599. if (requiredsize > PY_SSIZE_T_MAX - repwlen)
  3600. goto overflow;
  3601. requiredsize += repwlen;
  3602. if (requiredsize > PY_SSIZE_T_MAX - (insize - newpos))
  3603. goto overflow;
  3604. requiredsize += insize - newpos;
  3605. outsize = *bufsize;
  3606. if (requiredsize > outsize) {
  3607. if (outsize <= PY_SSIZE_T_MAX/2 && requiredsize < 2*outsize)
  3608. requiredsize = 2*outsize;
  3609. if (widechar_resize(buf, bufsize, requiredsize) < 0) {
  3610. goto onError;
  3611. }
  3612. }
  3613. PyUnicode_AsWideChar(repunicode, *buf + *outpos, repwlen);
  3614. *outpos += repwlen;
  3615. *endinpos = newpos;
  3616. *inptr = *input + newpos;
  3617. /* we made it! */
  3618. Py_DECREF(restuple);
  3619. return 0;
  3620. overflow:
  3621. PyErr_SetString(PyExc_OverflowError,
  3622. "decoded result is too long for a Python string");
  3623. onError:
  3624. Py_XDECREF(restuple);
  3625. return -1;
  3626. }
  3627. #endif /* MS_WINDOWS */
  3628. static int
  3629. unicode_decode_call_errorhandler_writer(
  3630. const char *errors, PyObject **errorHandler,
  3631. const char *encoding, const char *reason,
  3632. const char **input, const char **inend, Py_ssize_t *startinpos,
  3633. Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
  3634. _PyUnicodeWriter *writer /* PyObject **output, Py_ssize_t *outpos */)
  3635. {
  3636. static const char *argparse = "Un;decoding error handler must return (str, int) tuple";
  3637. PyObject *restuple = NULL;
  3638. PyObject *repunicode = NULL;
  3639. Py_ssize_t insize;
  3640. Py_ssize_t newpos;
  3641. Py_ssize_t replen;
  3642. Py_ssize_t remain;
  3643. PyObject *inputobj = NULL;
  3644. int need_to_grow = 0;
  3645. const char *new_inptr;
  3646. if (*errorHandler == NULL) {
  3647. *errorHandler = PyCodec_LookupError(errors);
  3648. if (*errorHandler == NULL)
  3649. goto onError;
  3650. }
  3651. make_decode_exception(exceptionObject,
  3652. encoding,
  3653. *input, *inend - *input,
  3654. *startinpos, *endinpos,
  3655. reason);
  3656. if (*exceptionObject == NULL)
  3657. goto onError;
  3658. restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
  3659. if (restuple == NULL)
  3660. goto onError;
  3661. if (!PyTuple_Check(restuple)) {
  3662. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  3663. goto onError;
  3664. }
  3665. if (!PyArg_ParseTuple(restuple, argparse, &repunicode, &newpos))
  3666. goto onError;
  3667. /* Copy back the bytes variables, which might have been modified by the
  3668. callback */
  3669. inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
  3670. if (!inputobj)
  3671. goto onError;
  3672. remain = *inend - *input - *endinpos;
  3673. *input = PyBytes_AS_STRING(inputobj);
  3674. insize = PyBytes_GET_SIZE(inputobj);
  3675. *inend = *input + insize;
  3676. /* we can DECREF safely, as the exception has another reference,
  3677. so the object won't go away. */
  3678. Py_DECREF(inputobj);
  3679. if (newpos<0)
  3680. newpos = insize+newpos;
  3681. if (newpos<0 || newpos>insize) {
  3682. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
  3683. goto onError;
  3684. }
  3685. replen = PyUnicode_GET_LENGTH(repunicode);
  3686. if (replen > 1) {
  3687. writer->min_length += replen - 1;
  3688. need_to_grow = 1;
  3689. }
  3690. new_inptr = *input + newpos;
  3691. if (*inend - new_inptr > remain) {
  3692. /* We don't know the decoding algorithm here so we make the worst
  3693. assumption that one byte decodes to one unicode character.
  3694. If unfortunately one byte could decode to more unicode characters,
  3695. the decoder may write out-of-bound then. Is it possible for the
  3696. algorithms using this function? */
  3697. writer->min_length += *inend - new_inptr - remain;
  3698. need_to_grow = 1;
  3699. }
  3700. if (need_to_grow) {
  3701. writer->overallocate = 1;
  3702. if (_PyUnicodeWriter_Prepare(writer, writer->min_length - writer->pos,
  3703. PyUnicode_MAX_CHAR_VALUE(repunicode)) == -1)
  3704. goto onError;
  3705. }
  3706. if (_PyUnicodeWriter_WriteStr(writer, repunicode) == -1)
  3707. goto onError;
  3708. *endinpos = newpos;
  3709. *inptr = new_inptr;
  3710. /* we made it! */
  3711. Py_DECREF(restuple);
  3712. return 0;
  3713. onError:
  3714. Py_XDECREF(restuple);
  3715. return -1;
  3716. }
  3717. /* --- UTF-7 Codec -------------------------------------------------------- */
  3718. /* See RFC2152 for details. We encode conservatively and decode liberally. */
  3719. /* Three simple macros defining base-64. */
  3720. /* Is c a base-64 character? */
  3721. #define IS_BASE64(c) \
  3722. (((c) >= 'A' && (c) <= 'Z') || \
  3723. ((c) >= 'a' && (c) <= 'z') || \
  3724. ((c) >= '0' && (c) <= '9') || \
  3725. (c) == '+' || (c) == '/')
  3726. /* given that c is a base-64 character, what is its base-64 value? */
  3727. #define FROM_BASE64(c) \
  3728. (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
  3729. ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
  3730. ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
  3731. (c) == '+' ? 62 : 63)
  3732. /* What is the base-64 character of the bottom 6 bits of n? */
  3733. #define TO_BASE64(n) \
  3734. ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
  3735. /* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
  3736. * decoded as itself. We are permissive on decoding; the only ASCII
  3737. * byte not decoding to itself is the + which begins a base64
  3738. * string. */
  3739. #define DECODE_DIRECT(c) \
  3740. ((c) <= 127 && (c) != '+')
  3741. /* The UTF-7 encoder treats ASCII characters differently according to
  3742. * whether they are Set D, Set O, Whitespace, or special (i.e. none of
  3743. * the above). See RFC2152. This array identifies these different
  3744. * sets:
  3745. * 0 : "Set D"
  3746. * alphanumeric and '(),-./:?
  3747. * 1 : "Set O"
  3748. * !"#$%&*;<=>@[]^_`{|}
  3749. * 2 : "whitespace"
  3750. * ht nl cr sp
  3751. * 3 : special (must be base64 encoded)
  3752. * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
  3753. */
  3754. static
  3755. char utf7_category[128] = {
  3756. /* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
  3757. 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
  3758. /* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
  3759. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  3760. /* sp ! " # $ % & ' ( ) * + , - . / */
  3761. 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
  3762. /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
  3763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
  3764. /* @ A B C D E F G H I J K L M N O */
  3765. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  3766. /* P Q R S T U V W X Y Z [ \ ] ^ _ */
  3767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
  3768. /* ` a b c d e f g h i j k l m n o */
  3769. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  3770. /* p q r s t u v w x y z { | } ~ del */
  3771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
  3772. };
  3773. /* ENCODE_DIRECT: this character should be encoded as itself. The
  3774. * answer depends on whether we are encoding set O as itself, and also
  3775. * on whether we are encoding whitespace as itself. RFC2152 makes it
  3776. * clear that the answers to these questions vary between
  3777. * applications, so this code needs to be flexible. */
  3778. #define ENCODE_DIRECT(c, directO, directWS) \
  3779. ((c) < 128 && (c) > 0 && \
  3780. ((utf7_category[(c)] == 0) || \
  3781. (directWS && (utf7_category[(c)] == 2)) || \
  3782. (directO && (utf7_category[(c)] == 1))))
  3783. PyObject *
  3784. PyUnicode_DecodeUTF7(const char *s,
  3785. Py_ssize_t size,
  3786. const char *errors)
  3787. {
  3788. return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
  3789. }
  3790. /* The decoder. The only state we preserve is our read position,
  3791. * i.e. how many characters we have consumed. So if we end in the
  3792. * middle of a shift sequence we have to back off the read position
  3793. * and the output to the beginning of the sequence, otherwise we lose
  3794. * all the shift state (seen bits, number of bits seen, high
  3795. * surrogate). */
  3796. PyObject *
  3797. PyUnicode_DecodeUTF7Stateful(const char *s,
  3798. Py_ssize_t size,
  3799. const char *errors,
  3800. Py_ssize_t *consumed)
  3801. {
  3802. const char *starts = s;
  3803. Py_ssize_t startinpos;
  3804. Py_ssize_t endinpos;
  3805. const char *e;
  3806. _PyUnicodeWriter writer;
  3807. const char *errmsg = "";
  3808. int inShift = 0;
  3809. Py_ssize_t shiftOutStart;
  3810. unsigned int base64bits = 0;
  3811. unsigned long base64buffer = 0;
  3812. Py_UCS4 surrogate = 0;
  3813. PyObject *errorHandler = NULL;
  3814. PyObject *exc = NULL;
  3815. if (size == 0) {
  3816. if (consumed)
  3817. *consumed = 0;
  3818. _Py_RETURN_UNICODE_EMPTY();
  3819. }
  3820. /* Start off assuming it's all ASCII. Widen later as necessary. */
  3821. _PyUnicodeWriter_Init(&writer);
  3822. writer.min_length = size;
  3823. shiftOutStart = 0;
  3824. e = s + size;
  3825. while (s < e) {
  3826. Py_UCS4 ch;
  3827. restart:
  3828. ch = (unsigned char) *s;
  3829. if (inShift) { /* in a base-64 section */
  3830. if (IS_BASE64(ch)) { /* consume a base-64 character */
  3831. base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
  3832. base64bits += 6;
  3833. s++;
  3834. if (base64bits >= 16) {
  3835. /* we have enough bits for a UTF-16 value */
  3836. Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
  3837. base64bits -= 16;
  3838. base64buffer &= (1 << base64bits) - 1; /* clear high bits */
  3839. assert(outCh <= 0xffff);
  3840. if (surrogate) {
  3841. /* expecting a second surrogate */
  3842. if (Py_UNICODE_IS_LOW_SURROGATE(outCh)) {
  3843. Py_UCS4 ch2 = Py_UNICODE_JOIN_SURROGATES(surrogate, outCh);
  3844. if (_PyUnicodeWriter_WriteCharInline(&writer, ch2) < 0)
  3845. goto onError;
  3846. surrogate = 0;
  3847. continue;
  3848. }
  3849. else {
  3850. if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
  3851. goto onError;
  3852. surrogate = 0;
  3853. }
  3854. }
  3855. if (Py_UNICODE_IS_HIGH_SURROGATE(outCh)) {
  3856. /* first surrogate */
  3857. surrogate = outCh;
  3858. }
  3859. else {
  3860. if (_PyUnicodeWriter_WriteCharInline(&writer, outCh) < 0)
  3861. goto onError;
  3862. }
  3863. }
  3864. }
  3865. else { /* now leaving a base-64 section */
  3866. inShift = 0;
  3867. if (base64bits > 0) { /* left-over bits */
  3868. if (base64bits >= 6) {
  3869. /* We've seen at least one base-64 character */
  3870. s++;
  3871. errmsg = "partial character in shift sequence";
  3872. goto utf7Error;
  3873. }
  3874. else {
  3875. /* Some bits remain; they should be zero */
  3876. if (base64buffer != 0) {
  3877. s++;
  3878. errmsg = "non-zero padding bits in shift sequence";
  3879. goto utf7Error;
  3880. }
  3881. }
  3882. }
  3883. if (surrogate && DECODE_DIRECT(ch)) {
  3884. if (_PyUnicodeWriter_WriteCharInline(&writer, surrogate) < 0)
  3885. goto onError;
  3886. }
  3887. surrogate = 0;
  3888. if (ch == '-') {
  3889. /* '-' is absorbed; other terminating
  3890. characters are preserved */
  3891. s++;
  3892. }
  3893. }
  3894. }
  3895. else if ( ch == '+' ) {
  3896. startinpos = s-starts;
  3897. s++; /* consume '+' */
  3898. if (s < e && *s == '-') { /* '+-' encodes '+' */
  3899. s++;
  3900. if (_PyUnicodeWriter_WriteCharInline(&writer, '+') < 0)
  3901. goto onError;
  3902. }
  3903. else if (s < e && !IS_BASE64(*s)) {
  3904. s++;
  3905. errmsg = "ill-formed sequence";
  3906. goto utf7Error;
  3907. }
  3908. else { /* begin base64-encoded section */
  3909. inShift = 1;
  3910. surrogate = 0;
  3911. shiftOutStart = writer.pos;
  3912. base64bits = 0;
  3913. base64buffer = 0;
  3914. }
  3915. }
  3916. else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
  3917. s++;
  3918. if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
  3919. goto onError;
  3920. }
  3921. else {
  3922. startinpos = s-starts;
  3923. s++;
  3924. errmsg = "unexpected special character";
  3925. goto utf7Error;
  3926. }
  3927. continue;
  3928. utf7Error:
  3929. endinpos = s-starts;
  3930. if (unicode_decode_call_errorhandler_writer(
  3931. errors, &errorHandler,
  3932. "utf7", errmsg,
  3933. &starts, &e, &startinpos, &endinpos, &exc, &s,
  3934. &writer))
  3935. goto onError;
  3936. }
  3937. /* end of string */
  3938. if (inShift && !consumed) { /* in shift sequence, no more to follow */
  3939. /* if we're in an inconsistent state, that's an error */
  3940. inShift = 0;
  3941. if (surrogate ||
  3942. (base64bits >= 6) ||
  3943. (base64bits > 0 && base64buffer != 0)) {
  3944. endinpos = size;
  3945. if (unicode_decode_call_errorhandler_writer(
  3946. errors, &errorHandler,
  3947. "utf7", "unterminated shift sequence",
  3948. &starts, &e, &startinpos, &endinpos, &exc, &s,
  3949. &writer))
  3950. goto onError;
  3951. if (s < e)
  3952. goto restart;
  3953. }
  3954. }
  3955. /* return state */
  3956. if (consumed) {
  3957. if (inShift) {
  3958. *consumed = startinpos;
  3959. if (writer.pos != shiftOutStart && writer.maxchar > 127) {
  3960. PyObject *result = PyUnicode_FromKindAndData(
  3961. writer.kind, writer.data, shiftOutStart);
  3962. Py_XDECREF(errorHandler);
  3963. Py_XDECREF(exc);
  3964. _PyUnicodeWriter_Dealloc(&writer);
  3965. return result;
  3966. }
  3967. writer.pos = shiftOutStart; /* back off output */
  3968. }
  3969. else {
  3970. *consumed = s-starts;
  3971. }
  3972. }
  3973. Py_XDECREF(errorHandler);
  3974. Py_XDECREF(exc);
  3975. return _PyUnicodeWriter_Finish(&writer);
  3976. onError:
  3977. Py_XDECREF(errorHandler);
  3978. Py_XDECREF(exc);
  3979. _PyUnicodeWriter_Dealloc(&writer);
  3980. return NULL;
  3981. }
  3982. PyObject *
  3983. _PyUnicode_EncodeUTF7(PyObject *str,
  3984. int base64SetO,
  3985. int base64WhiteSpace,
  3986. const char *errors)
  3987. {
  3988. int kind;
  3989. const void *data;
  3990. Py_ssize_t len;
  3991. PyObject *v;
  3992. int inShift = 0;
  3993. Py_ssize_t i;
  3994. unsigned int base64bits = 0;
  3995. unsigned long base64buffer = 0;
  3996. char * out;
  3997. const char * start;
  3998. kind = PyUnicode_KIND(str);
  3999. data = PyUnicode_DATA(str);
  4000. len = PyUnicode_GET_LENGTH(str);
  4001. if (len == 0)
  4002. return PyBytes_FromStringAndSize(NULL, 0);
  4003. /* It might be possible to tighten this worst case */
  4004. if (len > PY_SSIZE_T_MAX / 8)
  4005. return PyErr_NoMemory();
  4006. v = PyBytes_FromStringAndSize(NULL, len * 8);
  4007. if (v == NULL)
  4008. return NULL;
  4009. start = out = PyBytes_AS_STRING(v);
  4010. for (i = 0; i < len; ++i) {
  4011. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  4012. if (inShift) {
  4013. if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
  4014. /* shifting out */
  4015. if (base64bits) { /* output remaining bits */
  4016. *out++ = TO_BASE64(base64buffer << (6-base64bits));
  4017. base64buffer = 0;
  4018. base64bits = 0;
  4019. }
  4020. inShift = 0;
  4021. /* Characters not in the BASE64 set implicitly unshift the sequence
  4022. so no '-' is required, except if the character is itself a '-' */
  4023. if (IS_BASE64(ch) || ch == '-') {
  4024. *out++ = '-';
  4025. }
  4026. *out++ = (char) ch;
  4027. }
  4028. else {
  4029. goto encode_char;
  4030. }
  4031. }
  4032. else { /* not in a shift sequence */
  4033. if (ch == '+') {
  4034. *out++ = '+';
  4035. *out++ = '-';
  4036. }
  4037. else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
  4038. *out++ = (char) ch;
  4039. }
  4040. else {
  4041. *out++ = '+';
  4042. inShift = 1;
  4043. goto encode_char;
  4044. }
  4045. }
  4046. continue;
  4047. encode_char:
  4048. if (ch >= 0x10000) {
  4049. assert(ch <= MAX_UNICODE);
  4050. /* code first surrogate */
  4051. base64bits += 16;
  4052. base64buffer = (base64buffer << 16) | Py_UNICODE_HIGH_SURROGATE(ch);
  4053. while (base64bits >= 6) {
  4054. *out++ = TO_BASE64(base64buffer >> (base64bits-6));
  4055. base64bits -= 6;
  4056. }
  4057. /* prepare second surrogate */
  4058. ch = Py_UNICODE_LOW_SURROGATE(ch);
  4059. }
  4060. base64bits += 16;
  4061. base64buffer = (base64buffer << 16) | ch;
  4062. while (base64bits >= 6) {
  4063. *out++ = TO_BASE64(base64buffer >> (base64bits-6));
  4064. base64bits -= 6;
  4065. }
  4066. }
  4067. if (base64bits)
  4068. *out++= TO_BASE64(base64buffer << (6-base64bits) );
  4069. if (inShift)
  4070. *out++ = '-';
  4071. if (_PyBytes_Resize(&v, out - start) < 0)
  4072. return NULL;
  4073. return v;
  4074. }
  4075. #undef IS_BASE64
  4076. #undef FROM_BASE64
  4077. #undef TO_BASE64
  4078. #undef DECODE_DIRECT
  4079. #undef ENCODE_DIRECT
  4080. /* --- UTF-8 Codec -------------------------------------------------------- */
  4081. PyObject *
  4082. PyUnicode_DecodeUTF8(const char *s,
  4083. Py_ssize_t size,
  4084. const char *errors)
  4085. {
  4086. return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
  4087. }
  4088. #include "stringlib/asciilib.h"
  4089. #include "stringlib/codecs.h"
  4090. #include "stringlib/undef.h"
  4091. #include "stringlib/ucs1lib.h"
  4092. #include "stringlib/codecs.h"
  4093. #include "stringlib/undef.h"
  4094. #include "stringlib/ucs2lib.h"
  4095. #include "stringlib/codecs.h"
  4096. #include "stringlib/undef.h"
  4097. #include "stringlib/ucs4lib.h"
  4098. #include "stringlib/codecs.h"
  4099. #include "stringlib/undef.h"
  4100. /* Mask to quickly check whether a C 'size_t' contains a
  4101. non-ASCII, UTF8-encoded char. */
  4102. #if (SIZEOF_SIZE_T == 8)
  4103. # define ASCII_CHAR_MASK 0x8080808080808080ULL
  4104. #elif (SIZEOF_SIZE_T == 4)
  4105. # define ASCII_CHAR_MASK 0x80808080U
  4106. #else
  4107. # error C 'size_t' size should be either 4 or 8!
  4108. #endif
  4109. static Py_ssize_t
  4110. ascii_decode(const char *start, const char *end, Py_UCS1 *dest)
  4111. {
  4112. const char *p = start;
  4113. #if SIZEOF_SIZE_T <= SIZEOF_VOID_P
  4114. assert(_Py_IS_ALIGNED(dest, ALIGNOF_SIZE_T));
  4115. if (_Py_IS_ALIGNED(p, ALIGNOF_SIZE_T)) {
  4116. /* Fast path, see in STRINGLIB(utf8_decode) for
  4117. an explanation. */
  4118. /* Help allocation */
  4119. const char *_p = p;
  4120. Py_UCS1 * q = dest;
  4121. while (_p + SIZEOF_SIZE_T <= end) {
  4122. size_t value = *(const size_t *) _p;
  4123. if (value & ASCII_CHAR_MASK)
  4124. break;
  4125. *((size_t *)q) = value;
  4126. _p += SIZEOF_SIZE_T;
  4127. q += SIZEOF_SIZE_T;
  4128. }
  4129. p = _p;
  4130. while (p < end) {
  4131. if ((unsigned char)*p & 0x80)
  4132. break;
  4133. *q++ = *p++;
  4134. }
  4135. return p - start;
  4136. }
  4137. #endif
  4138. while (p < end) {
  4139. /* Fast path, see in STRINGLIB(utf8_decode) in stringlib/codecs.h
  4140. for an explanation. */
  4141. if (_Py_IS_ALIGNED(p, ALIGNOF_SIZE_T)) {
  4142. /* Help allocation */
  4143. const char *_p = p;
  4144. while (_p + SIZEOF_SIZE_T <= end) {
  4145. size_t value = *(const size_t *) _p;
  4146. if (value & ASCII_CHAR_MASK)
  4147. break;
  4148. _p += SIZEOF_SIZE_T;
  4149. }
  4150. p = _p;
  4151. if (_p == end)
  4152. break;
  4153. }
  4154. if ((unsigned char)*p & 0x80)
  4155. break;
  4156. ++p;
  4157. }
  4158. memcpy(dest, start, p - start);
  4159. return p - start;
  4160. }
  4161. static PyObject *
  4162. unicode_decode_utf8(const char *s, Py_ssize_t size,
  4163. _Py_error_handler error_handler, const char *errors,
  4164. Py_ssize_t *consumed)
  4165. {
  4166. if (size == 0) {
  4167. if (consumed)
  4168. *consumed = 0;
  4169. _Py_RETURN_UNICODE_EMPTY();
  4170. }
  4171. /* ASCII is equivalent to the first 128 ordinals in Unicode. */
  4172. if (size == 1 && (unsigned char)s[0] < 128) {
  4173. if (consumed) {
  4174. *consumed = 1;
  4175. }
  4176. return get_latin1_char((unsigned char)s[0]);
  4177. }
  4178. const char *starts = s;
  4179. const char *end = s + size;
  4180. // fast path: try ASCII string.
  4181. PyObject *u = PyUnicode_New(size, 127);
  4182. if (u == NULL) {
  4183. return NULL;
  4184. }
  4185. s += ascii_decode(s, end, PyUnicode_1BYTE_DATA(u));
  4186. if (s == end) {
  4187. if (consumed) {
  4188. *consumed = size;
  4189. }
  4190. return u;
  4191. }
  4192. // Use _PyUnicodeWriter after fast path is failed.
  4193. _PyUnicodeWriter writer;
  4194. _PyUnicodeWriter_InitWithBuffer(&writer, u);
  4195. writer.pos = s - starts;
  4196. Py_ssize_t startinpos, endinpos;
  4197. const char *errmsg = "";
  4198. PyObject *error_handler_obj = NULL;
  4199. PyObject *exc = NULL;
  4200. while (s < end) {
  4201. Py_UCS4 ch;
  4202. int kind = writer.kind;
  4203. if (kind == PyUnicode_1BYTE_KIND) {
  4204. if (PyUnicode_IS_ASCII(writer.buffer))
  4205. ch = asciilib_utf8_decode(&s, end, writer.data, &writer.pos);
  4206. else
  4207. ch = ucs1lib_utf8_decode(&s, end, writer.data, &writer.pos);
  4208. } else if (kind == PyUnicode_2BYTE_KIND) {
  4209. ch = ucs2lib_utf8_decode(&s, end, writer.data, &writer.pos);
  4210. } else {
  4211. assert(kind == PyUnicode_4BYTE_KIND);
  4212. ch = ucs4lib_utf8_decode(&s, end, writer.data, &writer.pos);
  4213. }
  4214. switch (ch) {
  4215. case 0:
  4216. if (s == end || consumed)
  4217. goto End;
  4218. errmsg = "unexpected end of data";
  4219. startinpos = s - starts;
  4220. endinpos = end - starts;
  4221. break;
  4222. case 1:
  4223. errmsg = "invalid start byte";
  4224. startinpos = s - starts;
  4225. endinpos = startinpos + 1;
  4226. break;
  4227. case 2:
  4228. if (consumed && (unsigned char)s[0] == 0xED && end - s == 2
  4229. && (unsigned char)s[1] >= 0xA0 && (unsigned char)s[1] <= 0xBF)
  4230. {
  4231. /* Truncated surrogate code in range D800-DFFF */
  4232. goto End;
  4233. }
  4234. /* fall through */
  4235. case 3:
  4236. case 4:
  4237. errmsg = "invalid continuation byte";
  4238. startinpos = s - starts;
  4239. endinpos = startinpos + ch - 1;
  4240. break;
  4241. default:
  4242. if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
  4243. goto onError;
  4244. continue;
  4245. }
  4246. if (error_handler == _Py_ERROR_UNKNOWN)
  4247. error_handler = _Py_GetErrorHandler(errors);
  4248. switch (error_handler) {
  4249. case _Py_ERROR_IGNORE:
  4250. s += (endinpos - startinpos);
  4251. break;
  4252. case _Py_ERROR_REPLACE:
  4253. if (_PyUnicodeWriter_WriteCharInline(&writer, 0xfffd) < 0)
  4254. goto onError;
  4255. s += (endinpos - startinpos);
  4256. break;
  4257. case _Py_ERROR_SURROGATEESCAPE:
  4258. {
  4259. Py_ssize_t i;
  4260. if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
  4261. goto onError;
  4262. for (i=startinpos; i<endinpos; i++) {
  4263. ch = (Py_UCS4)(unsigned char)(starts[i]);
  4264. PyUnicode_WRITE(writer.kind, writer.data, writer.pos,
  4265. ch + 0xdc00);
  4266. writer.pos++;
  4267. }
  4268. s += (endinpos - startinpos);
  4269. break;
  4270. }
  4271. default:
  4272. if (unicode_decode_call_errorhandler_writer(
  4273. errors, &error_handler_obj,
  4274. "utf-8", errmsg,
  4275. &starts, &end, &startinpos, &endinpos, &exc, &s,
  4276. &writer))
  4277. goto onError;
  4278. }
  4279. }
  4280. End:
  4281. if (consumed)
  4282. *consumed = s - starts;
  4283. Py_XDECREF(error_handler_obj);
  4284. Py_XDECREF(exc);
  4285. return _PyUnicodeWriter_Finish(&writer);
  4286. onError:
  4287. Py_XDECREF(error_handler_obj);
  4288. Py_XDECREF(exc);
  4289. _PyUnicodeWriter_Dealloc(&writer);
  4290. return NULL;
  4291. }
  4292. PyObject *
  4293. PyUnicode_DecodeUTF8Stateful(const char *s,
  4294. Py_ssize_t size,
  4295. const char *errors,
  4296. Py_ssize_t *consumed)
  4297. {
  4298. return unicode_decode_utf8(s, size, _Py_ERROR_UNKNOWN, errors, consumed);
  4299. }
  4300. /* UTF-8 decoder: use surrogateescape error handler if 'surrogateescape' is
  4301. non-zero, use strict error handler otherwise.
  4302. On success, write a pointer to a newly allocated wide character string into
  4303. *wstr (use PyMem_RawFree() to free the memory) and write the output length
  4304. (in number of wchar_t units) into *wlen (if wlen is set).
  4305. On memory allocation failure, return -1.
  4306. On decoding error (if surrogateescape is zero), return -2. If wlen is
  4307. non-NULL, write the start of the illegal byte sequence into *wlen. If reason
  4308. is not NULL, write the decoding error message into *reason. */
  4309. int
  4310. _Py_DecodeUTF8Ex(const char *s, Py_ssize_t size, wchar_t **wstr, size_t *wlen,
  4311. const char **reason, _Py_error_handler errors)
  4312. {
  4313. const char *orig_s = s;
  4314. const char *e;
  4315. wchar_t *unicode;
  4316. Py_ssize_t outpos;
  4317. int surrogateescape = 0;
  4318. int surrogatepass = 0;
  4319. switch (errors)
  4320. {
  4321. case _Py_ERROR_STRICT:
  4322. break;
  4323. case _Py_ERROR_SURROGATEESCAPE:
  4324. surrogateescape = 1;
  4325. break;
  4326. case _Py_ERROR_SURROGATEPASS:
  4327. surrogatepass = 1;
  4328. break;
  4329. default:
  4330. return -3;
  4331. }
  4332. /* Note: size will always be longer than the resulting Unicode
  4333. character count */
  4334. if (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t) - 1 < size) {
  4335. return -1;
  4336. }
  4337. unicode = PyMem_RawMalloc((size + 1) * sizeof(wchar_t));
  4338. if (!unicode) {
  4339. return -1;
  4340. }
  4341. /* Unpack UTF-8 encoded data */
  4342. e = s + size;
  4343. outpos = 0;
  4344. while (s < e) {
  4345. Py_UCS4 ch;
  4346. #if SIZEOF_WCHAR_T == 4
  4347. ch = ucs4lib_utf8_decode(&s, e, (Py_UCS4 *)unicode, &outpos);
  4348. #else
  4349. ch = ucs2lib_utf8_decode(&s, e, (Py_UCS2 *)unicode, &outpos);
  4350. #endif
  4351. if (ch > 0xFF) {
  4352. #if SIZEOF_WCHAR_T == 4
  4353. Py_UNREACHABLE();
  4354. #else
  4355. assert(ch > 0xFFFF && ch <= MAX_UNICODE);
  4356. /* write a surrogate pair */
  4357. unicode[outpos++] = (wchar_t)Py_UNICODE_HIGH_SURROGATE(ch);
  4358. unicode[outpos++] = (wchar_t)Py_UNICODE_LOW_SURROGATE(ch);
  4359. #endif
  4360. }
  4361. else {
  4362. if (!ch && s == e) {
  4363. break;
  4364. }
  4365. if (surrogateescape) {
  4366. unicode[outpos++] = 0xDC00 + (unsigned char)*s++;
  4367. }
  4368. else {
  4369. /* Is it a valid three-byte code? */
  4370. if (surrogatepass
  4371. && (e - s) >= 3
  4372. && (s[0] & 0xf0) == 0xe0
  4373. && (s[1] & 0xc0) == 0x80
  4374. && (s[2] & 0xc0) == 0x80)
  4375. {
  4376. ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
  4377. s += 3;
  4378. unicode[outpos++] = ch;
  4379. }
  4380. else {
  4381. PyMem_RawFree(unicode );
  4382. if (reason != NULL) {
  4383. switch (ch) {
  4384. case 0:
  4385. *reason = "unexpected end of data";
  4386. break;
  4387. case 1:
  4388. *reason = "invalid start byte";
  4389. break;
  4390. /* 2, 3, 4 */
  4391. default:
  4392. *reason = "invalid continuation byte";
  4393. break;
  4394. }
  4395. }
  4396. if (wlen != NULL) {
  4397. *wlen = s - orig_s;
  4398. }
  4399. return -2;
  4400. }
  4401. }
  4402. }
  4403. }
  4404. unicode[outpos] = L'\0';
  4405. if (wlen) {
  4406. *wlen = outpos;
  4407. }
  4408. *wstr = unicode;
  4409. return 0;
  4410. }
  4411. wchar_t*
  4412. _Py_DecodeUTF8_surrogateescape(const char *arg, Py_ssize_t arglen,
  4413. size_t *wlen)
  4414. {
  4415. wchar_t *wstr;
  4416. int res = _Py_DecodeUTF8Ex(arg, arglen,
  4417. &wstr, wlen,
  4418. NULL, _Py_ERROR_SURROGATEESCAPE);
  4419. if (res != 0) {
  4420. /* _Py_DecodeUTF8Ex() must support _Py_ERROR_SURROGATEESCAPE */
  4421. assert(res != -3);
  4422. if (wlen) {
  4423. *wlen = (size_t)res;
  4424. }
  4425. return NULL;
  4426. }
  4427. return wstr;
  4428. }
  4429. /* UTF-8 encoder using the surrogateescape error handler .
  4430. On success, return 0 and write the newly allocated character string (use
  4431. PyMem_Free() to free the memory) into *str.
  4432. On encoding failure, return -2 and write the position of the invalid
  4433. surrogate character into *error_pos (if error_pos is set) and the decoding
  4434. error message into *reason (if reason is set).
  4435. On memory allocation failure, return -1. */
  4436. int
  4437. _Py_EncodeUTF8Ex(const wchar_t *text, char **str, size_t *error_pos,
  4438. const char **reason, int raw_malloc, _Py_error_handler errors)
  4439. {
  4440. const Py_ssize_t max_char_size = 4;
  4441. Py_ssize_t len = wcslen(text);
  4442. assert(len >= 0);
  4443. int surrogateescape = 0;
  4444. int surrogatepass = 0;
  4445. switch (errors)
  4446. {
  4447. case _Py_ERROR_STRICT:
  4448. break;
  4449. case _Py_ERROR_SURROGATEESCAPE:
  4450. surrogateescape = 1;
  4451. break;
  4452. case _Py_ERROR_SURROGATEPASS:
  4453. surrogatepass = 1;
  4454. break;
  4455. default:
  4456. return -3;
  4457. }
  4458. if (len > PY_SSIZE_T_MAX / max_char_size - 1) {
  4459. return -1;
  4460. }
  4461. char *bytes;
  4462. if (raw_malloc) {
  4463. bytes = PyMem_RawMalloc((len + 1) * max_char_size);
  4464. }
  4465. else {
  4466. bytes = PyMem_Malloc((len + 1) * max_char_size);
  4467. }
  4468. if (bytes == NULL) {
  4469. return -1;
  4470. }
  4471. char *p = bytes;
  4472. Py_ssize_t i;
  4473. for (i = 0; i < len; ) {
  4474. Py_ssize_t ch_pos = i;
  4475. Py_UCS4 ch = text[i];
  4476. i++;
  4477. #if Py_UNICODE_SIZE == 2
  4478. if (Py_UNICODE_IS_HIGH_SURROGATE(ch)
  4479. && i < len
  4480. && Py_UNICODE_IS_LOW_SURROGATE(text[i]))
  4481. {
  4482. ch = Py_UNICODE_JOIN_SURROGATES(ch, text[i]);
  4483. i++;
  4484. }
  4485. #endif
  4486. if (ch < 0x80) {
  4487. /* Encode ASCII */
  4488. *p++ = (char) ch;
  4489. }
  4490. else if (ch < 0x0800) {
  4491. /* Encode Latin-1 */
  4492. *p++ = (char)(0xc0 | (ch >> 6));
  4493. *p++ = (char)(0x80 | (ch & 0x3f));
  4494. }
  4495. else if (Py_UNICODE_IS_SURROGATE(ch) && !surrogatepass) {
  4496. /* surrogateescape error handler */
  4497. if (!surrogateescape || !(0xDC80 <= ch && ch <= 0xDCFF)) {
  4498. if (error_pos != NULL) {
  4499. *error_pos = (size_t)ch_pos;
  4500. }
  4501. if (reason != NULL) {
  4502. *reason = "encoding error";
  4503. }
  4504. if (raw_malloc) {
  4505. PyMem_RawFree(bytes);
  4506. }
  4507. else {
  4508. PyMem_Free(bytes);
  4509. }
  4510. return -2;
  4511. }
  4512. *p++ = (char)(ch & 0xff);
  4513. }
  4514. else if (ch < 0x10000) {
  4515. *p++ = (char)(0xe0 | (ch >> 12));
  4516. *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
  4517. *p++ = (char)(0x80 | (ch & 0x3f));
  4518. }
  4519. else { /* ch >= 0x10000 */
  4520. assert(ch <= MAX_UNICODE);
  4521. /* Encode UCS4 Unicode ordinals */
  4522. *p++ = (char)(0xf0 | (ch >> 18));
  4523. *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
  4524. *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
  4525. *p++ = (char)(0x80 | (ch & 0x3f));
  4526. }
  4527. }
  4528. *p++ = '\0';
  4529. size_t final_size = (p - bytes);
  4530. char *bytes2;
  4531. if (raw_malloc) {
  4532. bytes2 = PyMem_RawRealloc(bytes, final_size);
  4533. }
  4534. else {
  4535. bytes2 = PyMem_Realloc(bytes, final_size);
  4536. }
  4537. if (bytes2 == NULL) {
  4538. if (error_pos != NULL) {
  4539. *error_pos = (size_t)-1;
  4540. }
  4541. if (raw_malloc) {
  4542. PyMem_RawFree(bytes);
  4543. }
  4544. else {
  4545. PyMem_Free(bytes);
  4546. }
  4547. return -1;
  4548. }
  4549. *str = bytes2;
  4550. return 0;
  4551. }
  4552. /* Primary internal function which creates utf8 encoded bytes objects.
  4553. Allocation strategy: if the string is short, convert into a stack buffer
  4554. and allocate exactly as much space needed at the end. Else allocate the
  4555. maximum possible needed (4 result bytes per Unicode character), and return
  4556. the excess memory at the end.
  4557. */
  4558. static PyObject *
  4559. unicode_encode_utf8(PyObject *unicode, _Py_error_handler error_handler,
  4560. const char *errors)
  4561. {
  4562. if (!PyUnicode_Check(unicode)) {
  4563. PyErr_BadArgument();
  4564. return NULL;
  4565. }
  4566. if (PyUnicode_UTF8(unicode))
  4567. return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
  4568. PyUnicode_UTF8_LENGTH(unicode));
  4569. int kind = PyUnicode_KIND(unicode);
  4570. const void *data = PyUnicode_DATA(unicode);
  4571. Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
  4572. _PyBytesWriter writer;
  4573. char *end;
  4574. switch (kind) {
  4575. default:
  4576. Py_UNREACHABLE();
  4577. case PyUnicode_1BYTE_KIND:
  4578. /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
  4579. assert(!PyUnicode_IS_ASCII(unicode));
  4580. end = ucs1lib_utf8_encoder(&writer, unicode, data, size, error_handler, errors);
  4581. break;
  4582. case PyUnicode_2BYTE_KIND:
  4583. end = ucs2lib_utf8_encoder(&writer, unicode, data, size, error_handler, errors);
  4584. break;
  4585. case PyUnicode_4BYTE_KIND:
  4586. end = ucs4lib_utf8_encoder(&writer, unicode, data, size, error_handler, errors);
  4587. break;
  4588. }
  4589. if (end == NULL) {
  4590. _PyBytesWriter_Dealloc(&writer);
  4591. return NULL;
  4592. }
  4593. return _PyBytesWriter_Finish(&writer, end);
  4594. }
  4595. static int
  4596. unicode_fill_utf8(PyObject *unicode)
  4597. {
  4598. /* the string cannot be ASCII, or PyUnicode_UTF8() would be set */
  4599. assert(!PyUnicode_IS_ASCII(unicode));
  4600. int kind = PyUnicode_KIND(unicode);
  4601. const void *data = PyUnicode_DATA(unicode);
  4602. Py_ssize_t size = PyUnicode_GET_LENGTH(unicode);
  4603. _PyBytesWriter writer;
  4604. char *end;
  4605. switch (kind) {
  4606. default:
  4607. Py_UNREACHABLE();
  4608. case PyUnicode_1BYTE_KIND:
  4609. end = ucs1lib_utf8_encoder(&writer, unicode, data, size,
  4610. _Py_ERROR_STRICT, NULL);
  4611. break;
  4612. case PyUnicode_2BYTE_KIND:
  4613. end = ucs2lib_utf8_encoder(&writer, unicode, data, size,
  4614. _Py_ERROR_STRICT, NULL);
  4615. break;
  4616. case PyUnicode_4BYTE_KIND:
  4617. end = ucs4lib_utf8_encoder(&writer, unicode, data, size,
  4618. _Py_ERROR_STRICT, NULL);
  4619. break;
  4620. }
  4621. if (end == NULL) {
  4622. _PyBytesWriter_Dealloc(&writer);
  4623. return -1;
  4624. }
  4625. const char *start = writer.use_small_buffer ? writer.small_buffer :
  4626. PyBytes_AS_STRING(writer.buffer);
  4627. Py_ssize_t len = end - start;
  4628. char *cache = PyObject_Malloc(len + 1);
  4629. if (cache == NULL) {
  4630. _PyBytesWriter_Dealloc(&writer);
  4631. PyErr_NoMemory();
  4632. return -1;
  4633. }
  4634. _PyUnicode_UTF8(unicode) = cache;
  4635. _PyUnicode_UTF8_LENGTH(unicode) = len;
  4636. memcpy(cache, start, len);
  4637. cache[len] = '\0';
  4638. _PyBytesWriter_Dealloc(&writer);
  4639. return 0;
  4640. }
  4641. PyObject *
  4642. _PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
  4643. {
  4644. return unicode_encode_utf8(unicode, _Py_ERROR_UNKNOWN, errors);
  4645. }
  4646. PyObject *
  4647. PyUnicode_AsUTF8String(PyObject *unicode)
  4648. {
  4649. return _PyUnicode_AsUTF8String(unicode, NULL);
  4650. }
  4651. /* --- UTF-32 Codec ------------------------------------------------------- */
  4652. PyObject *
  4653. PyUnicode_DecodeUTF32(const char *s,
  4654. Py_ssize_t size,
  4655. const char *errors,
  4656. int *byteorder)
  4657. {
  4658. return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
  4659. }
  4660. PyObject *
  4661. PyUnicode_DecodeUTF32Stateful(const char *s,
  4662. Py_ssize_t size,
  4663. const char *errors,
  4664. int *byteorder,
  4665. Py_ssize_t *consumed)
  4666. {
  4667. const char *starts = s;
  4668. Py_ssize_t startinpos;
  4669. Py_ssize_t endinpos;
  4670. _PyUnicodeWriter writer;
  4671. const unsigned char *q, *e;
  4672. int le, bo = 0; /* assume native ordering by default */
  4673. const char *encoding;
  4674. const char *errmsg = "";
  4675. PyObject *errorHandler = NULL;
  4676. PyObject *exc = NULL;
  4677. q = (const unsigned char *)s;
  4678. e = q + size;
  4679. if (byteorder)
  4680. bo = *byteorder;
  4681. /* Check for BOM marks (U+FEFF) in the input and adjust current
  4682. byte order setting accordingly. In native mode, the leading BOM
  4683. mark is skipped, in all other modes, it is copied to the output
  4684. stream as-is (giving a ZWNBSP character). */
  4685. if (bo == 0 && size >= 4) {
  4686. Py_UCS4 bom = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
  4687. if (bom == 0x0000FEFF) {
  4688. bo = -1;
  4689. q += 4;
  4690. }
  4691. else if (bom == 0xFFFE0000) {
  4692. bo = 1;
  4693. q += 4;
  4694. }
  4695. if (byteorder)
  4696. *byteorder = bo;
  4697. }
  4698. if (q == e) {
  4699. if (consumed)
  4700. *consumed = size;
  4701. _Py_RETURN_UNICODE_EMPTY();
  4702. }
  4703. #ifdef WORDS_BIGENDIAN
  4704. le = bo < 0;
  4705. #else
  4706. le = bo <= 0;
  4707. #endif
  4708. encoding = le ? "utf-32-le" : "utf-32-be";
  4709. _PyUnicodeWriter_Init(&writer);
  4710. writer.min_length = (e - q + 3) / 4;
  4711. if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
  4712. goto onError;
  4713. while (1) {
  4714. Py_UCS4 ch = 0;
  4715. Py_UCS4 maxch = PyUnicode_MAX_CHAR_VALUE(writer.buffer);
  4716. if (e - q >= 4) {
  4717. int kind = writer.kind;
  4718. void *data = writer.data;
  4719. const unsigned char *last = e - 4;
  4720. Py_ssize_t pos = writer.pos;
  4721. if (le) {
  4722. do {
  4723. ch = ((unsigned int)q[3] << 24) | (q[2] << 16) | (q[1] << 8) | q[0];
  4724. if (ch > maxch)
  4725. break;
  4726. if (kind != PyUnicode_1BYTE_KIND &&
  4727. Py_UNICODE_IS_SURROGATE(ch))
  4728. break;
  4729. PyUnicode_WRITE(kind, data, pos++, ch);
  4730. q += 4;
  4731. } while (q <= last);
  4732. }
  4733. else {
  4734. do {
  4735. ch = ((unsigned int)q[0] << 24) | (q[1] << 16) | (q[2] << 8) | q[3];
  4736. if (ch > maxch)
  4737. break;
  4738. if (kind != PyUnicode_1BYTE_KIND &&
  4739. Py_UNICODE_IS_SURROGATE(ch))
  4740. break;
  4741. PyUnicode_WRITE(kind, data, pos++, ch);
  4742. q += 4;
  4743. } while (q <= last);
  4744. }
  4745. writer.pos = pos;
  4746. }
  4747. if (Py_UNICODE_IS_SURROGATE(ch)) {
  4748. errmsg = "code point in surrogate code point range(0xd800, 0xe000)";
  4749. startinpos = ((const char *)q) - starts;
  4750. endinpos = startinpos + 4;
  4751. }
  4752. else if (ch <= maxch) {
  4753. if (q == e || consumed)
  4754. break;
  4755. /* remaining bytes at the end? (size should be divisible by 4) */
  4756. errmsg = "truncated data";
  4757. startinpos = ((const char *)q) - starts;
  4758. endinpos = ((const char *)e) - starts;
  4759. }
  4760. else {
  4761. if (ch < 0x110000) {
  4762. if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
  4763. goto onError;
  4764. q += 4;
  4765. continue;
  4766. }
  4767. errmsg = "code point not in range(0x110000)";
  4768. startinpos = ((const char *)q) - starts;
  4769. endinpos = startinpos + 4;
  4770. }
  4771. /* The remaining input chars are ignored if the callback
  4772. chooses to skip the input */
  4773. if (unicode_decode_call_errorhandler_writer(
  4774. errors, &errorHandler,
  4775. encoding, errmsg,
  4776. &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
  4777. &writer))
  4778. goto onError;
  4779. }
  4780. if (consumed)
  4781. *consumed = (const char *)q-starts;
  4782. Py_XDECREF(errorHandler);
  4783. Py_XDECREF(exc);
  4784. return _PyUnicodeWriter_Finish(&writer);
  4785. onError:
  4786. _PyUnicodeWriter_Dealloc(&writer);
  4787. Py_XDECREF(errorHandler);
  4788. Py_XDECREF(exc);
  4789. return NULL;
  4790. }
  4791. PyObject *
  4792. _PyUnicode_EncodeUTF32(PyObject *str,
  4793. const char *errors,
  4794. int byteorder)
  4795. {
  4796. int kind;
  4797. const void *data;
  4798. Py_ssize_t len;
  4799. PyObject *v;
  4800. uint32_t *out;
  4801. #if PY_LITTLE_ENDIAN
  4802. int native_ordering = byteorder <= 0;
  4803. #else
  4804. int native_ordering = byteorder >= 0;
  4805. #endif
  4806. const char *encoding;
  4807. Py_ssize_t nsize, pos;
  4808. PyObject *errorHandler = NULL;
  4809. PyObject *exc = NULL;
  4810. PyObject *rep = NULL;
  4811. if (!PyUnicode_Check(str)) {
  4812. PyErr_BadArgument();
  4813. return NULL;
  4814. }
  4815. kind = PyUnicode_KIND(str);
  4816. data = PyUnicode_DATA(str);
  4817. len = PyUnicode_GET_LENGTH(str);
  4818. if (len > PY_SSIZE_T_MAX / 4 - (byteorder == 0))
  4819. return PyErr_NoMemory();
  4820. nsize = len + (byteorder == 0);
  4821. v = PyBytes_FromStringAndSize(NULL, nsize * 4);
  4822. if (v == NULL)
  4823. return NULL;
  4824. /* output buffer is 4-bytes aligned */
  4825. assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 4));
  4826. out = (uint32_t *)PyBytes_AS_STRING(v);
  4827. if (byteorder == 0)
  4828. *out++ = 0xFEFF;
  4829. if (len == 0)
  4830. goto done;
  4831. if (byteorder == -1)
  4832. encoding = "utf-32-le";
  4833. else if (byteorder == 1)
  4834. encoding = "utf-32-be";
  4835. else
  4836. encoding = "utf-32";
  4837. if (kind == PyUnicode_1BYTE_KIND) {
  4838. ucs1lib_utf32_encode((const Py_UCS1 *)data, len, &out, native_ordering);
  4839. goto done;
  4840. }
  4841. pos = 0;
  4842. while (pos < len) {
  4843. Py_ssize_t newpos, repsize, moreunits;
  4844. if (kind == PyUnicode_2BYTE_KIND) {
  4845. pos += ucs2lib_utf32_encode((const Py_UCS2 *)data + pos, len - pos,
  4846. &out, native_ordering);
  4847. }
  4848. else {
  4849. assert(kind == PyUnicode_4BYTE_KIND);
  4850. pos += ucs4lib_utf32_encode((const Py_UCS4 *)data + pos, len - pos,
  4851. &out, native_ordering);
  4852. }
  4853. if (pos == len)
  4854. break;
  4855. rep = unicode_encode_call_errorhandler(
  4856. errors, &errorHandler,
  4857. encoding, "surrogates not allowed",
  4858. str, &exc, pos, pos + 1, &newpos);
  4859. if (!rep)
  4860. goto error;
  4861. if (PyBytes_Check(rep)) {
  4862. repsize = PyBytes_GET_SIZE(rep);
  4863. if (repsize & 3) {
  4864. raise_encode_exception(&exc, encoding,
  4865. str, pos, pos + 1,
  4866. "surrogates not allowed");
  4867. goto error;
  4868. }
  4869. moreunits = repsize / 4;
  4870. }
  4871. else {
  4872. assert(PyUnicode_Check(rep));
  4873. moreunits = repsize = PyUnicode_GET_LENGTH(rep);
  4874. if (!PyUnicode_IS_ASCII(rep)) {
  4875. raise_encode_exception(&exc, encoding,
  4876. str, pos, pos + 1,
  4877. "surrogates not allowed");
  4878. goto error;
  4879. }
  4880. }
  4881. moreunits += pos - newpos;
  4882. pos = newpos;
  4883. /* four bytes are reserved for each surrogate */
  4884. if (moreunits > 0) {
  4885. Py_ssize_t outpos = out - (uint32_t*) PyBytes_AS_STRING(v);
  4886. if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 4) {
  4887. /* integer overflow */
  4888. PyErr_NoMemory();
  4889. goto error;
  4890. }
  4891. if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 4 * moreunits) < 0)
  4892. goto error;
  4893. out = (uint32_t*) PyBytes_AS_STRING(v) + outpos;
  4894. }
  4895. if (PyBytes_Check(rep)) {
  4896. memcpy(out, PyBytes_AS_STRING(rep), repsize);
  4897. out += repsize / 4;
  4898. } else /* rep is unicode */ {
  4899. assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
  4900. ucs1lib_utf32_encode(PyUnicode_1BYTE_DATA(rep), repsize,
  4901. &out, native_ordering);
  4902. }
  4903. Py_CLEAR(rep);
  4904. }
  4905. /* Cut back to size actually needed. This is necessary for, for example,
  4906. encoding of a string containing isolated surrogates and the 'ignore'
  4907. handler is used. */
  4908. nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
  4909. if (nsize != PyBytes_GET_SIZE(v))
  4910. _PyBytes_Resize(&v, nsize);
  4911. Py_XDECREF(errorHandler);
  4912. Py_XDECREF(exc);
  4913. done:
  4914. return v;
  4915. error:
  4916. Py_XDECREF(rep);
  4917. Py_XDECREF(errorHandler);
  4918. Py_XDECREF(exc);
  4919. Py_XDECREF(v);
  4920. return NULL;
  4921. }
  4922. PyObject *
  4923. PyUnicode_AsUTF32String(PyObject *unicode)
  4924. {
  4925. return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
  4926. }
  4927. /* --- UTF-16 Codec ------------------------------------------------------- */
  4928. PyObject *
  4929. PyUnicode_DecodeUTF16(const char *s,
  4930. Py_ssize_t size,
  4931. const char *errors,
  4932. int *byteorder)
  4933. {
  4934. return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
  4935. }
  4936. PyObject *
  4937. PyUnicode_DecodeUTF16Stateful(const char *s,
  4938. Py_ssize_t size,
  4939. const char *errors,
  4940. int *byteorder,
  4941. Py_ssize_t *consumed)
  4942. {
  4943. const char *starts = s;
  4944. Py_ssize_t startinpos;
  4945. Py_ssize_t endinpos;
  4946. _PyUnicodeWriter writer;
  4947. const unsigned char *q, *e;
  4948. int bo = 0; /* assume native ordering by default */
  4949. int native_ordering;
  4950. const char *errmsg = "";
  4951. PyObject *errorHandler = NULL;
  4952. PyObject *exc = NULL;
  4953. const char *encoding;
  4954. q = (const unsigned char *)s;
  4955. e = q + size;
  4956. if (byteorder)
  4957. bo = *byteorder;
  4958. /* Check for BOM marks (U+FEFF) in the input and adjust current
  4959. byte order setting accordingly. In native mode, the leading BOM
  4960. mark is skipped, in all other modes, it is copied to the output
  4961. stream as-is (giving a ZWNBSP character). */
  4962. if (bo == 0 && size >= 2) {
  4963. const Py_UCS4 bom = (q[1] << 8) | q[0];
  4964. if (bom == 0xFEFF) {
  4965. q += 2;
  4966. bo = -1;
  4967. }
  4968. else if (bom == 0xFFFE) {
  4969. q += 2;
  4970. bo = 1;
  4971. }
  4972. if (byteorder)
  4973. *byteorder = bo;
  4974. }
  4975. if (q == e) {
  4976. if (consumed)
  4977. *consumed = size;
  4978. _Py_RETURN_UNICODE_EMPTY();
  4979. }
  4980. #if PY_LITTLE_ENDIAN
  4981. native_ordering = bo <= 0;
  4982. encoding = bo <= 0 ? "utf-16-le" : "utf-16-be";
  4983. #else
  4984. native_ordering = bo >= 0;
  4985. encoding = bo >= 0 ? "utf-16-be" : "utf-16-le";
  4986. #endif
  4987. /* Note: size will always be longer than the resulting Unicode
  4988. character count normally. Error handler will take care of
  4989. resizing when needed. */
  4990. _PyUnicodeWriter_Init(&writer);
  4991. writer.min_length = (e - q + 1) / 2;
  4992. if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
  4993. goto onError;
  4994. while (1) {
  4995. Py_UCS4 ch = 0;
  4996. if (e - q >= 2) {
  4997. int kind = writer.kind;
  4998. if (kind == PyUnicode_1BYTE_KIND) {
  4999. if (PyUnicode_IS_ASCII(writer.buffer))
  5000. ch = asciilib_utf16_decode(&q, e,
  5001. (Py_UCS1*)writer.data, &writer.pos,
  5002. native_ordering);
  5003. else
  5004. ch = ucs1lib_utf16_decode(&q, e,
  5005. (Py_UCS1*)writer.data, &writer.pos,
  5006. native_ordering);
  5007. } else if (kind == PyUnicode_2BYTE_KIND) {
  5008. ch = ucs2lib_utf16_decode(&q, e,
  5009. (Py_UCS2*)writer.data, &writer.pos,
  5010. native_ordering);
  5011. } else {
  5012. assert(kind == PyUnicode_4BYTE_KIND);
  5013. ch = ucs4lib_utf16_decode(&q, e,
  5014. (Py_UCS4*)writer.data, &writer.pos,
  5015. native_ordering);
  5016. }
  5017. }
  5018. switch (ch)
  5019. {
  5020. case 0:
  5021. /* remaining byte at the end? (size should be even) */
  5022. if (q == e || consumed)
  5023. goto End;
  5024. errmsg = "truncated data";
  5025. startinpos = ((const char *)q) - starts;
  5026. endinpos = ((const char *)e) - starts;
  5027. break;
  5028. /* The remaining input chars are ignored if the callback
  5029. chooses to skip the input */
  5030. case 1:
  5031. q -= 2;
  5032. if (consumed)
  5033. goto End;
  5034. errmsg = "unexpected end of data";
  5035. startinpos = ((const char *)q) - starts;
  5036. endinpos = ((const char *)e) - starts;
  5037. break;
  5038. case 2:
  5039. errmsg = "illegal encoding";
  5040. startinpos = ((const char *)q) - 2 - starts;
  5041. endinpos = startinpos + 2;
  5042. break;
  5043. case 3:
  5044. errmsg = "illegal UTF-16 surrogate";
  5045. startinpos = ((const char *)q) - 4 - starts;
  5046. endinpos = startinpos + 2;
  5047. break;
  5048. default:
  5049. if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0)
  5050. goto onError;
  5051. continue;
  5052. }
  5053. if (unicode_decode_call_errorhandler_writer(
  5054. errors,
  5055. &errorHandler,
  5056. encoding, errmsg,
  5057. &starts,
  5058. (const char **)&e,
  5059. &startinpos,
  5060. &endinpos,
  5061. &exc,
  5062. (const char **)&q,
  5063. &writer))
  5064. goto onError;
  5065. }
  5066. End:
  5067. if (consumed)
  5068. *consumed = (const char *)q-starts;
  5069. Py_XDECREF(errorHandler);
  5070. Py_XDECREF(exc);
  5071. return _PyUnicodeWriter_Finish(&writer);
  5072. onError:
  5073. _PyUnicodeWriter_Dealloc(&writer);
  5074. Py_XDECREF(errorHandler);
  5075. Py_XDECREF(exc);
  5076. return NULL;
  5077. }
  5078. PyObject *
  5079. _PyUnicode_EncodeUTF16(PyObject *str,
  5080. const char *errors,
  5081. int byteorder)
  5082. {
  5083. int kind;
  5084. const void *data;
  5085. Py_ssize_t len;
  5086. PyObject *v;
  5087. unsigned short *out;
  5088. Py_ssize_t pairs;
  5089. #if PY_BIG_ENDIAN
  5090. int native_ordering = byteorder >= 0;
  5091. #else
  5092. int native_ordering = byteorder <= 0;
  5093. #endif
  5094. const char *encoding;
  5095. Py_ssize_t nsize, pos;
  5096. PyObject *errorHandler = NULL;
  5097. PyObject *exc = NULL;
  5098. PyObject *rep = NULL;
  5099. if (!PyUnicode_Check(str)) {
  5100. PyErr_BadArgument();
  5101. return NULL;
  5102. }
  5103. kind = PyUnicode_KIND(str);
  5104. data = PyUnicode_DATA(str);
  5105. len = PyUnicode_GET_LENGTH(str);
  5106. pairs = 0;
  5107. if (kind == PyUnicode_4BYTE_KIND) {
  5108. const Py_UCS4 *in = (const Py_UCS4 *)data;
  5109. const Py_UCS4 *end = in + len;
  5110. while (in < end) {
  5111. if (*in++ >= 0x10000) {
  5112. pairs++;
  5113. }
  5114. }
  5115. }
  5116. if (len > PY_SSIZE_T_MAX / 2 - pairs - (byteorder == 0)) {
  5117. return PyErr_NoMemory();
  5118. }
  5119. nsize = len + pairs + (byteorder == 0);
  5120. v = PyBytes_FromStringAndSize(NULL, nsize * 2);
  5121. if (v == NULL) {
  5122. return NULL;
  5123. }
  5124. /* output buffer is 2-bytes aligned */
  5125. assert(_Py_IS_ALIGNED(PyBytes_AS_STRING(v), 2));
  5126. out = (unsigned short *)PyBytes_AS_STRING(v);
  5127. if (byteorder == 0) {
  5128. *out++ = 0xFEFF;
  5129. }
  5130. if (len == 0) {
  5131. goto done;
  5132. }
  5133. if (kind == PyUnicode_1BYTE_KIND) {
  5134. ucs1lib_utf16_encode((const Py_UCS1 *)data, len, &out, native_ordering);
  5135. goto done;
  5136. }
  5137. if (byteorder < 0) {
  5138. encoding = "utf-16-le";
  5139. }
  5140. else if (byteorder > 0) {
  5141. encoding = "utf-16-be";
  5142. }
  5143. else {
  5144. encoding = "utf-16";
  5145. }
  5146. pos = 0;
  5147. while (pos < len) {
  5148. Py_ssize_t newpos, repsize, moreunits;
  5149. if (kind == PyUnicode_2BYTE_KIND) {
  5150. pos += ucs2lib_utf16_encode((const Py_UCS2 *)data + pos, len - pos,
  5151. &out, native_ordering);
  5152. }
  5153. else {
  5154. assert(kind == PyUnicode_4BYTE_KIND);
  5155. pos += ucs4lib_utf16_encode((const Py_UCS4 *)data + pos, len - pos,
  5156. &out, native_ordering);
  5157. }
  5158. if (pos == len)
  5159. break;
  5160. rep = unicode_encode_call_errorhandler(
  5161. errors, &errorHandler,
  5162. encoding, "surrogates not allowed",
  5163. str, &exc, pos, pos + 1, &newpos);
  5164. if (!rep)
  5165. goto error;
  5166. if (PyBytes_Check(rep)) {
  5167. repsize = PyBytes_GET_SIZE(rep);
  5168. if (repsize & 1) {
  5169. raise_encode_exception(&exc, encoding,
  5170. str, pos, pos + 1,
  5171. "surrogates not allowed");
  5172. goto error;
  5173. }
  5174. moreunits = repsize / 2;
  5175. }
  5176. else {
  5177. assert(PyUnicode_Check(rep));
  5178. moreunits = repsize = PyUnicode_GET_LENGTH(rep);
  5179. if (!PyUnicode_IS_ASCII(rep)) {
  5180. raise_encode_exception(&exc, encoding,
  5181. str, pos, pos + 1,
  5182. "surrogates not allowed");
  5183. goto error;
  5184. }
  5185. }
  5186. moreunits += pos - newpos;
  5187. pos = newpos;
  5188. /* two bytes are reserved for each surrogate */
  5189. if (moreunits > 0) {
  5190. Py_ssize_t outpos = out - (unsigned short*) PyBytes_AS_STRING(v);
  5191. if (moreunits >= (PY_SSIZE_T_MAX - PyBytes_GET_SIZE(v)) / 2) {
  5192. /* integer overflow */
  5193. PyErr_NoMemory();
  5194. goto error;
  5195. }
  5196. if (_PyBytes_Resize(&v, PyBytes_GET_SIZE(v) + 2 * moreunits) < 0)
  5197. goto error;
  5198. out = (unsigned short*) PyBytes_AS_STRING(v) + outpos;
  5199. }
  5200. if (PyBytes_Check(rep)) {
  5201. memcpy(out, PyBytes_AS_STRING(rep), repsize);
  5202. out += repsize / 2;
  5203. } else /* rep is unicode */ {
  5204. assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
  5205. ucs1lib_utf16_encode(PyUnicode_1BYTE_DATA(rep), repsize,
  5206. &out, native_ordering);
  5207. }
  5208. Py_CLEAR(rep);
  5209. }
  5210. /* Cut back to size actually needed. This is necessary for, for example,
  5211. encoding of a string containing isolated surrogates and the 'ignore' handler
  5212. is used. */
  5213. nsize = (unsigned char*) out - (unsigned char*) PyBytes_AS_STRING(v);
  5214. if (nsize != PyBytes_GET_SIZE(v))
  5215. _PyBytes_Resize(&v, nsize);
  5216. Py_XDECREF(errorHandler);
  5217. Py_XDECREF(exc);
  5218. done:
  5219. return v;
  5220. error:
  5221. Py_XDECREF(rep);
  5222. Py_XDECREF(errorHandler);
  5223. Py_XDECREF(exc);
  5224. Py_XDECREF(v);
  5225. return NULL;
  5226. #undef STORECHAR
  5227. }
  5228. PyObject *
  5229. PyUnicode_AsUTF16String(PyObject *unicode)
  5230. {
  5231. return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
  5232. }
  5233. /* --- Unicode Escape Codec ----------------------------------------------- */
  5234. PyObject *
  5235. _PyUnicode_DecodeUnicodeEscapeInternal(const char *s,
  5236. Py_ssize_t size,
  5237. const char *errors,
  5238. Py_ssize_t *consumed,
  5239. const char **first_invalid_escape)
  5240. {
  5241. const char *starts = s;
  5242. _PyUnicodeWriter writer;
  5243. const char *end;
  5244. PyObject *errorHandler = NULL;
  5245. PyObject *exc = NULL;
  5246. _PyUnicode_Name_CAPI *ucnhash_capi;
  5247. PyInterpreterState *interp = _PyInterpreterState_Get();
  5248. // so we can remember if we've seen an invalid escape char or not
  5249. *first_invalid_escape = NULL;
  5250. if (size == 0) {
  5251. if (consumed) {
  5252. *consumed = 0;
  5253. }
  5254. _Py_RETURN_UNICODE_EMPTY();
  5255. }
  5256. /* Escaped strings will always be longer than the resulting
  5257. Unicode string, so we start with size here and then reduce the
  5258. length after conversion to the true value.
  5259. (but if the error callback returns a long replacement string
  5260. we'll have to allocate more space) */
  5261. _PyUnicodeWriter_Init(&writer);
  5262. writer.min_length = size;
  5263. if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
  5264. goto onError;
  5265. }
  5266. end = s + size;
  5267. while (s < end) {
  5268. unsigned char c = (unsigned char) *s++;
  5269. Py_UCS4 ch;
  5270. int count;
  5271. const char *message;
  5272. #define WRITE_ASCII_CHAR(ch) \
  5273. do { \
  5274. assert(ch <= 127); \
  5275. assert(writer.pos < writer.size); \
  5276. PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
  5277. } while(0)
  5278. #define WRITE_CHAR(ch) \
  5279. do { \
  5280. if (ch <= writer.maxchar) { \
  5281. assert(writer.pos < writer.size); \
  5282. PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
  5283. } \
  5284. else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
  5285. goto onError; \
  5286. } \
  5287. } while(0)
  5288. /* Non-escape characters are interpreted as Unicode ordinals */
  5289. if (c != '\\') {
  5290. WRITE_CHAR(c);
  5291. continue;
  5292. }
  5293. Py_ssize_t startinpos = s - starts - 1;
  5294. /* \ - Escapes */
  5295. if (s >= end) {
  5296. message = "\\ at end of string";
  5297. goto incomplete;
  5298. }
  5299. c = (unsigned char) *s++;
  5300. assert(writer.pos < writer.size);
  5301. switch (c) {
  5302. /* \x escapes */
  5303. case '\n': continue;
  5304. case '\\': WRITE_ASCII_CHAR('\\'); continue;
  5305. case '\'': WRITE_ASCII_CHAR('\''); continue;
  5306. case '\"': WRITE_ASCII_CHAR('\"'); continue;
  5307. case 'b': WRITE_ASCII_CHAR('\b'); continue;
  5308. /* FF */
  5309. case 'f': WRITE_ASCII_CHAR('\014'); continue;
  5310. case 't': WRITE_ASCII_CHAR('\t'); continue;
  5311. case 'n': WRITE_ASCII_CHAR('\n'); continue;
  5312. case 'r': WRITE_ASCII_CHAR('\r'); continue;
  5313. /* VT */
  5314. case 'v': WRITE_ASCII_CHAR('\013'); continue;
  5315. /* BEL, not classic C */
  5316. case 'a': WRITE_ASCII_CHAR('\007'); continue;
  5317. /* \OOO (octal) escapes */
  5318. case '0': case '1': case '2': case '3':
  5319. case '4': case '5': case '6': case '7':
  5320. ch = c - '0';
  5321. if (s < end && '0' <= *s && *s <= '7') {
  5322. ch = (ch<<3) + *s++ - '0';
  5323. if (s < end && '0' <= *s && *s <= '7') {
  5324. ch = (ch<<3) + *s++ - '0';
  5325. }
  5326. }
  5327. if (ch > 0377) {
  5328. if (*first_invalid_escape == NULL) {
  5329. *first_invalid_escape = s-3; /* Back up 3 chars, since we've
  5330. already incremented s. */
  5331. }
  5332. }
  5333. WRITE_CHAR(ch);
  5334. continue;
  5335. /* hex escapes */
  5336. /* \xXX */
  5337. case 'x':
  5338. count = 2;
  5339. message = "truncated \\xXX escape";
  5340. goto hexescape;
  5341. /* \uXXXX */
  5342. case 'u':
  5343. count = 4;
  5344. message = "truncated \\uXXXX escape";
  5345. goto hexescape;
  5346. /* \UXXXXXXXX */
  5347. case 'U':
  5348. count = 8;
  5349. message = "truncated \\UXXXXXXXX escape";
  5350. hexescape:
  5351. for (ch = 0; count; ++s, --count) {
  5352. if (s >= end) {
  5353. goto incomplete;
  5354. }
  5355. c = (unsigned char)*s;
  5356. ch <<= 4;
  5357. if (c >= '0' && c <= '9') {
  5358. ch += c - '0';
  5359. }
  5360. else if (c >= 'a' && c <= 'f') {
  5361. ch += c - ('a' - 10);
  5362. }
  5363. else if (c >= 'A' && c <= 'F') {
  5364. ch += c - ('A' - 10);
  5365. }
  5366. else {
  5367. goto error;
  5368. }
  5369. }
  5370. /* when we get here, ch is a 32-bit unicode character */
  5371. if (ch > MAX_UNICODE) {
  5372. message = "illegal Unicode character";
  5373. goto error;
  5374. }
  5375. WRITE_CHAR(ch);
  5376. continue;
  5377. /* \N{name} */
  5378. case 'N':
  5379. ucnhash_capi = interp->unicode.ucnhash_capi;
  5380. if (ucnhash_capi == NULL) {
  5381. /* load the unicode data module */
  5382. ucnhash_capi = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
  5383. PyUnicodeData_CAPSULE_NAME, 1);
  5384. if (ucnhash_capi == NULL) {
  5385. PyErr_SetString(
  5386. PyExc_UnicodeError,
  5387. "\\N escapes not supported (can't load unicodedata module)"
  5388. );
  5389. goto onError;
  5390. }
  5391. interp->unicode.ucnhash_capi = ucnhash_capi;
  5392. }
  5393. message = "malformed \\N character escape";
  5394. if (s >= end) {
  5395. goto incomplete;
  5396. }
  5397. if (*s == '{') {
  5398. const char *start = ++s;
  5399. size_t namelen;
  5400. /* look for the closing brace */
  5401. while (s < end && *s != '}')
  5402. s++;
  5403. if (s >= end) {
  5404. goto incomplete;
  5405. }
  5406. namelen = s - start;
  5407. if (namelen) {
  5408. /* found a name. look it up in the unicode database */
  5409. s++;
  5410. ch = 0xffffffff; /* in case 'getcode' messes up */
  5411. if (namelen <= INT_MAX &&
  5412. ucnhash_capi->getcode(start, (int)namelen,
  5413. &ch, 0)) {
  5414. assert(ch <= MAX_UNICODE);
  5415. WRITE_CHAR(ch);
  5416. continue;
  5417. }
  5418. message = "unknown Unicode character name";
  5419. }
  5420. }
  5421. goto error;
  5422. default:
  5423. if (*first_invalid_escape == NULL) {
  5424. *first_invalid_escape = s-1; /* Back up one char, since we've
  5425. already incremented s. */
  5426. }
  5427. WRITE_ASCII_CHAR('\\');
  5428. WRITE_CHAR(c);
  5429. continue;
  5430. }
  5431. incomplete:
  5432. if (consumed) {
  5433. *consumed = startinpos;
  5434. break;
  5435. }
  5436. error:;
  5437. Py_ssize_t endinpos = s-starts;
  5438. writer.min_length = end - s + writer.pos;
  5439. if (unicode_decode_call_errorhandler_writer(
  5440. errors, &errorHandler,
  5441. "unicodeescape", message,
  5442. &starts, &end, &startinpos, &endinpos, &exc, &s,
  5443. &writer)) {
  5444. goto onError;
  5445. }
  5446. assert(end - s <= writer.size - writer.pos);
  5447. #undef WRITE_ASCII_CHAR
  5448. #undef WRITE_CHAR
  5449. }
  5450. Py_XDECREF(errorHandler);
  5451. Py_XDECREF(exc);
  5452. return _PyUnicodeWriter_Finish(&writer);
  5453. onError:
  5454. _PyUnicodeWriter_Dealloc(&writer);
  5455. Py_XDECREF(errorHandler);
  5456. Py_XDECREF(exc);
  5457. return NULL;
  5458. }
  5459. PyObject *
  5460. _PyUnicode_DecodeUnicodeEscapeStateful(const char *s,
  5461. Py_ssize_t size,
  5462. const char *errors,
  5463. Py_ssize_t *consumed)
  5464. {
  5465. const char *first_invalid_escape;
  5466. PyObject *result = _PyUnicode_DecodeUnicodeEscapeInternal(s, size, errors,
  5467. consumed,
  5468. &first_invalid_escape);
  5469. if (result == NULL)
  5470. return NULL;
  5471. if (first_invalid_escape != NULL) {
  5472. unsigned char c = *first_invalid_escape;
  5473. if ('4' <= c && c <= '7') {
  5474. if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
  5475. "invalid octal escape sequence '\\%.3s'",
  5476. first_invalid_escape) < 0)
  5477. {
  5478. Py_DECREF(result);
  5479. return NULL;
  5480. }
  5481. }
  5482. else {
  5483. if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
  5484. "invalid escape sequence '\\%c'",
  5485. c) < 0)
  5486. {
  5487. Py_DECREF(result);
  5488. return NULL;
  5489. }
  5490. }
  5491. }
  5492. return result;
  5493. }
  5494. PyObject *
  5495. PyUnicode_DecodeUnicodeEscape(const char *s,
  5496. Py_ssize_t size,
  5497. const char *errors)
  5498. {
  5499. return _PyUnicode_DecodeUnicodeEscapeStateful(s, size, errors, NULL);
  5500. }
  5501. /* Return a Unicode-Escape string version of the Unicode object. */
  5502. PyObject *
  5503. PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
  5504. {
  5505. Py_ssize_t i, len;
  5506. PyObject *repr;
  5507. char *p;
  5508. int kind;
  5509. const void *data;
  5510. Py_ssize_t expandsize;
  5511. /* Initial allocation is based on the longest-possible character
  5512. escape.
  5513. For UCS1 strings it's '\xxx', 4 bytes per source character.
  5514. For UCS2 strings it's '\uxxxx', 6 bytes per source character.
  5515. For UCS4 strings it's '\U00xxxxxx', 10 bytes per source character.
  5516. */
  5517. if (!PyUnicode_Check(unicode)) {
  5518. PyErr_BadArgument();
  5519. return NULL;
  5520. }
  5521. len = PyUnicode_GET_LENGTH(unicode);
  5522. if (len == 0) {
  5523. return PyBytes_FromStringAndSize(NULL, 0);
  5524. }
  5525. kind = PyUnicode_KIND(unicode);
  5526. data = PyUnicode_DATA(unicode);
  5527. /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
  5528. bytes, and 1 byte characters 4. */
  5529. expandsize = kind * 2 + 2;
  5530. if (len > PY_SSIZE_T_MAX / expandsize) {
  5531. return PyErr_NoMemory();
  5532. }
  5533. repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
  5534. if (repr == NULL) {
  5535. return NULL;
  5536. }
  5537. p = PyBytes_AS_STRING(repr);
  5538. for (i = 0; i < len; i++) {
  5539. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  5540. /* U+0000-U+00ff range */
  5541. if (ch < 0x100) {
  5542. if (ch >= ' ' && ch < 127) {
  5543. if (ch != '\\') {
  5544. /* Copy printable US ASCII as-is */
  5545. *p++ = (char) ch;
  5546. }
  5547. /* Escape backslashes */
  5548. else {
  5549. *p++ = '\\';
  5550. *p++ = '\\';
  5551. }
  5552. }
  5553. /* Map special whitespace to '\t', \n', '\r' */
  5554. else if (ch == '\t') {
  5555. *p++ = '\\';
  5556. *p++ = 't';
  5557. }
  5558. else if (ch == '\n') {
  5559. *p++ = '\\';
  5560. *p++ = 'n';
  5561. }
  5562. else if (ch == '\r') {
  5563. *p++ = '\\';
  5564. *p++ = 'r';
  5565. }
  5566. /* Map non-printable US ASCII and 8-bit characters to '\xHH' */
  5567. else {
  5568. *p++ = '\\';
  5569. *p++ = 'x';
  5570. *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
  5571. *p++ = Py_hexdigits[ch & 0x000F];
  5572. }
  5573. }
  5574. /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
  5575. else if (ch < 0x10000) {
  5576. *p++ = '\\';
  5577. *p++ = 'u';
  5578. *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
  5579. *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
  5580. *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
  5581. *p++ = Py_hexdigits[ch & 0x000F];
  5582. }
  5583. /* U+010000-U+10ffff range: Map 21-bit characters to '\U00HHHHHH' */
  5584. else {
  5585. /* Make sure that the first two digits are zero */
  5586. assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
  5587. *p++ = '\\';
  5588. *p++ = 'U';
  5589. *p++ = '0';
  5590. *p++ = '0';
  5591. *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
  5592. *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
  5593. *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
  5594. *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
  5595. *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
  5596. *p++ = Py_hexdigits[ch & 0x0000000F];
  5597. }
  5598. }
  5599. assert(p - PyBytes_AS_STRING(repr) > 0);
  5600. if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
  5601. return NULL;
  5602. }
  5603. return repr;
  5604. }
  5605. /* --- Raw Unicode Escape Codec ------------------------------------------- */
  5606. PyObject *
  5607. _PyUnicode_DecodeRawUnicodeEscapeStateful(const char *s,
  5608. Py_ssize_t size,
  5609. const char *errors,
  5610. Py_ssize_t *consumed)
  5611. {
  5612. const char *starts = s;
  5613. _PyUnicodeWriter writer;
  5614. const char *end;
  5615. PyObject *errorHandler = NULL;
  5616. PyObject *exc = NULL;
  5617. if (size == 0) {
  5618. if (consumed) {
  5619. *consumed = 0;
  5620. }
  5621. _Py_RETURN_UNICODE_EMPTY();
  5622. }
  5623. /* Escaped strings will always be longer than the resulting
  5624. Unicode string, so we start with size here and then reduce the
  5625. length after conversion to the true value. (But decoding error
  5626. handler might have to resize the string) */
  5627. _PyUnicodeWriter_Init(&writer);
  5628. writer.min_length = size;
  5629. if (_PyUnicodeWriter_Prepare(&writer, size, 127) < 0) {
  5630. goto onError;
  5631. }
  5632. end = s + size;
  5633. while (s < end) {
  5634. unsigned char c = (unsigned char) *s++;
  5635. Py_UCS4 ch;
  5636. int count;
  5637. const char *message;
  5638. #define WRITE_CHAR(ch) \
  5639. do { \
  5640. if (ch <= writer.maxchar) { \
  5641. assert(writer.pos < writer.size); \
  5642. PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, ch); \
  5643. } \
  5644. else if (_PyUnicodeWriter_WriteCharInline(&writer, ch) < 0) { \
  5645. goto onError; \
  5646. } \
  5647. } while(0)
  5648. /* Non-escape characters are interpreted as Unicode ordinals */
  5649. if (c != '\\' || (s >= end && !consumed)) {
  5650. WRITE_CHAR(c);
  5651. continue;
  5652. }
  5653. Py_ssize_t startinpos = s - starts - 1;
  5654. /* \ - Escapes */
  5655. if (s >= end) {
  5656. assert(consumed);
  5657. // Set message to silent compiler warning.
  5658. // Actually it is never used.
  5659. message = "\\ at end of string";
  5660. goto incomplete;
  5661. }
  5662. c = (unsigned char) *s++;
  5663. if (c == 'u') {
  5664. count = 4;
  5665. message = "truncated \\uXXXX escape";
  5666. }
  5667. else if (c == 'U') {
  5668. count = 8;
  5669. message = "truncated \\UXXXXXXXX escape";
  5670. }
  5671. else {
  5672. assert(writer.pos < writer.size);
  5673. PyUnicode_WRITE(writer.kind, writer.data, writer.pos++, '\\');
  5674. WRITE_CHAR(c);
  5675. continue;
  5676. }
  5677. /* \uHHHH with 4 hex digits, \U00HHHHHH with 8 */
  5678. for (ch = 0; count; ++s, --count) {
  5679. if (s >= end) {
  5680. goto incomplete;
  5681. }
  5682. c = (unsigned char)*s;
  5683. ch <<= 4;
  5684. if (c >= '0' && c <= '9') {
  5685. ch += c - '0';
  5686. }
  5687. else if (c >= 'a' && c <= 'f') {
  5688. ch += c - ('a' - 10);
  5689. }
  5690. else if (c >= 'A' && c <= 'F') {
  5691. ch += c - ('A' - 10);
  5692. }
  5693. else {
  5694. goto error;
  5695. }
  5696. }
  5697. if (ch > MAX_UNICODE) {
  5698. message = "\\Uxxxxxxxx out of range";
  5699. goto error;
  5700. }
  5701. WRITE_CHAR(ch);
  5702. continue;
  5703. incomplete:
  5704. if (consumed) {
  5705. *consumed = startinpos;
  5706. break;
  5707. }
  5708. error:;
  5709. Py_ssize_t endinpos = s-starts;
  5710. writer.min_length = end - s + writer.pos;
  5711. if (unicode_decode_call_errorhandler_writer(
  5712. errors, &errorHandler,
  5713. "rawunicodeescape", message,
  5714. &starts, &end, &startinpos, &endinpos, &exc, &s,
  5715. &writer)) {
  5716. goto onError;
  5717. }
  5718. assert(end - s <= writer.size - writer.pos);
  5719. #undef WRITE_CHAR
  5720. }
  5721. Py_XDECREF(errorHandler);
  5722. Py_XDECREF(exc);
  5723. return _PyUnicodeWriter_Finish(&writer);
  5724. onError:
  5725. _PyUnicodeWriter_Dealloc(&writer);
  5726. Py_XDECREF(errorHandler);
  5727. Py_XDECREF(exc);
  5728. return NULL;
  5729. }
  5730. PyObject *
  5731. PyUnicode_DecodeRawUnicodeEscape(const char *s,
  5732. Py_ssize_t size,
  5733. const char *errors)
  5734. {
  5735. return _PyUnicode_DecodeRawUnicodeEscapeStateful(s, size, errors, NULL);
  5736. }
  5737. PyObject *
  5738. PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
  5739. {
  5740. PyObject *repr;
  5741. char *p;
  5742. Py_ssize_t expandsize, pos;
  5743. int kind;
  5744. const void *data;
  5745. Py_ssize_t len;
  5746. if (!PyUnicode_Check(unicode)) {
  5747. PyErr_BadArgument();
  5748. return NULL;
  5749. }
  5750. kind = PyUnicode_KIND(unicode);
  5751. data = PyUnicode_DATA(unicode);
  5752. len = PyUnicode_GET_LENGTH(unicode);
  5753. if (kind == PyUnicode_1BYTE_KIND) {
  5754. return PyBytes_FromStringAndSize(data, len);
  5755. }
  5756. /* 4 byte characters can take up 10 bytes, 2 byte characters can take up 6
  5757. bytes, and 1 byte characters 4. */
  5758. expandsize = kind * 2 + 2;
  5759. if (len > PY_SSIZE_T_MAX / expandsize) {
  5760. return PyErr_NoMemory();
  5761. }
  5762. repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
  5763. if (repr == NULL) {
  5764. return NULL;
  5765. }
  5766. if (len == 0) {
  5767. return repr;
  5768. }
  5769. p = PyBytes_AS_STRING(repr);
  5770. for (pos = 0; pos < len; pos++) {
  5771. Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
  5772. /* U+0000-U+00ff range: Copy 8-bit characters as-is */
  5773. if (ch < 0x100) {
  5774. *p++ = (char) ch;
  5775. }
  5776. /* U+0100-U+ffff range: Map 16-bit characters to '\uHHHH' */
  5777. else if (ch < 0x10000) {
  5778. *p++ = '\\';
  5779. *p++ = 'u';
  5780. *p++ = Py_hexdigits[(ch >> 12) & 0xf];
  5781. *p++ = Py_hexdigits[(ch >> 8) & 0xf];
  5782. *p++ = Py_hexdigits[(ch >> 4) & 0xf];
  5783. *p++ = Py_hexdigits[ch & 15];
  5784. }
  5785. /* U+010000-U+10ffff range: Map 32-bit characters to '\U00HHHHHH' */
  5786. else {
  5787. assert(ch <= MAX_UNICODE && MAX_UNICODE <= 0x10ffff);
  5788. *p++ = '\\';
  5789. *p++ = 'U';
  5790. *p++ = '0';
  5791. *p++ = '0';
  5792. *p++ = Py_hexdigits[(ch >> 20) & 0xf];
  5793. *p++ = Py_hexdigits[(ch >> 16) & 0xf];
  5794. *p++ = Py_hexdigits[(ch >> 12) & 0xf];
  5795. *p++ = Py_hexdigits[(ch >> 8) & 0xf];
  5796. *p++ = Py_hexdigits[(ch >> 4) & 0xf];
  5797. *p++ = Py_hexdigits[ch & 15];
  5798. }
  5799. }
  5800. assert(p > PyBytes_AS_STRING(repr));
  5801. if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0) {
  5802. return NULL;
  5803. }
  5804. return repr;
  5805. }
  5806. /* --- Latin-1 Codec ------------------------------------------------------ */
  5807. PyObject *
  5808. PyUnicode_DecodeLatin1(const char *s,
  5809. Py_ssize_t size,
  5810. const char *errors)
  5811. {
  5812. /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
  5813. return _PyUnicode_FromUCS1((const unsigned char*)s, size);
  5814. }
  5815. /* create or adjust a UnicodeEncodeError */
  5816. static void
  5817. make_encode_exception(PyObject **exceptionObject,
  5818. const char *encoding,
  5819. PyObject *unicode,
  5820. Py_ssize_t startpos, Py_ssize_t endpos,
  5821. const char *reason)
  5822. {
  5823. if (*exceptionObject == NULL) {
  5824. *exceptionObject = PyObject_CallFunction(
  5825. PyExc_UnicodeEncodeError, "sOnns",
  5826. encoding, unicode, startpos, endpos, reason);
  5827. }
  5828. else {
  5829. if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
  5830. goto onError;
  5831. if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
  5832. goto onError;
  5833. if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
  5834. goto onError;
  5835. return;
  5836. onError:
  5837. Py_CLEAR(*exceptionObject);
  5838. }
  5839. }
  5840. /* raises a UnicodeEncodeError */
  5841. static void
  5842. raise_encode_exception(PyObject **exceptionObject,
  5843. const char *encoding,
  5844. PyObject *unicode,
  5845. Py_ssize_t startpos, Py_ssize_t endpos,
  5846. const char *reason)
  5847. {
  5848. make_encode_exception(exceptionObject,
  5849. encoding, unicode, startpos, endpos, reason);
  5850. if (*exceptionObject != NULL)
  5851. PyCodec_StrictErrors(*exceptionObject);
  5852. }
  5853. /* error handling callback helper:
  5854. build arguments, call the callback and check the arguments,
  5855. put the result into newpos and return the replacement string, which
  5856. has to be freed by the caller */
  5857. static PyObject *
  5858. unicode_encode_call_errorhandler(const char *errors,
  5859. PyObject **errorHandler,
  5860. const char *encoding, const char *reason,
  5861. PyObject *unicode, PyObject **exceptionObject,
  5862. Py_ssize_t startpos, Py_ssize_t endpos,
  5863. Py_ssize_t *newpos)
  5864. {
  5865. static const char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
  5866. Py_ssize_t len;
  5867. PyObject *restuple;
  5868. PyObject *resunicode;
  5869. if (*errorHandler == NULL) {
  5870. *errorHandler = PyCodec_LookupError(errors);
  5871. if (*errorHandler == NULL)
  5872. return NULL;
  5873. }
  5874. len = PyUnicode_GET_LENGTH(unicode);
  5875. make_encode_exception(exceptionObject,
  5876. encoding, unicode, startpos, endpos, reason);
  5877. if (*exceptionObject == NULL)
  5878. return NULL;
  5879. restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
  5880. if (restuple == NULL)
  5881. return NULL;
  5882. if (!PyTuple_Check(restuple)) {
  5883. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  5884. Py_DECREF(restuple);
  5885. return NULL;
  5886. }
  5887. if (!PyArg_ParseTuple(restuple, argparse,
  5888. &resunicode, newpos)) {
  5889. Py_DECREF(restuple);
  5890. return NULL;
  5891. }
  5892. if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
  5893. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  5894. Py_DECREF(restuple);
  5895. return NULL;
  5896. }
  5897. if (*newpos<0)
  5898. *newpos = len + *newpos;
  5899. if (*newpos<0 || *newpos>len) {
  5900. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
  5901. Py_DECREF(restuple);
  5902. return NULL;
  5903. }
  5904. Py_INCREF(resunicode);
  5905. Py_DECREF(restuple);
  5906. return resunicode;
  5907. }
  5908. static PyObject *
  5909. unicode_encode_ucs1(PyObject *unicode,
  5910. const char *errors,
  5911. const Py_UCS4 limit)
  5912. {
  5913. /* input state */
  5914. Py_ssize_t pos=0, size;
  5915. int kind;
  5916. const void *data;
  5917. /* pointer into the output */
  5918. char *str;
  5919. const char *encoding = (limit == 256) ? "latin-1" : "ascii";
  5920. const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
  5921. PyObject *error_handler_obj = NULL;
  5922. PyObject *exc = NULL;
  5923. _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
  5924. PyObject *rep = NULL;
  5925. /* output object */
  5926. _PyBytesWriter writer;
  5927. size = PyUnicode_GET_LENGTH(unicode);
  5928. kind = PyUnicode_KIND(unicode);
  5929. data = PyUnicode_DATA(unicode);
  5930. /* allocate enough for a simple encoding without
  5931. replacements, if we need more, we'll resize */
  5932. if (size == 0)
  5933. return PyBytes_FromStringAndSize(NULL, 0);
  5934. _PyBytesWriter_Init(&writer);
  5935. str = _PyBytesWriter_Alloc(&writer, size);
  5936. if (str == NULL)
  5937. return NULL;
  5938. while (pos < size) {
  5939. Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
  5940. /* can we encode this? */
  5941. if (ch < limit) {
  5942. /* no overflow check, because we know that the space is enough */
  5943. *str++ = (char)ch;
  5944. ++pos;
  5945. }
  5946. else {
  5947. Py_ssize_t newpos, i;
  5948. /* startpos for collecting unencodable chars */
  5949. Py_ssize_t collstart = pos;
  5950. Py_ssize_t collend = collstart + 1;
  5951. /* find all unecodable characters */
  5952. while ((collend < size) && (PyUnicode_READ(kind, data, collend) >= limit))
  5953. ++collend;
  5954. /* Only overallocate the buffer if it's not the last write */
  5955. writer.overallocate = (collend < size);
  5956. /* cache callback name lookup (if not done yet, i.e. it's the first error) */
  5957. if (error_handler == _Py_ERROR_UNKNOWN)
  5958. error_handler = _Py_GetErrorHandler(errors);
  5959. switch (error_handler) {
  5960. case _Py_ERROR_STRICT:
  5961. raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
  5962. goto onError;
  5963. case _Py_ERROR_REPLACE:
  5964. memset(str, '?', collend - collstart);
  5965. str += (collend - collstart);
  5966. /* fall through */
  5967. case _Py_ERROR_IGNORE:
  5968. pos = collend;
  5969. break;
  5970. case _Py_ERROR_BACKSLASHREPLACE:
  5971. /* subtract preallocated bytes */
  5972. writer.min_size -= (collend - collstart);
  5973. str = backslashreplace(&writer, str,
  5974. unicode, collstart, collend);
  5975. if (str == NULL)
  5976. goto onError;
  5977. pos = collend;
  5978. break;
  5979. case _Py_ERROR_XMLCHARREFREPLACE:
  5980. /* subtract preallocated bytes */
  5981. writer.min_size -= (collend - collstart);
  5982. str = xmlcharrefreplace(&writer, str,
  5983. unicode, collstart, collend);
  5984. if (str == NULL)
  5985. goto onError;
  5986. pos = collend;
  5987. break;
  5988. case _Py_ERROR_SURROGATEESCAPE:
  5989. for (i = collstart; i < collend; ++i) {
  5990. ch = PyUnicode_READ(kind, data, i);
  5991. if (ch < 0xdc80 || 0xdcff < ch) {
  5992. /* Not a UTF-8b surrogate */
  5993. break;
  5994. }
  5995. *str++ = (char)(ch - 0xdc00);
  5996. ++pos;
  5997. }
  5998. if (i >= collend)
  5999. break;
  6000. collstart = pos;
  6001. assert(collstart != collend);
  6002. /* fall through */
  6003. default:
  6004. rep = unicode_encode_call_errorhandler(errors, &error_handler_obj,
  6005. encoding, reason, unicode, &exc,
  6006. collstart, collend, &newpos);
  6007. if (rep == NULL)
  6008. goto onError;
  6009. if (newpos < collstart) {
  6010. writer.overallocate = 1;
  6011. str = _PyBytesWriter_Prepare(&writer, str,
  6012. collstart - newpos);
  6013. if (str == NULL)
  6014. goto onError;
  6015. }
  6016. else {
  6017. /* subtract preallocated bytes */
  6018. writer.min_size -= newpos - collstart;
  6019. /* Only overallocate the buffer if it's not the last write */
  6020. writer.overallocate = (newpos < size);
  6021. }
  6022. if (PyBytes_Check(rep)) {
  6023. /* Directly copy bytes result to output. */
  6024. str = _PyBytesWriter_WriteBytes(&writer, str,
  6025. PyBytes_AS_STRING(rep),
  6026. PyBytes_GET_SIZE(rep));
  6027. }
  6028. else {
  6029. assert(PyUnicode_Check(rep));
  6030. if (limit == 256 ?
  6031. PyUnicode_KIND(rep) != PyUnicode_1BYTE_KIND :
  6032. !PyUnicode_IS_ASCII(rep))
  6033. {
  6034. /* Not all characters are smaller than limit */
  6035. raise_encode_exception(&exc, encoding, unicode,
  6036. collstart, collend, reason);
  6037. goto onError;
  6038. }
  6039. assert(PyUnicode_KIND(rep) == PyUnicode_1BYTE_KIND);
  6040. str = _PyBytesWriter_WriteBytes(&writer, str,
  6041. PyUnicode_DATA(rep),
  6042. PyUnicode_GET_LENGTH(rep));
  6043. }
  6044. if (str == NULL)
  6045. goto onError;
  6046. pos = newpos;
  6047. Py_CLEAR(rep);
  6048. }
  6049. /* If overallocation was disabled, ensure that it was the last
  6050. write. Otherwise, we missed an optimization */
  6051. assert(writer.overallocate || pos == size);
  6052. }
  6053. }
  6054. Py_XDECREF(error_handler_obj);
  6055. Py_XDECREF(exc);
  6056. return _PyBytesWriter_Finish(&writer, str);
  6057. onError:
  6058. Py_XDECREF(rep);
  6059. _PyBytesWriter_Dealloc(&writer);
  6060. Py_XDECREF(error_handler_obj);
  6061. Py_XDECREF(exc);
  6062. return NULL;
  6063. }
  6064. PyObject *
  6065. _PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
  6066. {
  6067. if (!PyUnicode_Check(unicode)) {
  6068. PyErr_BadArgument();
  6069. return NULL;
  6070. }
  6071. /* Fast path: if it is a one-byte string, construct
  6072. bytes object directly. */
  6073. if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
  6074. return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
  6075. PyUnicode_GET_LENGTH(unicode));
  6076. /* Non-Latin-1 characters present. Defer to above function to
  6077. raise the exception. */
  6078. return unicode_encode_ucs1(unicode, errors, 256);
  6079. }
  6080. PyObject*
  6081. PyUnicode_AsLatin1String(PyObject *unicode)
  6082. {
  6083. return _PyUnicode_AsLatin1String(unicode, NULL);
  6084. }
  6085. /* --- 7-bit ASCII Codec -------------------------------------------------- */
  6086. PyObject *
  6087. PyUnicode_DecodeASCII(const char *s,
  6088. Py_ssize_t size,
  6089. const char *errors)
  6090. {
  6091. const char *starts = s;
  6092. const char *e = s + size;
  6093. PyObject *error_handler_obj = NULL;
  6094. PyObject *exc = NULL;
  6095. _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
  6096. if (size == 0)
  6097. _Py_RETURN_UNICODE_EMPTY();
  6098. /* ASCII is equivalent to the first 128 ordinals in Unicode. */
  6099. if (size == 1 && (unsigned char)s[0] < 128) {
  6100. return get_latin1_char((unsigned char)s[0]);
  6101. }
  6102. // Shortcut for simple case
  6103. PyObject *u = PyUnicode_New(size, 127);
  6104. if (u == NULL) {
  6105. return NULL;
  6106. }
  6107. Py_ssize_t outpos = ascii_decode(s, e, PyUnicode_1BYTE_DATA(u));
  6108. if (outpos == size) {
  6109. return u;
  6110. }
  6111. _PyUnicodeWriter writer;
  6112. _PyUnicodeWriter_InitWithBuffer(&writer, u);
  6113. writer.pos = outpos;
  6114. s += outpos;
  6115. int kind = writer.kind;
  6116. void *data = writer.data;
  6117. Py_ssize_t startinpos, endinpos;
  6118. while (s < e) {
  6119. unsigned char c = (unsigned char)*s;
  6120. if (c < 128) {
  6121. PyUnicode_WRITE(kind, data, writer.pos, c);
  6122. writer.pos++;
  6123. ++s;
  6124. continue;
  6125. }
  6126. /* byte outsize range 0x00..0x7f: call the error handler */
  6127. if (error_handler == _Py_ERROR_UNKNOWN)
  6128. error_handler = _Py_GetErrorHandler(errors);
  6129. switch (error_handler)
  6130. {
  6131. case _Py_ERROR_REPLACE:
  6132. case _Py_ERROR_SURROGATEESCAPE:
  6133. /* Fast-path: the error handler only writes one character,
  6134. but we may switch to UCS2 at the first write */
  6135. if (_PyUnicodeWriter_PrepareKind(&writer, PyUnicode_2BYTE_KIND) < 0)
  6136. goto onError;
  6137. kind = writer.kind;
  6138. data = writer.data;
  6139. if (error_handler == _Py_ERROR_REPLACE)
  6140. PyUnicode_WRITE(kind, data, writer.pos, 0xfffd);
  6141. else
  6142. PyUnicode_WRITE(kind, data, writer.pos, c + 0xdc00);
  6143. writer.pos++;
  6144. ++s;
  6145. break;
  6146. case _Py_ERROR_IGNORE:
  6147. ++s;
  6148. break;
  6149. default:
  6150. startinpos = s-starts;
  6151. endinpos = startinpos + 1;
  6152. if (unicode_decode_call_errorhandler_writer(
  6153. errors, &error_handler_obj,
  6154. "ascii", "ordinal not in range(128)",
  6155. &starts, &e, &startinpos, &endinpos, &exc, &s,
  6156. &writer))
  6157. goto onError;
  6158. kind = writer.kind;
  6159. data = writer.data;
  6160. }
  6161. }
  6162. Py_XDECREF(error_handler_obj);
  6163. Py_XDECREF(exc);
  6164. return _PyUnicodeWriter_Finish(&writer);
  6165. onError:
  6166. _PyUnicodeWriter_Dealloc(&writer);
  6167. Py_XDECREF(error_handler_obj);
  6168. Py_XDECREF(exc);
  6169. return NULL;
  6170. }
  6171. PyObject *
  6172. _PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
  6173. {
  6174. if (!PyUnicode_Check(unicode)) {
  6175. PyErr_BadArgument();
  6176. return NULL;
  6177. }
  6178. /* Fast path: if it is an ASCII-only string, construct bytes object
  6179. directly. Else defer to above function to raise the exception. */
  6180. if (PyUnicode_IS_ASCII(unicode))
  6181. return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
  6182. PyUnicode_GET_LENGTH(unicode));
  6183. return unicode_encode_ucs1(unicode, errors, 128);
  6184. }
  6185. PyObject *
  6186. PyUnicode_AsASCIIString(PyObject *unicode)
  6187. {
  6188. return _PyUnicode_AsASCIIString(unicode, NULL);
  6189. }
  6190. #ifdef MS_WINDOWS
  6191. /* --- MBCS codecs for Windows -------------------------------------------- */
  6192. #if SIZEOF_INT < SIZEOF_SIZE_T
  6193. #define NEED_RETRY
  6194. #endif
  6195. /* INT_MAX is the theoretical largest chunk (or INT_MAX / 2 when
  6196. transcoding from UTF-16), but INT_MAX / 4 performs better in
  6197. both cases also and avoids partial characters overrunning the
  6198. length limit in MultiByteToWideChar on Windows */
  6199. #define DECODING_CHUNK_SIZE (INT_MAX/4)
  6200. #ifndef WC_ERR_INVALID_CHARS
  6201. # define WC_ERR_INVALID_CHARS 0x0080
  6202. #endif
  6203. static const char*
  6204. code_page_name(UINT code_page, PyObject **obj)
  6205. {
  6206. *obj = NULL;
  6207. if (code_page == CP_ACP)
  6208. return "mbcs";
  6209. if (code_page == CP_UTF7)
  6210. return "CP_UTF7";
  6211. if (code_page == CP_UTF8)
  6212. return "CP_UTF8";
  6213. *obj = PyBytes_FromFormat("cp%u", code_page);
  6214. if (*obj == NULL)
  6215. return NULL;
  6216. return PyBytes_AS_STRING(*obj);
  6217. }
  6218. static DWORD
  6219. decode_code_page_flags(UINT code_page)
  6220. {
  6221. if (code_page == CP_UTF7) {
  6222. /* The CP_UTF7 decoder only supports flags=0 */
  6223. return 0;
  6224. }
  6225. else
  6226. return MB_ERR_INVALID_CHARS;
  6227. }
  6228. /*
  6229. * Decode a byte string from a Windows code page into unicode object in strict
  6230. * mode.
  6231. *
  6232. * Returns consumed size if succeed, returns -2 on decode error, or raise an
  6233. * OSError and returns -1 on other error.
  6234. */
  6235. static int
  6236. decode_code_page_strict(UINT code_page,
  6237. wchar_t **buf,
  6238. Py_ssize_t *bufsize,
  6239. const char *in,
  6240. int insize)
  6241. {
  6242. DWORD flags = MB_ERR_INVALID_CHARS;
  6243. wchar_t *out;
  6244. DWORD outsize;
  6245. /* First get the size of the result */
  6246. assert(insize > 0);
  6247. while ((outsize = MultiByteToWideChar(code_page, flags,
  6248. in, insize, NULL, 0)) <= 0)
  6249. {
  6250. if (!flags || GetLastError() != ERROR_INVALID_FLAGS) {
  6251. goto error;
  6252. }
  6253. /* For some code pages (e.g. UTF-7) flags must be set to 0. */
  6254. flags = 0;
  6255. }
  6256. /* Extend a wchar_t* buffer */
  6257. Py_ssize_t n = *bufsize; /* Get the current length */
  6258. if (widechar_resize(buf, bufsize, n + outsize) < 0) {
  6259. return -1;
  6260. }
  6261. out = *buf + n;
  6262. /* Do the conversion */
  6263. outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
  6264. if (outsize <= 0)
  6265. goto error;
  6266. return insize;
  6267. error:
  6268. if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
  6269. return -2;
  6270. PyErr_SetFromWindowsErr(0);
  6271. return -1;
  6272. }
  6273. /*
  6274. * Decode a byte string from a code page into unicode object with an error
  6275. * handler.
  6276. *
  6277. * Returns consumed size if succeed, or raise an OSError or
  6278. * UnicodeDecodeError exception and returns -1 on error.
  6279. */
  6280. static int
  6281. decode_code_page_errors(UINT code_page,
  6282. wchar_t **buf,
  6283. Py_ssize_t *bufsize,
  6284. const char *in, const int size,
  6285. const char *errors, int final)
  6286. {
  6287. const char *startin = in;
  6288. const char *endin = in + size;
  6289. DWORD flags = MB_ERR_INVALID_CHARS;
  6290. /* Ideally, we should get reason from FormatMessage. This is the Windows
  6291. 2000 English version of the message. */
  6292. const char *reason = "No mapping for the Unicode character exists "
  6293. "in the target code page.";
  6294. /* each step cannot decode more than 1 character, but a character can be
  6295. represented as a surrogate pair */
  6296. wchar_t buffer[2], *out;
  6297. int insize;
  6298. Py_ssize_t outsize;
  6299. PyObject *errorHandler = NULL;
  6300. PyObject *exc = NULL;
  6301. PyObject *encoding_obj = NULL;
  6302. const char *encoding;
  6303. DWORD err;
  6304. int ret = -1;
  6305. assert(size > 0);
  6306. encoding = code_page_name(code_page, &encoding_obj);
  6307. if (encoding == NULL)
  6308. return -1;
  6309. if ((errors == NULL || strcmp(errors, "strict") == 0) && final) {
  6310. /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
  6311. UnicodeDecodeError. */
  6312. make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
  6313. if (exc != NULL) {
  6314. PyCodec_StrictErrors(exc);
  6315. Py_CLEAR(exc);
  6316. }
  6317. goto error;
  6318. }
  6319. /* Extend a wchar_t* buffer */
  6320. Py_ssize_t n = *bufsize; /* Get the current length */
  6321. if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
  6322. PyErr_NoMemory();
  6323. goto error;
  6324. }
  6325. if (widechar_resize(buf, bufsize, n + size * Py_ARRAY_LENGTH(buffer)) < 0) {
  6326. goto error;
  6327. }
  6328. out = *buf + n;
  6329. /* Decode the byte string character per character */
  6330. while (in < endin)
  6331. {
  6332. /* Decode a character */
  6333. insize = 1;
  6334. do
  6335. {
  6336. outsize = MultiByteToWideChar(code_page, flags,
  6337. in, insize,
  6338. buffer, Py_ARRAY_LENGTH(buffer));
  6339. if (outsize > 0)
  6340. break;
  6341. err = GetLastError();
  6342. if (err == ERROR_INVALID_FLAGS && flags) {
  6343. /* For some code pages (e.g. UTF-7) flags must be set to 0. */
  6344. flags = 0;
  6345. continue;
  6346. }
  6347. if (err != ERROR_NO_UNICODE_TRANSLATION
  6348. && err != ERROR_INSUFFICIENT_BUFFER)
  6349. {
  6350. PyErr_SetFromWindowsErr(err);
  6351. goto error;
  6352. }
  6353. insize++;
  6354. }
  6355. /* 4=maximum length of a UTF-8 sequence */
  6356. while (insize <= 4 && (in + insize) <= endin);
  6357. if (outsize <= 0) {
  6358. Py_ssize_t startinpos, endinpos, outpos;
  6359. /* last character in partial decode? */
  6360. if (in + insize >= endin && !final)
  6361. break;
  6362. startinpos = in - startin;
  6363. endinpos = startinpos + 1;
  6364. outpos = out - *buf;
  6365. if (unicode_decode_call_errorhandler_wchar(
  6366. errors, &errorHandler,
  6367. encoding, reason,
  6368. &startin, &endin, &startinpos, &endinpos, &exc, &in,
  6369. buf, bufsize, &outpos))
  6370. {
  6371. goto error;
  6372. }
  6373. out = *buf + outpos;
  6374. }
  6375. else {
  6376. in += insize;
  6377. memcpy(out, buffer, outsize * sizeof(wchar_t));
  6378. out += outsize;
  6379. }
  6380. }
  6381. /* Shrink the buffer */
  6382. assert(out - *buf <= *bufsize);
  6383. *bufsize = out - *buf;
  6384. /* (in - startin) <= size and size is an int */
  6385. ret = Py_SAFE_DOWNCAST(in - startin, Py_ssize_t, int);
  6386. error:
  6387. Py_XDECREF(encoding_obj);
  6388. Py_XDECREF(errorHandler);
  6389. Py_XDECREF(exc);
  6390. return ret;
  6391. }
  6392. static PyObject *
  6393. decode_code_page_stateful(int code_page,
  6394. const char *s, Py_ssize_t size,
  6395. const char *errors, Py_ssize_t *consumed)
  6396. {
  6397. wchar_t *buf = NULL;
  6398. Py_ssize_t bufsize = 0;
  6399. int chunk_size, final, converted, done;
  6400. if (code_page < 0) {
  6401. PyErr_SetString(PyExc_ValueError, "invalid code page number");
  6402. return NULL;
  6403. }
  6404. if (size < 0) {
  6405. PyErr_BadInternalCall();
  6406. return NULL;
  6407. }
  6408. if (consumed)
  6409. *consumed = 0;
  6410. do
  6411. {
  6412. #ifdef NEED_RETRY
  6413. if (size > DECODING_CHUNK_SIZE) {
  6414. chunk_size = DECODING_CHUNK_SIZE;
  6415. final = 0;
  6416. done = 0;
  6417. }
  6418. else
  6419. #endif
  6420. {
  6421. chunk_size = (int)size;
  6422. final = (consumed == NULL);
  6423. done = 1;
  6424. }
  6425. if (chunk_size == 0 && done) {
  6426. if (buf != NULL)
  6427. break;
  6428. _Py_RETURN_UNICODE_EMPTY();
  6429. }
  6430. converted = decode_code_page_strict(code_page, &buf, &bufsize,
  6431. s, chunk_size);
  6432. if (converted == -2)
  6433. converted = decode_code_page_errors(code_page, &buf, &bufsize,
  6434. s, chunk_size,
  6435. errors, final);
  6436. assert(converted != 0 || done);
  6437. if (converted < 0) {
  6438. PyMem_Free(buf);
  6439. return NULL;
  6440. }
  6441. if (consumed)
  6442. *consumed += converted;
  6443. s += converted;
  6444. size -= converted;
  6445. } while (!done);
  6446. PyObject *v = PyUnicode_FromWideChar(buf, bufsize);
  6447. PyMem_Free(buf);
  6448. return v;
  6449. }
  6450. PyObject *
  6451. PyUnicode_DecodeCodePageStateful(int code_page,
  6452. const char *s,
  6453. Py_ssize_t size,
  6454. const char *errors,
  6455. Py_ssize_t *consumed)
  6456. {
  6457. return decode_code_page_stateful(code_page, s, size, errors, consumed);
  6458. }
  6459. PyObject *
  6460. PyUnicode_DecodeMBCSStateful(const char *s,
  6461. Py_ssize_t size,
  6462. const char *errors,
  6463. Py_ssize_t *consumed)
  6464. {
  6465. return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
  6466. }
  6467. PyObject *
  6468. PyUnicode_DecodeMBCS(const char *s,
  6469. Py_ssize_t size,
  6470. const char *errors)
  6471. {
  6472. return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
  6473. }
  6474. static DWORD
  6475. encode_code_page_flags(UINT code_page, const char *errors)
  6476. {
  6477. if (code_page == CP_UTF8) {
  6478. return WC_ERR_INVALID_CHARS;
  6479. }
  6480. else if (code_page == CP_UTF7) {
  6481. /* CP_UTF7 only supports flags=0 */
  6482. return 0;
  6483. }
  6484. else {
  6485. if (errors != NULL && strcmp(errors, "replace") == 0)
  6486. return 0;
  6487. else
  6488. return WC_NO_BEST_FIT_CHARS;
  6489. }
  6490. }
  6491. /*
  6492. * Encode a Unicode string to a Windows code page into a byte string in strict
  6493. * mode.
  6494. *
  6495. * Returns consumed characters if succeed, returns -2 on encode error, or raise
  6496. * an OSError and returns -1 on other error.
  6497. */
  6498. static int
  6499. encode_code_page_strict(UINT code_page, PyObject **outbytes,
  6500. PyObject *unicode, Py_ssize_t offset, int len,
  6501. const char* errors)
  6502. {
  6503. BOOL usedDefaultChar = FALSE;
  6504. BOOL *pusedDefaultChar = &usedDefaultChar;
  6505. int outsize;
  6506. wchar_t *p;
  6507. Py_ssize_t size;
  6508. const DWORD flags = encode_code_page_flags(code_page, NULL);
  6509. char *out;
  6510. /* Create a substring so that we can get the UTF-16 representation
  6511. of just the slice under consideration. */
  6512. PyObject *substring;
  6513. int ret = -1;
  6514. assert(len > 0);
  6515. if (code_page != CP_UTF8 && code_page != CP_UTF7)
  6516. pusedDefaultChar = &usedDefaultChar;
  6517. else
  6518. pusedDefaultChar = NULL;
  6519. substring = PyUnicode_Substring(unicode, offset, offset+len);
  6520. if (substring == NULL)
  6521. return -1;
  6522. p = PyUnicode_AsWideCharString(substring, &size);
  6523. Py_CLEAR(substring);
  6524. if (p == NULL) {
  6525. return -1;
  6526. }
  6527. assert(size <= INT_MAX);
  6528. /* First get the size of the result */
  6529. outsize = WideCharToMultiByte(code_page, flags,
  6530. p, (int)size,
  6531. NULL, 0,
  6532. NULL, pusedDefaultChar);
  6533. if (outsize <= 0)
  6534. goto error;
  6535. /* If we used a default char, then we failed! */
  6536. if (pusedDefaultChar && *pusedDefaultChar) {
  6537. ret = -2;
  6538. goto done;
  6539. }
  6540. if (*outbytes == NULL) {
  6541. /* Create string object */
  6542. *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
  6543. if (*outbytes == NULL) {
  6544. goto done;
  6545. }
  6546. out = PyBytes_AS_STRING(*outbytes);
  6547. }
  6548. else {
  6549. /* Extend string object */
  6550. const Py_ssize_t n = PyBytes_Size(*outbytes);
  6551. if (outsize > PY_SSIZE_T_MAX - n) {
  6552. PyErr_NoMemory();
  6553. goto done;
  6554. }
  6555. if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
  6556. goto done;
  6557. }
  6558. out = PyBytes_AS_STRING(*outbytes) + n;
  6559. }
  6560. /* Do the conversion */
  6561. outsize = WideCharToMultiByte(code_page, flags,
  6562. p, (int)size,
  6563. out, outsize,
  6564. NULL, pusedDefaultChar);
  6565. if (outsize <= 0)
  6566. goto error;
  6567. if (pusedDefaultChar && *pusedDefaultChar) {
  6568. ret = -2;
  6569. goto done;
  6570. }
  6571. ret = 0;
  6572. done:
  6573. PyMem_Free(p);
  6574. return ret;
  6575. error:
  6576. if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION) {
  6577. ret = -2;
  6578. goto done;
  6579. }
  6580. PyErr_SetFromWindowsErr(0);
  6581. goto done;
  6582. }
  6583. /*
  6584. * Encode a Unicode string to a Windows code page into a byte string using an
  6585. * error handler.
  6586. *
  6587. * Returns consumed characters if succeed, or raise an OSError and returns
  6588. * -1 on other error.
  6589. */
  6590. static int
  6591. encode_code_page_errors(UINT code_page, PyObject **outbytes,
  6592. PyObject *unicode, Py_ssize_t unicode_offset,
  6593. Py_ssize_t insize, const char* errors)
  6594. {
  6595. const DWORD flags = encode_code_page_flags(code_page, errors);
  6596. Py_ssize_t pos = unicode_offset;
  6597. Py_ssize_t endin = unicode_offset + insize;
  6598. /* Ideally, we should get reason from FormatMessage. This is the Windows
  6599. 2000 English version of the message. */
  6600. const char *reason = "invalid character";
  6601. /* 4=maximum length of a UTF-8 sequence */
  6602. char buffer[4];
  6603. BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
  6604. Py_ssize_t outsize;
  6605. char *out;
  6606. PyObject *errorHandler = NULL;
  6607. PyObject *exc = NULL;
  6608. PyObject *encoding_obj = NULL;
  6609. const char *encoding;
  6610. Py_ssize_t newpos, newoutsize;
  6611. PyObject *rep;
  6612. int ret = -1;
  6613. assert(insize > 0);
  6614. encoding = code_page_name(code_page, &encoding_obj);
  6615. if (encoding == NULL)
  6616. return -1;
  6617. if (errors == NULL || strcmp(errors, "strict") == 0) {
  6618. /* The last error was ERROR_NO_UNICODE_TRANSLATION,
  6619. then we raise a UnicodeEncodeError. */
  6620. make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
  6621. if (exc != NULL) {
  6622. PyCodec_StrictErrors(exc);
  6623. Py_DECREF(exc);
  6624. }
  6625. Py_XDECREF(encoding_obj);
  6626. return -1;
  6627. }
  6628. if (code_page != CP_UTF8 && code_page != CP_UTF7)
  6629. pusedDefaultChar = &usedDefaultChar;
  6630. else
  6631. pusedDefaultChar = NULL;
  6632. if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
  6633. PyErr_NoMemory();
  6634. goto error;
  6635. }
  6636. outsize = insize * Py_ARRAY_LENGTH(buffer);
  6637. if (*outbytes == NULL) {
  6638. /* Create string object */
  6639. *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
  6640. if (*outbytes == NULL)
  6641. goto error;
  6642. out = PyBytes_AS_STRING(*outbytes);
  6643. }
  6644. else {
  6645. /* Extend string object */
  6646. Py_ssize_t n = PyBytes_Size(*outbytes);
  6647. if (n > PY_SSIZE_T_MAX - outsize) {
  6648. PyErr_NoMemory();
  6649. goto error;
  6650. }
  6651. if (_PyBytes_Resize(outbytes, n + outsize) < 0)
  6652. goto error;
  6653. out = PyBytes_AS_STRING(*outbytes) + n;
  6654. }
  6655. /* Encode the string character per character */
  6656. while (pos < endin)
  6657. {
  6658. Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
  6659. wchar_t chars[2];
  6660. int charsize;
  6661. if (ch < 0x10000) {
  6662. chars[0] = (wchar_t)ch;
  6663. charsize = 1;
  6664. }
  6665. else {
  6666. chars[0] = Py_UNICODE_HIGH_SURROGATE(ch);
  6667. chars[1] = Py_UNICODE_LOW_SURROGATE(ch);
  6668. charsize = 2;
  6669. }
  6670. outsize = WideCharToMultiByte(code_page, flags,
  6671. chars, charsize,
  6672. buffer, Py_ARRAY_LENGTH(buffer),
  6673. NULL, pusedDefaultChar);
  6674. if (outsize > 0) {
  6675. if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
  6676. {
  6677. pos++;
  6678. memcpy(out, buffer, outsize);
  6679. out += outsize;
  6680. continue;
  6681. }
  6682. }
  6683. else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
  6684. PyErr_SetFromWindowsErr(0);
  6685. goto error;
  6686. }
  6687. rep = unicode_encode_call_errorhandler(
  6688. errors, &errorHandler, encoding, reason,
  6689. unicode, &exc,
  6690. pos, pos + 1, &newpos);
  6691. if (rep == NULL)
  6692. goto error;
  6693. Py_ssize_t morebytes = pos - newpos;
  6694. if (PyBytes_Check(rep)) {
  6695. outsize = PyBytes_GET_SIZE(rep);
  6696. morebytes += outsize;
  6697. if (morebytes > 0) {
  6698. Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
  6699. newoutsize = PyBytes_GET_SIZE(*outbytes) + morebytes;
  6700. if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
  6701. Py_DECREF(rep);
  6702. goto error;
  6703. }
  6704. out = PyBytes_AS_STRING(*outbytes) + offset;
  6705. }
  6706. memcpy(out, PyBytes_AS_STRING(rep), outsize);
  6707. out += outsize;
  6708. }
  6709. else {
  6710. Py_ssize_t i;
  6711. int kind;
  6712. const void *data;
  6713. outsize = PyUnicode_GET_LENGTH(rep);
  6714. morebytes += outsize;
  6715. if (morebytes > 0) {
  6716. Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
  6717. newoutsize = PyBytes_GET_SIZE(*outbytes) + morebytes;
  6718. if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
  6719. Py_DECREF(rep);
  6720. goto error;
  6721. }
  6722. out = PyBytes_AS_STRING(*outbytes) + offset;
  6723. }
  6724. kind = PyUnicode_KIND(rep);
  6725. data = PyUnicode_DATA(rep);
  6726. for (i=0; i < outsize; i++) {
  6727. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  6728. if (ch > 127) {
  6729. raise_encode_exception(&exc,
  6730. encoding, unicode,
  6731. pos, pos + 1,
  6732. "unable to encode error handler result to ASCII");
  6733. Py_DECREF(rep);
  6734. goto error;
  6735. }
  6736. *out = (unsigned char)ch;
  6737. out++;
  6738. }
  6739. }
  6740. pos = newpos;
  6741. Py_DECREF(rep);
  6742. }
  6743. /* write a NUL byte */
  6744. *out = 0;
  6745. outsize = out - PyBytes_AS_STRING(*outbytes);
  6746. assert(outsize <= PyBytes_GET_SIZE(*outbytes));
  6747. if (_PyBytes_Resize(outbytes, outsize) < 0)
  6748. goto error;
  6749. ret = 0;
  6750. error:
  6751. Py_XDECREF(encoding_obj);
  6752. Py_XDECREF(errorHandler);
  6753. Py_XDECREF(exc);
  6754. return ret;
  6755. }
  6756. static PyObject *
  6757. encode_code_page(int code_page,
  6758. PyObject *unicode,
  6759. const char *errors)
  6760. {
  6761. Py_ssize_t len;
  6762. PyObject *outbytes = NULL;
  6763. Py_ssize_t offset;
  6764. int chunk_len, ret, done;
  6765. if (!PyUnicode_Check(unicode)) {
  6766. PyErr_BadArgument();
  6767. return NULL;
  6768. }
  6769. len = PyUnicode_GET_LENGTH(unicode);
  6770. if (code_page < 0) {
  6771. PyErr_SetString(PyExc_ValueError, "invalid code page number");
  6772. return NULL;
  6773. }
  6774. if (len == 0)
  6775. return PyBytes_FromStringAndSize(NULL, 0);
  6776. offset = 0;
  6777. do
  6778. {
  6779. #ifdef NEED_RETRY
  6780. if (len > DECODING_CHUNK_SIZE) {
  6781. chunk_len = DECODING_CHUNK_SIZE;
  6782. done = 0;
  6783. }
  6784. else
  6785. #endif
  6786. {
  6787. chunk_len = (int)len;
  6788. done = 1;
  6789. }
  6790. ret = encode_code_page_strict(code_page, &outbytes,
  6791. unicode, offset, chunk_len,
  6792. errors);
  6793. if (ret == -2)
  6794. ret = encode_code_page_errors(code_page, &outbytes,
  6795. unicode, offset,
  6796. chunk_len, errors);
  6797. if (ret < 0) {
  6798. Py_XDECREF(outbytes);
  6799. return NULL;
  6800. }
  6801. offset += chunk_len;
  6802. len -= chunk_len;
  6803. } while (!done);
  6804. return outbytes;
  6805. }
  6806. PyObject *
  6807. PyUnicode_EncodeCodePage(int code_page,
  6808. PyObject *unicode,
  6809. const char *errors)
  6810. {
  6811. return encode_code_page(code_page, unicode, errors);
  6812. }
  6813. PyObject *
  6814. PyUnicode_AsMBCSString(PyObject *unicode)
  6815. {
  6816. return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
  6817. }
  6818. #undef NEED_RETRY
  6819. #endif /* MS_WINDOWS */
  6820. /* --- Character Mapping Codec -------------------------------------------- */
  6821. static int
  6822. charmap_decode_string(const char *s,
  6823. Py_ssize_t size,
  6824. PyObject *mapping,
  6825. const char *errors,
  6826. _PyUnicodeWriter *writer)
  6827. {
  6828. const char *starts = s;
  6829. const char *e;
  6830. Py_ssize_t startinpos, endinpos;
  6831. PyObject *errorHandler = NULL, *exc = NULL;
  6832. Py_ssize_t maplen;
  6833. int mapkind;
  6834. const void *mapdata;
  6835. Py_UCS4 x;
  6836. unsigned char ch;
  6837. maplen = PyUnicode_GET_LENGTH(mapping);
  6838. mapdata = PyUnicode_DATA(mapping);
  6839. mapkind = PyUnicode_KIND(mapping);
  6840. e = s + size;
  6841. if (mapkind == PyUnicode_1BYTE_KIND && maplen >= 256) {
  6842. /* fast-path for cp037, cp500 and iso8859_1 encodings. iso8859_1
  6843. * is disabled in encoding aliases, latin1 is preferred because
  6844. * its implementation is faster. */
  6845. const Py_UCS1 *mapdata_ucs1 = (const Py_UCS1 *)mapdata;
  6846. Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
  6847. Py_UCS4 maxchar = writer->maxchar;
  6848. assert (writer->kind == PyUnicode_1BYTE_KIND);
  6849. while (s < e) {
  6850. ch = *s;
  6851. x = mapdata_ucs1[ch];
  6852. if (x > maxchar) {
  6853. if (_PyUnicodeWriter_Prepare(writer, 1, 0xff) == -1)
  6854. goto onError;
  6855. maxchar = writer->maxchar;
  6856. outdata = (Py_UCS1 *)writer->data;
  6857. }
  6858. outdata[writer->pos] = x;
  6859. writer->pos++;
  6860. ++s;
  6861. }
  6862. return 0;
  6863. }
  6864. while (s < e) {
  6865. if (mapkind == PyUnicode_2BYTE_KIND && maplen >= 256) {
  6866. int outkind = writer->kind;
  6867. const Py_UCS2 *mapdata_ucs2 = (const Py_UCS2 *)mapdata;
  6868. if (outkind == PyUnicode_1BYTE_KIND) {
  6869. Py_UCS1 *outdata = (Py_UCS1 *)writer->data;
  6870. Py_UCS4 maxchar = writer->maxchar;
  6871. while (s < e) {
  6872. ch = *s;
  6873. x = mapdata_ucs2[ch];
  6874. if (x > maxchar)
  6875. goto Error;
  6876. outdata[writer->pos] = x;
  6877. writer->pos++;
  6878. ++s;
  6879. }
  6880. break;
  6881. }
  6882. else if (outkind == PyUnicode_2BYTE_KIND) {
  6883. Py_UCS2 *outdata = (Py_UCS2 *)writer->data;
  6884. while (s < e) {
  6885. ch = *s;
  6886. x = mapdata_ucs2[ch];
  6887. if (x == 0xFFFE)
  6888. goto Error;
  6889. outdata[writer->pos] = x;
  6890. writer->pos++;
  6891. ++s;
  6892. }
  6893. break;
  6894. }
  6895. }
  6896. ch = *s;
  6897. if (ch < maplen)
  6898. x = PyUnicode_READ(mapkind, mapdata, ch);
  6899. else
  6900. x = 0xfffe; /* invalid value */
  6901. Error:
  6902. if (x == 0xfffe)
  6903. {
  6904. /* undefined mapping */
  6905. startinpos = s-starts;
  6906. endinpos = startinpos+1;
  6907. if (unicode_decode_call_errorhandler_writer(
  6908. errors, &errorHandler,
  6909. "charmap", "character maps to <undefined>",
  6910. &starts, &e, &startinpos, &endinpos, &exc, &s,
  6911. writer)) {
  6912. goto onError;
  6913. }
  6914. continue;
  6915. }
  6916. if (_PyUnicodeWriter_WriteCharInline(writer, x) < 0)
  6917. goto onError;
  6918. ++s;
  6919. }
  6920. Py_XDECREF(errorHandler);
  6921. Py_XDECREF(exc);
  6922. return 0;
  6923. onError:
  6924. Py_XDECREF(errorHandler);
  6925. Py_XDECREF(exc);
  6926. return -1;
  6927. }
  6928. static int
  6929. charmap_decode_mapping(const char *s,
  6930. Py_ssize_t size,
  6931. PyObject *mapping,
  6932. const char *errors,
  6933. _PyUnicodeWriter *writer)
  6934. {
  6935. const char *starts = s;
  6936. const char *e;
  6937. Py_ssize_t startinpos, endinpos;
  6938. PyObject *errorHandler = NULL, *exc = NULL;
  6939. unsigned char ch;
  6940. PyObject *key, *item = NULL;
  6941. e = s + size;
  6942. while (s < e) {
  6943. ch = *s;
  6944. /* Get mapping (char ordinal -> integer, Unicode char or None) */
  6945. key = PyLong_FromLong((long)ch);
  6946. if (key == NULL)
  6947. goto onError;
  6948. item = PyObject_GetItem(mapping, key);
  6949. Py_DECREF(key);
  6950. if (item == NULL) {
  6951. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  6952. /* No mapping found means: mapping is undefined. */
  6953. PyErr_Clear();
  6954. goto Undefined;
  6955. } else
  6956. goto onError;
  6957. }
  6958. /* Apply mapping */
  6959. if (item == Py_None)
  6960. goto Undefined;
  6961. if (PyLong_Check(item)) {
  6962. long value = PyLong_AS_LONG(item);
  6963. if (value == 0xFFFE)
  6964. goto Undefined;
  6965. if (value < 0 || value > MAX_UNICODE) {
  6966. PyErr_Format(PyExc_TypeError,
  6967. "character mapping must be in range(0x%x)",
  6968. (unsigned long)MAX_UNICODE + 1);
  6969. goto onError;
  6970. }
  6971. if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
  6972. goto onError;
  6973. }
  6974. else if (PyUnicode_Check(item)) {
  6975. if (PyUnicode_GET_LENGTH(item) == 1) {
  6976. Py_UCS4 value = PyUnicode_READ_CHAR(item, 0);
  6977. if (value == 0xFFFE)
  6978. goto Undefined;
  6979. if (_PyUnicodeWriter_WriteCharInline(writer, value) < 0)
  6980. goto onError;
  6981. }
  6982. else {
  6983. writer->overallocate = 1;
  6984. if (_PyUnicodeWriter_WriteStr(writer, item) == -1)
  6985. goto onError;
  6986. }
  6987. }
  6988. else {
  6989. /* wrong return value */
  6990. PyErr_SetString(PyExc_TypeError,
  6991. "character mapping must return integer, None or str");
  6992. goto onError;
  6993. }
  6994. Py_CLEAR(item);
  6995. ++s;
  6996. continue;
  6997. Undefined:
  6998. /* undefined mapping */
  6999. Py_CLEAR(item);
  7000. startinpos = s-starts;
  7001. endinpos = startinpos+1;
  7002. if (unicode_decode_call_errorhandler_writer(
  7003. errors, &errorHandler,
  7004. "charmap", "character maps to <undefined>",
  7005. &starts, &e, &startinpos, &endinpos, &exc, &s,
  7006. writer)) {
  7007. goto onError;
  7008. }
  7009. }
  7010. Py_XDECREF(errorHandler);
  7011. Py_XDECREF(exc);
  7012. return 0;
  7013. onError:
  7014. Py_XDECREF(item);
  7015. Py_XDECREF(errorHandler);
  7016. Py_XDECREF(exc);
  7017. return -1;
  7018. }
  7019. PyObject *
  7020. PyUnicode_DecodeCharmap(const char *s,
  7021. Py_ssize_t size,
  7022. PyObject *mapping,
  7023. const char *errors)
  7024. {
  7025. _PyUnicodeWriter writer;
  7026. /* Default to Latin-1 */
  7027. if (mapping == NULL)
  7028. return PyUnicode_DecodeLatin1(s, size, errors);
  7029. if (size == 0)
  7030. _Py_RETURN_UNICODE_EMPTY();
  7031. _PyUnicodeWriter_Init(&writer);
  7032. writer.min_length = size;
  7033. if (_PyUnicodeWriter_Prepare(&writer, writer.min_length, 127) == -1)
  7034. goto onError;
  7035. if (PyUnicode_CheckExact(mapping)) {
  7036. if (charmap_decode_string(s, size, mapping, errors, &writer) < 0)
  7037. goto onError;
  7038. }
  7039. else {
  7040. if (charmap_decode_mapping(s, size, mapping, errors, &writer) < 0)
  7041. goto onError;
  7042. }
  7043. return _PyUnicodeWriter_Finish(&writer);
  7044. onError:
  7045. _PyUnicodeWriter_Dealloc(&writer);
  7046. return NULL;
  7047. }
  7048. /* Charmap encoding: the lookup table */
  7049. /*[clinic input]
  7050. class EncodingMap "struct encoding_map *" "&EncodingMapType"
  7051. [clinic start generated code]*/
  7052. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=14e46bbb6c522d22]*/
  7053. struct encoding_map {
  7054. PyObject_HEAD
  7055. unsigned char level1[32];
  7056. int count2, count3;
  7057. unsigned char level23[1];
  7058. };
  7059. /*[clinic input]
  7060. EncodingMap.size
  7061. Return the size (in bytes) of this object.
  7062. [clinic start generated code]*/
  7063. static PyObject *
  7064. EncodingMap_size_impl(struct encoding_map *self)
  7065. /*[clinic end generated code: output=c4c969e4c99342a4 input=004ff13f26bb5366]*/
  7066. {
  7067. return PyLong_FromLong((sizeof(*self) - 1) + 16*self->count2 +
  7068. 128*self->count3);
  7069. }
  7070. static PyMethodDef encoding_map_methods[] = {
  7071. ENCODINGMAP_SIZE_METHODDEF
  7072. {NULL, NULL}
  7073. };
  7074. static PyTypeObject EncodingMapType = {
  7075. PyVarObject_HEAD_INIT(NULL, 0)
  7076. .tp_name = "EncodingMap",
  7077. .tp_basicsize = sizeof(struct encoding_map),
  7078. /* methods */
  7079. .tp_flags = Py_TPFLAGS_DEFAULT,
  7080. .tp_methods = encoding_map_methods,
  7081. };
  7082. PyObject*
  7083. PyUnicode_BuildEncodingMap(PyObject* string)
  7084. {
  7085. PyObject *result;
  7086. struct encoding_map *mresult;
  7087. int i;
  7088. int need_dict = 0;
  7089. unsigned char level1[32];
  7090. unsigned char level2[512];
  7091. unsigned char *mlevel1, *mlevel2, *mlevel3;
  7092. int count2 = 0, count3 = 0;
  7093. int kind;
  7094. const void *data;
  7095. Py_ssize_t length;
  7096. Py_UCS4 ch;
  7097. if (!PyUnicode_Check(string) || !PyUnicode_GET_LENGTH(string)) {
  7098. PyErr_BadArgument();
  7099. return NULL;
  7100. }
  7101. kind = PyUnicode_KIND(string);
  7102. data = PyUnicode_DATA(string);
  7103. length = PyUnicode_GET_LENGTH(string);
  7104. length = Py_MIN(length, 256);
  7105. memset(level1, 0xFF, sizeof level1);
  7106. memset(level2, 0xFF, sizeof level2);
  7107. /* If there isn't a one-to-one mapping of NULL to \0,
  7108. or if there are non-BMP characters, we need to use
  7109. a mapping dictionary. */
  7110. if (PyUnicode_READ(kind, data, 0) != 0)
  7111. need_dict = 1;
  7112. for (i = 1; i < length; i++) {
  7113. int l1, l2;
  7114. ch = PyUnicode_READ(kind, data, i);
  7115. if (ch == 0 || ch > 0xFFFF) {
  7116. need_dict = 1;
  7117. break;
  7118. }
  7119. if (ch == 0xFFFE)
  7120. /* unmapped character */
  7121. continue;
  7122. l1 = ch >> 11;
  7123. l2 = ch >> 7;
  7124. if (level1[l1] == 0xFF)
  7125. level1[l1] = count2++;
  7126. if (level2[l2] == 0xFF)
  7127. level2[l2] = count3++;
  7128. }
  7129. if (count2 >= 0xFF || count3 >= 0xFF)
  7130. need_dict = 1;
  7131. if (need_dict) {
  7132. PyObject *result = PyDict_New();
  7133. if (!result)
  7134. return NULL;
  7135. for (i = 0; i < length; i++) {
  7136. Py_UCS4 c = PyUnicode_READ(kind, data, i);
  7137. PyObject *key = PyLong_FromLong(c);
  7138. if (key == NULL) {
  7139. Py_DECREF(result);
  7140. return NULL;
  7141. }
  7142. PyObject *value = PyLong_FromLong(i);
  7143. if (value == NULL) {
  7144. Py_DECREF(key);
  7145. Py_DECREF(result);
  7146. return NULL;
  7147. }
  7148. int rc = PyDict_SetItem(result, key, value);
  7149. Py_DECREF(key);
  7150. Py_DECREF(value);
  7151. if (rc < 0) {
  7152. Py_DECREF(result);
  7153. return NULL;
  7154. }
  7155. }
  7156. return result;
  7157. }
  7158. /* Create a three-level trie */
  7159. result = PyObject_Malloc(sizeof(struct encoding_map) +
  7160. 16*count2 + 128*count3 - 1);
  7161. if (!result) {
  7162. return PyErr_NoMemory();
  7163. }
  7164. _PyObject_Init(result, &EncodingMapType);
  7165. mresult = (struct encoding_map*)result;
  7166. mresult->count2 = count2;
  7167. mresult->count3 = count3;
  7168. mlevel1 = mresult->level1;
  7169. mlevel2 = mresult->level23;
  7170. mlevel3 = mresult->level23 + 16*count2;
  7171. memcpy(mlevel1, level1, 32);
  7172. memset(mlevel2, 0xFF, 16*count2);
  7173. memset(mlevel3, 0, 128*count3);
  7174. count3 = 0;
  7175. for (i = 1; i < length; i++) {
  7176. int o1, o2, o3, i2, i3;
  7177. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  7178. if (ch == 0xFFFE)
  7179. /* unmapped character */
  7180. continue;
  7181. o1 = ch>>11;
  7182. o2 = (ch>>7) & 0xF;
  7183. i2 = 16*mlevel1[o1] + o2;
  7184. if (mlevel2[i2] == 0xFF)
  7185. mlevel2[i2] = count3++;
  7186. o3 = ch & 0x7F;
  7187. i3 = 128*mlevel2[i2] + o3;
  7188. mlevel3[i3] = i;
  7189. }
  7190. return result;
  7191. }
  7192. static int
  7193. encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
  7194. {
  7195. struct encoding_map *map = (struct encoding_map*)mapping;
  7196. int l1 = c>>11;
  7197. int l2 = (c>>7) & 0xF;
  7198. int l3 = c & 0x7F;
  7199. int i;
  7200. if (c > 0xFFFF)
  7201. return -1;
  7202. if (c == 0)
  7203. return 0;
  7204. /* level 1*/
  7205. i = map->level1[l1];
  7206. if (i == 0xFF) {
  7207. return -1;
  7208. }
  7209. /* level 2*/
  7210. i = map->level23[16*i+l2];
  7211. if (i == 0xFF) {
  7212. return -1;
  7213. }
  7214. /* level 3 */
  7215. i = map->level23[16*map->count2 + 128*i + l3];
  7216. if (i == 0) {
  7217. return -1;
  7218. }
  7219. return i;
  7220. }
  7221. /* Lookup the character ch in the mapping. If the character
  7222. can't be found, Py_None is returned (or NULL, if another
  7223. error occurred). */
  7224. static PyObject *
  7225. charmapencode_lookup(Py_UCS4 c, PyObject *mapping)
  7226. {
  7227. PyObject *w = PyLong_FromLong((long)c);
  7228. PyObject *x;
  7229. if (w == NULL)
  7230. return NULL;
  7231. x = PyObject_GetItem(mapping, w);
  7232. Py_DECREF(w);
  7233. if (x == NULL) {
  7234. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  7235. /* No mapping found means: mapping is undefined. */
  7236. PyErr_Clear();
  7237. Py_RETURN_NONE;
  7238. } else
  7239. return NULL;
  7240. }
  7241. else if (x == Py_None)
  7242. return x;
  7243. else if (PyLong_Check(x)) {
  7244. long value = PyLong_AS_LONG(x);
  7245. if (value < 0 || value > 255) {
  7246. PyErr_SetString(PyExc_TypeError,
  7247. "character mapping must be in range(256)");
  7248. Py_DECREF(x);
  7249. return NULL;
  7250. }
  7251. return x;
  7252. }
  7253. else if (PyBytes_Check(x))
  7254. return x;
  7255. else {
  7256. /* wrong return value */
  7257. PyErr_Format(PyExc_TypeError,
  7258. "character mapping must return integer, bytes or None, not %.400s",
  7259. Py_TYPE(x)->tp_name);
  7260. Py_DECREF(x);
  7261. return NULL;
  7262. }
  7263. }
  7264. static int
  7265. charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
  7266. {
  7267. Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
  7268. /* exponentially overallocate to minimize reallocations */
  7269. if (requiredsize < 2*outsize)
  7270. requiredsize = 2*outsize;
  7271. if (_PyBytes_Resize(outobj, requiredsize))
  7272. return -1;
  7273. return 0;
  7274. }
  7275. typedef enum charmapencode_result {
  7276. enc_SUCCESS, enc_FAILED, enc_EXCEPTION
  7277. } charmapencode_result;
  7278. /* lookup the character, put the result in the output string and adjust
  7279. various state variables. Resize the output bytes object if not enough
  7280. space is available. Return a new reference to the object that
  7281. was put in the output buffer, or Py_None, if the mapping was undefined
  7282. (in which case no character was written) or NULL, if a
  7283. reallocation error occurred. The caller must decref the result */
  7284. static charmapencode_result
  7285. charmapencode_output(Py_UCS4 c, PyObject *mapping,
  7286. PyObject **outobj, Py_ssize_t *outpos)
  7287. {
  7288. PyObject *rep;
  7289. char *outstart;
  7290. Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
  7291. if (Py_IS_TYPE(mapping, &EncodingMapType)) {
  7292. int res = encoding_map_lookup(c, mapping);
  7293. Py_ssize_t requiredsize = *outpos+1;
  7294. if (res == -1)
  7295. return enc_FAILED;
  7296. if (outsize<requiredsize)
  7297. if (charmapencode_resize(outobj, outpos, requiredsize))
  7298. return enc_EXCEPTION;
  7299. outstart = PyBytes_AS_STRING(*outobj);
  7300. outstart[(*outpos)++] = (char)res;
  7301. return enc_SUCCESS;
  7302. }
  7303. rep = charmapencode_lookup(c, mapping);
  7304. if (rep==NULL)
  7305. return enc_EXCEPTION;
  7306. else if (rep==Py_None) {
  7307. Py_DECREF(rep);
  7308. return enc_FAILED;
  7309. } else {
  7310. if (PyLong_Check(rep)) {
  7311. Py_ssize_t requiredsize = *outpos+1;
  7312. if (outsize<requiredsize)
  7313. if (charmapencode_resize(outobj, outpos, requiredsize)) {
  7314. Py_DECREF(rep);
  7315. return enc_EXCEPTION;
  7316. }
  7317. outstart = PyBytes_AS_STRING(*outobj);
  7318. outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
  7319. }
  7320. else {
  7321. const char *repchars = PyBytes_AS_STRING(rep);
  7322. Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
  7323. Py_ssize_t requiredsize = *outpos+repsize;
  7324. if (outsize<requiredsize)
  7325. if (charmapencode_resize(outobj, outpos, requiredsize)) {
  7326. Py_DECREF(rep);
  7327. return enc_EXCEPTION;
  7328. }
  7329. outstart = PyBytes_AS_STRING(*outobj);
  7330. memcpy(outstart + *outpos, repchars, repsize);
  7331. *outpos += repsize;
  7332. }
  7333. }
  7334. Py_DECREF(rep);
  7335. return enc_SUCCESS;
  7336. }
  7337. /* handle an error in PyUnicode_EncodeCharmap
  7338. Return 0 on success, -1 on error */
  7339. static int
  7340. charmap_encoding_error(
  7341. PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
  7342. PyObject **exceptionObject,
  7343. _Py_error_handler *error_handler, PyObject **error_handler_obj, const char *errors,
  7344. PyObject **res, Py_ssize_t *respos)
  7345. {
  7346. PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
  7347. Py_ssize_t size, repsize;
  7348. Py_ssize_t newpos;
  7349. int kind;
  7350. const void *data;
  7351. Py_ssize_t index;
  7352. /* startpos for collecting unencodable chars */
  7353. Py_ssize_t collstartpos = *inpos;
  7354. Py_ssize_t collendpos = *inpos+1;
  7355. Py_ssize_t collpos;
  7356. const char *encoding = "charmap";
  7357. const char *reason = "character maps to <undefined>";
  7358. charmapencode_result x;
  7359. Py_UCS4 ch;
  7360. int val;
  7361. size = PyUnicode_GET_LENGTH(unicode);
  7362. /* find all unencodable characters */
  7363. while (collendpos < size) {
  7364. PyObject *rep;
  7365. if (Py_IS_TYPE(mapping, &EncodingMapType)) {
  7366. ch = PyUnicode_READ_CHAR(unicode, collendpos);
  7367. val = encoding_map_lookup(ch, mapping);
  7368. if (val != -1)
  7369. break;
  7370. ++collendpos;
  7371. continue;
  7372. }
  7373. ch = PyUnicode_READ_CHAR(unicode, collendpos);
  7374. rep = charmapencode_lookup(ch, mapping);
  7375. if (rep==NULL)
  7376. return -1;
  7377. else if (rep!=Py_None) {
  7378. Py_DECREF(rep);
  7379. break;
  7380. }
  7381. Py_DECREF(rep);
  7382. ++collendpos;
  7383. }
  7384. /* cache callback name lookup
  7385. * (if not done yet, i.e. it's the first error) */
  7386. if (*error_handler == _Py_ERROR_UNKNOWN)
  7387. *error_handler = _Py_GetErrorHandler(errors);
  7388. switch (*error_handler) {
  7389. case _Py_ERROR_STRICT:
  7390. raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
  7391. return -1;
  7392. case _Py_ERROR_REPLACE:
  7393. for (collpos = collstartpos; collpos<collendpos; ++collpos) {
  7394. x = charmapencode_output('?', mapping, res, respos);
  7395. if (x==enc_EXCEPTION) {
  7396. return -1;
  7397. }
  7398. else if (x==enc_FAILED) {
  7399. raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
  7400. return -1;
  7401. }
  7402. }
  7403. /* fall through */
  7404. case _Py_ERROR_IGNORE:
  7405. *inpos = collendpos;
  7406. break;
  7407. case _Py_ERROR_XMLCHARREFREPLACE:
  7408. /* generate replacement (temporarily (mis)uses p) */
  7409. for (collpos = collstartpos; collpos < collendpos; ++collpos) {
  7410. char buffer[2+29+1+1];
  7411. char *cp;
  7412. sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
  7413. for (cp = buffer; *cp; ++cp) {
  7414. x = charmapencode_output(*cp, mapping, res, respos);
  7415. if (x==enc_EXCEPTION)
  7416. return -1;
  7417. else if (x==enc_FAILED) {
  7418. raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
  7419. return -1;
  7420. }
  7421. }
  7422. }
  7423. *inpos = collendpos;
  7424. break;
  7425. default:
  7426. repunicode = unicode_encode_call_errorhandler(errors, error_handler_obj,
  7427. encoding, reason, unicode, exceptionObject,
  7428. collstartpos, collendpos, &newpos);
  7429. if (repunicode == NULL)
  7430. return -1;
  7431. if (PyBytes_Check(repunicode)) {
  7432. /* Directly copy bytes result to output. */
  7433. Py_ssize_t outsize = PyBytes_Size(*res);
  7434. Py_ssize_t requiredsize;
  7435. repsize = PyBytes_Size(repunicode);
  7436. requiredsize = *respos + repsize;
  7437. if (requiredsize > outsize)
  7438. /* Make room for all additional bytes. */
  7439. if (charmapencode_resize(res, respos, requiredsize)) {
  7440. Py_DECREF(repunicode);
  7441. return -1;
  7442. }
  7443. memcpy(PyBytes_AsString(*res) + *respos,
  7444. PyBytes_AsString(repunicode), repsize);
  7445. *respos += repsize;
  7446. *inpos = newpos;
  7447. Py_DECREF(repunicode);
  7448. break;
  7449. }
  7450. /* generate replacement */
  7451. repsize = PyUnicode_GET_LENGTH(repunicode);
  7452. data = PyUnicode_DATA(repunicode);
  7453. kind = PyUnicode_KIND(repunicode);
  7454. for (index = 0; index < repsize; index++) {
  7455. Py_UCS4 repch = PyUnicode_READ(kind, data, index);
  7456. x = charmapencode_output(repch, mapping, res, respos);
  7457. if (x==enc_EXCEPTION) {
  7458. Py_DECREF(repunicode);
  7459. return -1;
  7460. }
  7461. else if (x==enc_FAILED) {
  7462. Py_DECREF(repunicode);
  7463. raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
  7464. return -1;
  7465. }
  7466. }
  7467. *inpos = newpos;
  7468. Py_DECREF(repunicode);
  7469. }
  7470. return 0;
  7471. }
  7472. PyObject *
  7473. _PyUnicode_EncodeCharmap(PyObject *unicode,
  7474. PyObject *mapping,
  7475. const char *errors)
  7476. {
  7477. /* output object */
  7478. PyObject *res = NULL;
  7479. /* current input position */
  7480. Py_ssize_t inpos = 0;
  7481. Py_ssize_t size;
  7482. /* current output position */
  7483. Py_ssize_t respos = 0;
  7484. PyObject *error_handler_obj = NULL;
  7485. PyObject *exc = NULL;
  7486. _Py_error_handler error_handler = _Py_ERROR_UNKNOWN;
  7487. const void *data;
  7488. int kind;
  7489. size = PyUnicode_GET_LENGTH(unicode);
  7490. data = PyUnicode_DATA(unicode);
  7491. kind = PyUnicode_KIND(unicode);
  7492. /* Default to Latin-1 */
  7493. if (mapping == NULL)
  7494. return unicode_encode_ucs1(unicode, errors, 256);
  7495. /* allocate enough for a simple encoding without
  7496. replacements, if we need more, we'll resize */
  7497. res = PyBytes_FromStringAndSize(NULL, size);
  7498. if (res == NULL)
  7499. goto onError;
  7500. if (size == 0)
  7501. return res;
  7502. while (inpos<size) {
  7503. Py_UCS4 ch = PyUnicode_READ(kind, data, inpos);
  7504. /* try to encode it */
  7505. charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
  7506. if (x==enc_EXCEPTION) /* error */
  7507. goto onError;
  7508. if (x==enc_FAILED) { /* unencodable character */
  7509. if (charmap_encoding_error(unicode, &inpos, mapping,
  7510. &exc,
  7511. &error_handler, &error_handler_obj, errors,
  7512. &res, &respos)) {
  7513. goto onError;
  7514. }
  7515. }
  7516. else
  7517. /* done with this character => adjust input position */
  7518. ++inpos;
  7519. }
  7520. /* Resize if we allocated to much */
  7521. if (respos<PyBytes_GET_SIZE(res))
  7522. if (_PyBytes_Resize(&res, respos) < 0)
  7523. goto onError;
  7524. Py_XDECREF(exc);
  7525. Py_XDECREF(error_handler_obj);
  7526. return res;
  7527. onError:
  7528. Py_XDECREF(res);
  7529. Py_XDECREF(exc);
  7530. Py_XDECREF(error_handler_obj);
  7531. return NULL;
  7532. }
  7533. PyObject *
  7534. PyUnicode_AsCharmapString(PyObject *unicode,
  7535. PyObject *mapping)
  7536. {
  7537. if (!PyUnicode_Check(unicode) || mapping == NULL) {
  7538. PyErr_BadArgument();
  7539. return NULL;
  7540. }
  7541. return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
  7542. }
  7543. /* create or adjust a UnicodeTranslateError */
  7544. static void
  7545. make_translate_exception(PyObject **exceptionObject,
  7546. PyObject *unicode,
  7547. Py_ssize_t startpos, Py_ssize_t endpos,
  7548. const char *reason)
  7549. {
  7550. if (*exceptionObject == NULL) {
  7551. *exceptionObject = _PyUnicodeTranslateError_Create(
  7552. unicode, startpos, endpos, reason);
  7553. }
  7554. else {
  7555. if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
  7556. goto onError;
  7557. if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
  7558. goto onError;
  7559. if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
  7560. goto onError;
  7561. return;
  7562. onError:
  7563. Py_CLEAR(*exceptionObject);
  7564. }
  7565. }
  7566. /* error handling callback helper:
  7567. build arguments, call the callback and check the arguments,
  7568. put the result into newpos and return the replacement string, which
  7569. has to be freed by the caller */
  7570. static PyObject *
  7571. unicode_translate_call_errorhandler(const char *errors,
  7572. PyObject **errorHandler,
  7573. const char *reason,
  7574. PyObject *unicode, PyObject **exceptionObject,
  7575. Py_ssize_t startpos, Py_ssize_t endpos,
  7576. Py_ssize_t *newpos)
  7577. {
  7578. static const char *argparse = "Un;translating error handler must return (str, int) tuple";
  7579. Py_ssize_t i_newpos;
  7580. PyObject *restuple;
  7581. PyObject *resunicode;
  7582. if (*errorHandler == NULL) {
  7583. *errorHandler = PyCodec_LookupError(errors);
  7584. if (*errorHandler == NULL)
  7585. return NULL;
  7586. }
  7587. make_translate_exception(exceptionObject,
  7588. unicode, startpos, endpos, reason);
  7589. if (*exceptionObject == NULL)
  7590. return NULL;
  7591. restuple = PyObject_CallOneArg(*errorHandler, *exceptionObject);
  7592. if (restuple == NULL)
  7593. return NULL;
  7594. if (!PyTuple_Check(restuple)) {
  7595. PyErr_SetString(PyExc_TypeError, &argparse[3]);
  7596. Py_DECREF(restuple);
  7597. return NULL;
  7598. }
  7599. if (!PyArg_ParseTuple(restuple, argparse,
  7600. &resunicode, &i_newpos)) {
  7601. Py_DECREF(restuple);
  7602. return NULL;
  7603. }
  7604. if (i_newpos<0)
  7605. *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
  7606. else
  7607. *newpos = i_newpos;
  7608. if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
  7609. PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
  7610. Py_DECREF(restuple);
  7611. return NULL;
  7612. }
  7613. Py_INCREF(resunicode);
  7614. Py_DECREF(restuple);
  7615. return resunicode;
  7616. }
  7617. /* Lookup the character ch in the mapping and put the result in result,
  7618. which must be decrefed by the caller.
  7619. Return 0 on success, -1 on error */
  7620. static int
  7621. charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
  7622. {
  7623. PyObject *w = PyLong_FromLong((long)c);
  7624. PyObject *x;
  7625. if (w == NULL)
  7626. return -1;
  7627. x = PyObject_GetItem(mapping, w);
  7628. Py_DECREF(w);
  7629. if (x == NULL) {
  7630. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  7631. /* No mapping found means: use 1:1 mapping. */
  7632. PyErr_Clear();
  7633. *result = NULL;
  7634. return 0;
  7635. } else
  7636. return -1;
  7637. }
  7638. else if (x == Py_None) {
  7639. *result = x;
  7640. return 0;
  7641. }
  7642. else if (PyLong_Check(x)) {
  7643. long value = PyLong_AS_LONG(x);
  7644. if (value < 0 || value > MAX_UNICODE) {
  7645. PyErr_Format(PyExc_ValueError,
  7646. "character mapping must be in range(0x%x)",
  7647. MAX_UNICODE+1);
  7648. Py_DECREF(x);
  7649. return -1;
  7650. }
  7651. *result = x;
  7652. return 0;
  7653. }
  7654. else if (PyUnicode_Check(x)) {
  7655. *result = x;
  7656. return 0;
  7657. }
  7658. else {
  7659. /* wrong return value */
  7660. PyErr_SetString(PyExc_TypeError,
  7661. "character mapping must return integer, None or str");
  7662. Py_DECREF(x);
  7663. return -1;
  7664. }
  7665. }
  7666. /* lookup the character, write the result into the writer.
  7667. Return 1 if the result was written into the writer, return 0 if the mapping
  7668. was undefined, raise an exception return -1 on error. */
  7669. static int
  7670. charmaptranslate_output(Py_UCS4 ch, PyObject *mapping,
  7671. _PyUnicodeWriter *writer)
  7672. {
  7673. PyObject *item;
  7674. if (charmaptranslate_lookup(ch, mapping, &item))
  7675. return -1;
  7676. if (item == NULL) {
  7677. /* not found => default to 1:1 mapping */
  7678. if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
  7679. return -1;
  7680. }
  7681. return 1;
  7682. }
  7683. if (item == Py_None) {
  7684. Py_DECREF(item);
  7685. return 0;
  7686. }
  7687. if (PyLong_Check(item)) {
  7688. long ch = (Py_UCS4)PyLong_AS_LONG(item);
  7689. /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
  7690. used it */
  7691. if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0) {
  7692. Py_DECREF(item);
  7693. return -1;
  7694. }
  7695. Py_DECREF(item);
  7696. return 1;
  7697. }
  7698. if (!PyUnicode_Check(item)) {
  7699. Py_DECREF(item);
  7700. return -1;
  7701. }
  7702. if (_PyUnicodeWriter_WriteStr(writer, item) < 0) {
  7703. Py_DECREF(item);
  7704. return -1;
  7705. }
  7706. Py_DECREF(item);
  7707. return 1;
  7708. }
  7709. static int
  7710. unicode_fast_translate_lookup(PyObject *mapping, Py_UCS1 ch,
  7711. Py_UCS1 *translate)
  7712. {
  7713. PyObject *item = NULL;
  7714. int ret = 0;
  7715. if (charmaptranslate_lookup(ch, mapping, &item)) {
  7716. return -1;
  7717. }
  7718. if (item == Py_None) {
  7719. /* deletion */
  7720. translate[ch] = 0xfe;
  7721. }
  7722. else if (item == NULL) {
  7723. /* not found => default to 1:1 mapping */
  7724. translate[ch] = ch;
  7725. return 1;
  7726. }
  7727. else if (PyLong_Check(item)) {
  7728. long replace = PyLong_AS_LONG(item);
  7729. /* PyLong_AS_LONG() cannot fail, charmaptranslate_lookup() already
  7730. used it */
  7731. if (127 < replace) {
  7732. /* invalid character or character outside ASCII:
  7733. skip the fast translate */
  7734. goto exit;
  7735. }
  7736. translate[ch] = (Py_UCS1)replace;
  7737. }
  7738. else if (PyUnicode_Check(item)) {
  7739. Py_UCS4 replace;
  7740. if (PyUnicode_GET_LENGTH(item) != 1)
  7741. goto exit;
  7742. replace = PyUnicode_READ_CHAR(item, 0);
  7743. if (replace > 127)
  7744. goto exit;
  7745. translate[ch] = (Py_UCS1)replace;
  7746. }
  7747. else {
  7748. /* not None, NULL, long or unicode */
  7749. goto exit;
  7750. }
  7751. ret = 1;
  7752. exit:
  7753. Py_DECREF(item);
  7754. return ret;
  7755. }
  7756. /* Fast path for ascii => ascii translation. Return 1 if the whole string
  7757. was translated into writer, return 0 if the input string was partially
  7758. translated into writer, raise an exception and return -1 on error. */
  7759. static int
  7760. unicode_fast_translate(PyObject *input, PyObject *mapping,
  7761. _PyUnicodeWriter *writer, int ignore,
  7762. Py_ssize_t *input_pos)
  7763. {
  7764. Py_UCS1 ascii_table[128], ch, ch2;
  7765. Py_ssize_t len;
  7766. const Py_UCS1 *in, *end;
  7767. Py_UCS1 *out;
  7768. int res = 0;
  7769. len = PyUnicode_GET_LENGTH(input);
  7770. memset(ascii_table, 0xff, 128);
  7771. in = PyUnicode_1BYTE_DATA(input);
  7772. end = in + len;
  7773. assert(PyUnicode_IS_ASCII(writer->buffer));
  7774. assert(PyUnicode_GET_LENGTH(writer->buffer) == len);
  7775. out = PyUnicode_1BYTE_DATA(writer->buffer);
  7776. for (; in < end; in++) {
  7777. ch = *in;
  7778. ch2 = ascii_table[ch];
  7779. if (ch2 == 0xff) {
  7780. int translate = unicode_fast_translate_lookup(mapping, ch,
  7781. ascii_table);
  7782. if (translate < 0)
  7783. return -1;
  7784. if (translate == 0)
  7785. goto exit;
  7786. ch2 = ascii_table[ch];
  7787. }
  7788. if (ch2 == 0xfe) {
  7789. if (ignore)
  7790. continue;
  7791. goto exit;
  7792. }
  7793. assert(ch2 < 128);
  7794. *out = ch2;
  7795. out++;
  7796. }
  7797. res = 1;
  7798. exit:
  7799. writer->pos = out - PyUnicode_1BYTE_DATA(writer->buffer);
  7800. *input_pos = in - PyUnicode_1BYTE_DATA(input);
  7801. return res;
  7802. }
  7803. static PyObject *
  7804. _PyUnicode_TranslateCharmap(PyObject *input,
  7805. PyObject *mapping,
  7806. const char *errors)
  7807. {
  7808. /* input object */
  7809. const void *data;
  7810. Py_ssize_t size, i;
  7811. int kind;
  7812. /* output buffer */
  7813. _PyUnicodeWriter writer;
  7814. /* error handler */
  7815. const char *reason = "character maps to <undefined>";
  7816. PyObject *errorHandler = NULL;
  7817. PyObject *exc = NULL;
  7818. int ignore;
  7819. int res;
  7820. if (mapping == NULL) {
  7821. PyErr_BadArgument();
  7822. return NULL;
  7823. }
  7824. data = PyUnicode_DATA(input);
  7825. kind = PyUnicode_KIND(input);
  7826. size = PyUnicode_GET_LENGTH(input);
  7827. if (size == 0)
  7828. return PyUnicode_FromObject(input);
  7829. /* allocate enough for a simple 1:1 translation without
  7830. replacements, if we need more, we'll resize */
  7831. _PyUnicodeWriter_Init(&writer);
  7832. if (_PyUnicodeWriter_Prepare(&writer, size, 127) == -1)
  7833. goto onError;
  7834. ignore = (errors != NULL && strcmp(errors, "ignore") == 0);
  7835. if (PyUnicode_IS_ASCII(input)) {
  7836. res = unicode_fast_translate(input, mapping, &writer, ignore, &i);
  7837. if (res < 0) {
  7838. _PyUnicodeWriter_Dealloc(&writer);
  7839. return NULL;
  7840. }
  7841. if (res == 1)
  7842. return _PyUnicodeWriter_Finish(&writer);
  7843. }
  7844. else {
  7845. i = 0;
  7846. }
  7847. while (i<size) {
  7848. /* try to encode it */
  7849. int translate;
  7850. PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
  7851. Py_ssize_t newpos;
  7852. /* startpos for collecting untranslatable chars */
  7853. Py_ssize_t collstart;
  7854. Py_ssize_t collend;
  7855. Py_UCS4 ch;
  7856. ch = PyUnicode_READ(kind, data, i);
  7857. translate = charmaptranslate_output(ch, mapping, &writer);
  7858. if (translate < 0)
  7859. goto onError;
  7860. if (translate != 0) {
  7861. /* it worked => adjust input pointer */
  7862. ++i;
  7863. continue;
  7864. }
  7865. /* untranslatable character */
  7866. collstart = i;
  7867. collend = i+1;
  7868. /* find all untranslatable characters */
  7869. while (collend < size) {
  7870. PyObject *x;
  7871. ch = PyUnicode_READ(kind, data, collend);
  7872. if (charmaptranslate_lookup(ch, mapping, &x))
  7873. goto onError;
  7874. Py_XDECREF(x);
  7875. if (x != Py_None)
  7876. break;
  7877. ++collend;
  7878. }
  7879. if (ignore) {
  7880. i = collend;
  7881. }
  7882. else {
  7883. repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
  7884. reason, input, &exc,
  7885. collstart, collend, &newpos);
  7886. if (repunicode == NULL)
  7887. goto onError;
  7888. if (_PyUnicodeWriter_WriteStr(&writer, repunicode) < 0) {
  7889. Py_DECREF(repunicode);
  7890. goto onError;
  7891. }
  7892. Py_DECREF(repunicode);
  7893. i = newpos;
  7894. }
  7895. }
  7896. Py_XDECREF(exc);
  7897. Py_XDECREF(errorHandler);
  7898. return _PyUnicodeWriter_Finish(&writer);
  7899. onError:
  7900. _PyUnicodeWriter_Dealloc(&writer);
  7901. Py_XDECREF(exc);
  7902. Py_XDECREF(errorHandler);
  7903. return NULL;
  7904. }
  7905. PyObject *
  7906. PyUnicode_Translate(PyObject *str,
  7907. PyObject *mapping,
  7908. const char *errors)
  7909. {
  7910. if (ensure_unicode(str) < 0)
  7911. return NULL;
  7912. return _PyUnicode_TranslateCharmap(str, mapping, errors);
  7913. }
  7914. PyObject *
  7915. _PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
  7916. {
  7917. if (!PyUnicode_Check(unicode)) {
  7918. PyErr_BadInternalCall();
  7919. return NULL;
  7920. }
  7921. if (PyUnicode_IS_ASCII(unicode)) {
  7922. /* If the string is already ASCII, just return the same string */
  7923. return Py_NewRef(unicode);
  7924. }
  7925. Py_ssize_t len = PyUnicode_GET_LENGTH(unicode);
  7926. PyObject *result = PyUnicode_New(len, 127);
  7927. if (result == NULL) {
  7928. return NULL;
  7929. }
  7930. Py_UCS1 *out = PyUnicode_1BYTE_DATA(result);
  7931. int kind = PyUnicode_KIND(unicode);
  7932. const void *data = PyUnicode_DATA(unicode);
  7933. Py_ssize_t i;
  7934. for (i = 0; i < len; ++i) {
  7935. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  7936. if (ch < 127) {
  7937. out[i] = ch;
  7938. }
  7939. else if (Py_UNICODE_ISSPACE(ch)) {
  7940. out[i] = ' ';
  7941. }
  7942. else {
  7943. int decimal = Py_UNICODE_TODECIMAL(ch);
  7944. if (decimal < 0) {
  7945. out[i] = '?';
  7946. out[i+1] = '\0';
  7947. _PyUnicode_LENGTH(result) = i + 1;
  7948. break;
  7949. }
  7950. out[i] = '0' + decimal;
  7951. }
  7952. }
  7953. assert(_PyUnicode_CheckConsistency(result, 1));
  7954. return result;
  7955. }
  7956. /* --- Helpers ------------------------------------------------------------ */
  7957. /* helper macro to fixup start/end slice values */
  7958. #define ADJUST_INDICES(start, end, len) \
  7959. if (end > len) \
  7960. end = len; \
  7961. else if (end < 0) { \
  7962. end += len; \
  7963. if (end < 0) \
  7964. end = 0; \
  7965. } \
  7966. if (start < 0) { \
  7967. start += len; \
  7968. if (start < 0) \
  7969. start = 0; \
  7970. }
  7971. static Py_ssize_t
  7972. any_find_slice(PyObject* s1, PyObject* s2,
  7973. Py_ssize_t start,
  7974. Py_ssize_t end,
  7975. int direction)
  7976. {
  7977. int kind1, kind2;
  7978. const void *buf1, *buf2;
  7979. Py_ssize_t len1, len2, result;
  7980. kind1 = PyUnicode_KIND(s1);
  7981. kind2 = PyUnicode_KIND(s2);
  7982. if (kind1 < kind2)
  7983. return -1;
  7984. len1 = PyUnicode_GET_LENGTH(s1);
  7985. len2 = PyUnicode_GET_LENGTH(s2);
  7986. ADJUST_INDICES(start, end, len1);
  7987. if (end - start < len2)
  7988. return -1;
  7989. buf1 = PyUnicode_DATA(s1);
  7990. buf2 = PyUnicode_DATA(s2);
  7991. if (len2 == 1) {
  7992. Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
  7993. result = findchar((const char *)buf1 + kind1*start,
  7994. kind1, end - start, ch, direction);
  7995. if (result == -1)
  7996. return -1;
  7997. else
  7998. return start + result;
  7999. }
  8000. if (kind2 != kind1) {
  8001. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  8002. if (!buf2)
  8003. return -2;
  8004. }
  8005. if (direction > 0) {
  8006. switch (kind1) {
  8007. case PyUnicode_1BYTE_KIND:
  8008. if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
  8009. result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
  8010. else
  8011. result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
  8012. break;
  8013. case PyUnicode_2BYTE_KIND:
  8014. result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
  8015. break;
  8016. case PyUnicode_4BYTE_KIND:
  8017. result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
  8018. break;
  8019. default:
  8020. Py_UNREACHABLE();
  8021. }
  8022. }
  8023. else {
  8024. switch (kind1) {
  8025. case PyUnicode_1BYTE_KIND:
  8026. if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
  8027. result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
  8028. else
  8029. result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
  8030. break;
  8031. case PyUnicode_2BYTE_KIND:
  8032. result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
  8033. break;
  8034. case PyUnicode_4BYTE_KIND:
  8035. result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
  8036. break;
  8037. default:
  8038. Py_UNREACHABLE();
  8039. }
  8040. }
  8041. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(s2)));
  8042. if (kind2 != kind1)
  8043. PyMem_Free((void *)buf2);
  8044. return result;
  8045. }
  8046. /* _PyUnicode_InsertThousandsGrouping() helper functions */
  8047. #include "stringlib/localeutil.h"
  8048. /**
  8049. * InsertThousandsGrouping:
  8050. * @writer: Unicode writer.
  8051. * @n_buffer: Number of characters in @buffer.
  8052. * @digits: Digits we're reading from. If count is non-NULL, this is unused.
  8053. * @d_pos: Start of digits string.
  8054. * @n_digits: The number of digits in the string, in which we want
  8055. * to put the grouping chars.
  8056. * @min_width: The minimum width of the digits in the output string.
  8057. * Output will be zero-padded on the left to fill.
  8058. * @grouping: see definition in localeconv().
  8059. * @thousands_sep: see definition in localeconv().
  8060. *
  8061. * There are 2 modes: counting and filling. If @writer is NULL,
  8062. * we are in counting mode, else filling mode.
  8063. * If counting, the required buffer size is returned.
  8064. * If filling, we know the buffer will be large enough, so we don't
  8065. * need to pass in the buffer size.
  8066. * Inserts thousand grouping characters (as defined by grouping and
  8067. * thousands_sep) into @writer.
  8068. *
  8069. * Return value: -1 on error, number of characters otherwise.
  8070. **/
  8071. Py_ssize_t
  8072. _PyUnicode_InsertThousandsGrouping(
  8073. _PyUnicodeWriter *writer,
  8074. Py_ssize_t n_buffer,
  8075. PyObject *digits,
  8076. Py_ssize_t d_pos,
  8077. Py_ssize_t n_digits,
  8078. Py_ssize_t min_width,
  8079. const char *grouping,
  8080. PyObject *thousands_sep,
  8081. Py_UCS4 *maxchar)
  8082. {
  8083. min_width = Py_MAX(0, min_width);
  8084. if (writer) {
  8085. assert(digits != NULL);
  8086. assert(maxchar == NULL);
  8087. }
  8088. else {
  8089. assert(digits == NULL);
  8090. assert(maxchar != NULL);
  8091. }
  8092. assert(0 <= d_pos);
  8093. assert(0 <= n_digits);
  8094. assert(grouping != NULL);
  8095. Py_ssize_t count = 0;
  8096. Py_ssize_t n_zeros;
  8097. int loop_broken = 0;
  8098. int use_separator = 0; /* First time through, don't append the
  8099. separator. They only go between
  8100. groups. */
  8101. Py_ssize_t buffer_pos;
  8102. Py_ssize_t digits_pos;
  8103. Py_ssize_t len;
  8104. Py_ssize_t n_chars;
  8105. Py_ssize_t remaining = n_digits; /* Number of chars remaining to
  8106. be looked at */
  8107. /* A generator that returns all of the grouping widths, until it
  8108. returns 0. */
  8109. GroupGenerator groupgen;
  8110. GroupGenerator_init(&groupgen, grouping);
  8111. const Py_ssize_t thousands_sep_len = PyUnicode_GET_LENGTH(thousands_sep);
  8112. /* if digits are not grouped, thousands separator
  8113. should be an empty string */
  8114. assert(!(grouping[0] == CHAR_MAX && thousands_sep_len != 0));
  8115. digits_pos = d_pos + n_digits;
  8116. if (writer) {
  8117. buffer_pos = writer->pos + n_buffer;
  8118. assert(buffer_pos <= PyUnicode_GET_LENGTH(writer->buffer));
  8119. assert(digits_pos <= PyUnicode_GET_LENGTH(digits));
  8120. }
  8121. else {
  8122. buffer_pos = n_buffer;
  8123. }
  8124. if (!writer) {
  8125. *maxchar = 127;
  8126. }
  8127. while ((len = GroupGenerator_next(&groupgen)) > 0) {
  8128. len = Py_MIN(len, Py_MAX(Py_MAX(remaining, min_width), 1));
  8129. n_zeros = Py_MAX(0, len - remaining);
  8130. n_chars = Py_MAX(0, Py_MIN(remaining, len));
  8131. /* Use n_zero zero's and n_chars chars */
  8132. /* Count only, don't do anything. */
  8133. count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
  8134. /* Copy into the writer. */
  8135. InsertThousandsGrouping_fill(writer, &buffer_pos,
  8136. digits, &digits_pos,
  8137. n_chars, n_zeros,
  8138. use_separator ? thousands_sep : NULL,
  8139. thousands_sep_len, maxchar);
  8140. /* Use a separator next time. */
  8141. use_separator = 1;
  8142. remaining -= n_chars;
  8143. min_width -= len;
  8144. if (remaining <= 0 && min_width <= 0) {
  8145. loop_broken = 1;
  8146. break;
  8147. }
  8148. min_width -= thousands_sep_len;
  8149. }
  8150. if (!loop_broken) {
  8151. /* We left the loop without using a break statement. */
  8152. len = Py_MAX(Py_MAX(remaining, min_width), 1);
  8153. n_zeros = Py_MAX(0, len - remaining);
  8154. n_chars = Py_MAX(0, Py_MIN(remaining, len));
  8155. /* Use n_zero zero's and n_chars chars */
  8156. count += (use_separator ? thousands_sep_len : 0) + n_zeros + n_chars;
  8157. /* Copy into the writer. */
  8158. InsertThousandsGrouping_fill(writer, &buffer_pos,
  8159. digits, &digits_pos,
  8160. n_chars, n_zeros,
  8161. use_separator ? thousands_sep : NULL,
  8162. thousands_sep_len, maxchar);
  8163. }
  8164. return count;
  8165. }
  8166. static Py_ssize_t
  8167. unicode_count_impl(PyObject *str,
  8168. PyObject *substr,
  8169. Py_ssize_t start,
  8170. Py_ssize_t end)
  8171. {
  8172. assert(PyUnicode_Check(str));
  8173. assert(PyUnicode_Check(substr));
  8174. Py_ssize_t result;
  8175. int kind1, kind2;
  8176. const void *buf1 = NULL, *buf2 = NULL;
  8177. Py_ssize_t len1, len2;
  8178. kind1 = PyUnicode_KIND(str);
  8179. kind2 = PyUnicode_KIND(substr);
  8180. if (kind1 < kind2)
  8181. return 0;
  8182. len1 = PyUnicode_GET_LENGTH(str);
  8183. len2 = PyUnicode_GET_LENGTH(substr);
  8184. ADJUST_INDICES(start, end, len1);
  8185. if (end - start < len2)
  8186. return 0;
  8187. buf1 = PyUnicode_DATA(str);
  8188. buf2 = PyUnicode_DATA(substr);
  8189. if (kind2 != kind1) {
  8190. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  8191. if (!buf2)
  8192. goto onError;
  8193. }
  8194. // We don't reuse `anylib_count` here because of the explicit casts.
  8195. switch (kind1) {
  8196. case PyUnicode_1BYTE_KIND:
  8197. result = ucs1lib_count(
  8198. ((const Py_UCS1*)buf1) + start, end - start,
  8199. buf2, len2, PY_SSIZE_T_MAX
  8200. );
  8201. break;
  8202. case PyUnicode_2BYTE_KIND:
  8203. result = ucs2lib_count(
  8204. ((const Py_UCS2*)buf1) + start, end - start,
  8205. buf2, len2, PY_SSIZE_T_MAX
  8206. );
  8207. break;
  8208. case PyUnicode_4BYTE_KIND:
  8209. result = ucs4lib_count(
  8210. ((const Py_UCS4*)buf1) + start, end - start,
  8211. buf2, len2, PY_SSIZE_T_MAX
  8212. );
  8213. break;
  8214. default:
  8215. Py_UNREACHABLE();
  8216. }
  8217. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
  8218. if (kind2 != kind1)
  8219. PyMem_Free((void *)buf2);
  8220. return result;
  8221. onError:
  8222. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substr)));
  8223. if (kind2 != kind1)
  8224. PyMem_Free((void *)buf2);
  8225. return -1;
  8226. }
  8227. Py_ssize_t
  8228. PyUnicode_Count(PyObject *str,
  8229. PyObject *substr,
  8230. Py_ssize_t start,
  8231. Py_ssize_t end)
  8232. {
  8233. if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
  8234. return -1;
  8235. return unicode_count_impl(str, substr, start, end);
  8236. }
  8237. Py_ssize_t
  8238. PyUnicode_Find(PyObject *str,
  8239. PyObject *substr,
  8240. Py_ssize_t start,
  8241. Py_ssize_t end,
  8242. int direction)
  8243. {
  8244. if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
  8245. return -2;
  8246. return any_find_slice(str, substr, start, end, direction);
  8247. }
  8248. Py_ssize_t
  8249. PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
  8250. Py_ssize_t start, Py_ssize_t end,
  8251. int direction)
  8252. {
  8253. int kind;
  8254. Py_ssize_t len, result;
  8255. len = PyUnicode_GET_LENGTH(str);
  8256. ADJUST_INDICES(start, end, len);
  8257. if (end - start < 1)
  8258. return -1;
  8259. kind = PyUnicode_KIND(str);
  8260. result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
  8261. kind, end-start, ch, direction);
  8262. if (result == -1)
  8263. return -1;
  8264. else
  8265. return start + result;
  8266. }
  8267. static int
  8268. tailmatch(PyObject *self,
  8269. PyObject *substring,
  8270. Py_ssize_t start,
  8271. Py_ssize_t end,
  8272. int direction)
  8273. {
  8274. int kind_self;
  8275. int kind_sub;
  8276. const void *data_self;
  8277. const void *data_sub;
  8278. Py_ssize_t offset;
  8279. Py_ssize_t i;
  8280. Py_ssize_t end_sub;
  8281. ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
  8282. end -= PyUnicode_GET_LENGTH(substring);
  8283. if (end < start)
  8284. return 0;
  8285. if (PyUnicode_GET_LENGTH(substring) == 0)
  8286. return 1;
  8287. kind_self = PyUnicode_KIND(self);
  8288. data_self = PyUnicode_DATA(self);
  8289. kind_sub = PyUnicode_KIND(substring);
  8290. data_sub = PyUnicode_DATA(substring);
  8291. end_sub = PyUnicode_GET_LENGTH(substring) - 1;
  8292. if (direction > 0)
  8293. offset = end;
  8294. else
  8295. offset = start;
  8296. if (PyUnicode_READ(kind_self, data_self, offset) ==
  8297. PyUnicode_READ(kind_sub, data_sub, 0) &&
  8298. PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
  8299. PyUnicode_READ(kind_sub, data_sub, end_sub)) {
  8300. /* If both are of the same kind, memcmp is sufficient */
  8301. if (kind_self == kind_sub) {
  8302. return ! memcmp((char *)data_self +
  8303. (offset * PyUnicode_KIND(substring)),
  8304. data_sub,
  8305. PyUnicode_GET_LENGTH(substring) *
  8306. PyUnicode_KIND(substring));
  8307. }
  8308. /* otherwise we have to compare each character by first accessing it */
  8309. else {
  8310. /* We do not need to compare 0 and len(substring)-1 because
  8311. the if statement above ensured already that they are equal
  8312. when we end up here. */
  8313. for (i = 1; i < end_sub; ++i) {
  8314. if (PyUnicode_READ(kind_self, data_self, offset + i) !=
  8315. PyUnicode_READ(kind_sub, data_sub, i))
  8316. return 0;
  8317. }
  8318. return 1;
  8319. }
  8320. }
  8321. return 0;
  8322. }
  8323. Py_ssize_t
  8324. PyUnicode_Tailmatch(PyObject *str,
  8325. PyObject *substr,
  8326. Py_ssize_t start,
  8327. Py_ssize_t end,
  8328. int direction)
  8329. {
  8330. if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0)
  8331. return -1;
  8332. return tailmatch(str, substr, start, end, direction);
  8333. }
  8334. static PyObject *
  8335. ascii_upper_or_lower(PyObject *self, int lower)
  8336. {
  8337. Py_ssize_t len = PyUnicode_GET_LENGTH(self);
  8338. const char *data = PyUnicode_DATA(self);
  8339. char *resdata;
  8340. PyObject *res;
  8341. res = PyUnicode_New(len, 127);
  8342. if (res == NULL)
  8343. return NULL;
  8344. resdata = PyUnicode_DATA(res);
  8345. if (lower)
  8346. _Py_bytes_lower(resdata, data, len);
  8347. else
  8348. _Py_bytes_upper(resdata, data, len);
  8349. return res;
  8350. }
  8351. static Py_UCS4
  8352. handle_capital_sigma(int kind, const void *data, Py_ssize_t length, Py_ssize_t i)
  8353. {
  8354. Py_ssize_t j;
  8355. int final_sigma;
  8356. Py_UCS4 c = 0; /* initialize to prevent gcc warning */
  8357. /* U+03A3 is in the Final_Sigma context when, it is found like this:
  8358. \p{cased}\p{case-ignorable}*U+03A3!(\p{case-ignorable}*\p{cased})
  8359. where ! is a negation and \p{xxx} is a character with property xxx.
  8360. */
  8361. for (j = i - 1; j >= 0; j--) {
  8362. c = PyUnicode_READ(kind, data, j);
  8363. if (!_PyUnicode_IsCaseIgnorable(c))
  8364. break;
  8365. }
  8366. final_sigma = j >= 0 && _PyUnicode_IsCased(c);
  8367. if (final_sigma) {
  8368. for (j = i + 1; j < length; j++) {
  8369. c = PyUnicode_READ(kind, data, j);
  8370. if (!_PyUnicode_IsCaseIgnorable(c))
  8371. break;
  8372. }
  8373. final_sigma = j == length || !_PyUnicode_IsCased(c);
  8374. }
  8375. return (final_sigma) ? 0x3C2 : 0x3C3;
  8376. }
  8377. static int
  8378. lower_ucs4(int kind, const void *data, Py_ssize_t length, Py_ssize_t i,
  8379. Py_UCS4 c, Py_UCS4 *mapped)
  8380. {
  8381. /* Obscure special case. */
  8382. if (c == 0x3A3) {
  8383. mapped[0] = handle_capital_sigma(kind, data, length, i);
  8384. return 1;
  8385. }
  8386. return _PyUnicode_ToLowerFull(c, mapped);
  8387. }
  8388. static Py_ssize_t
  8389. do_capitalize(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8390. {
  8391. Py_ssize_t i, k = 0;
  8392. int n_res, j;
  8393. Py_UCS4 c, mapped[3];
  8394. c = PyUnicode_READ(kind, data, 0);
  8395. n_res = _PyUnicode_ToTitleFull(c, mapped);
  8396. for (j = 0; j < n_res; j++) {
  8397. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8398. res[k++] = mapped[j];
  8399. }
  8400. for (i = 1; i < length; i++) {
  8401. c = PyUnicode_READ(kind, data, i);
  8402. n_res = lower_ucs4(kind, data, length, i, c, mapped);
  8403. for (j = 0; j < n_res; j++) {
  8404. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8405. res[k++] = mapped[j];
  8406. }
  8407. }
  8408. return k;
  8409. }
  8410. static Py_ssize_t
  8411. do_swapcase(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar) {
  8412. Py_ssize_t i, k = 0;
  8413. for (i = 0; i < length; i++) {
  8414. Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
  8415. int n_res, j;
  8416. if (Py_UNICODE_ISUPPER(c)) {
  8417. n_res = lower_ucs4(kind, data, length, i, c, mapped);
  8418. }
  8419. else if (Py_UNICODE_ISLOWER(c)) {
  8420. n_res = _PyUnicode_ToUpperFull(c, mapped);
  8421. }
  8422. else {
  8423. n_res = 1;
  8424. mapped[0] = c;
  8425. }
  8426. for (j = 0; j < n_res; j++) {
  8427. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8428. res[k++] = mapped[j];
  8429. }
  8430. }
  8431. return k;
  8432. }
  8433. static Py_ssize_t
  8434. do_upper_or_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res,
  8435. Py_UCS4 *maxchar, int lower)
  8436. {
  8437. Py_ssize_t i, k = 0;
  8438. for (i = 0; i < length; i++) {
  8439. Py_UCS4 c = PyUnicode_READ(kind, data, i), mapped[3];
  8440. int n_res, j;
  8441. if (lower)
  8442. n_res = lower_ucs4(kind, data, length, i, c, mapped);
  8443. else
  8444. n_res = _PyUnicode_ToUpperFull(c, mapped);
  8445. for (j = 0; j < n_res; j++) {
  8446. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8447. res[k++] = mapped[j];
  8448. }
  8449. }
  8450. return k;
  8451. }
  8452. static Py_ssize_t
  8453. do_upper(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8454. {
  8455. return do_upper_or_lower(kind, data, length, res, maxchar, 0);
  8456. }
  8457. static Py_ssize_t
  8458. do_lower(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8459. {
  8460. return do_upper_or_lower(kind, data, length, res, maxchar, 1);
  8461. }
  8462. static Py_ssize_t
  8463. do_casefold(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8464. {
  8465. Py_ssize_t i, k = 0;
  8466. for (i = 0; i < length; i++) {
  8467. Py_UCS4 c = PyUnicode_READ(kind, data, i);
  8468. Py_UCS4 mapped[3];
  8469. int j, n_res = _PyUnicode_ToFoldedFull(c, mapped);
  8470. for (j = 0; j < n_res; j++) {
  8471. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8472. res[k++] = mapped[j];
  8473. }
  8474. }
  8475. return k;
  8476. }
  8477. static Py_ssize_t
  8478. do_title(int kind, const void *data, Py_ssize_t length, Py_UCS4 *res, Py_UCS4 *maxchar)
  8479. {
  8480. Py_ssize_t i, k = 0;
  8481. int previous_is_cased;
  8482. previous_is_cased = 0;
  8483. for (i = 0; i < length; i++) {
  8484. const Py_UCS4 c = PyUnicode_READ(kind, data, i);
  8485. Py_UCS4 mapped[3];
  8486. int n_res, j;
  8487. if (previous_is_cased)
  8488. n_res = lower_ucs4(kind, data, length, i, c, mapped);
  8489. else
  8490. n_res = _PyUnicode_ToTitleFull(c, mapped);
  8491. for (j = 0; j < n_res; j++) {
  8492. *maxchar = Py_MAX(*maxchar, mapped[j]);
  8493. res[k++] = mapped[j];
  8494. }
  8495. previous_is_cased = _PyUnicode_IsCased(c);
  8496. }
  8497. return k;
  8498. }
  8499. static PyObject *
  8500. case_operation(PyObject *self,
  8501. Py_ssize_t (*perform)(int, const void *, Py_ssize_t, Py_UCS4 *, Py_UCS4 *))
  8502. {
  8503. PyObject *res = NULL;
  8504. Py_ssize_t length, newlength = 0;
  8505. int kind, outkind;
  8506. const void *data;
  8507. void *outdata;
  8508. Py_UCS4 maxchar = 0, *tmp, *tmpend;
  8509. kind = PyUnicode_KIND(self);
  8510. data = PyUnicode_DATA(self);
  8511. length = PyUnicode_GET_LENGTH(self);
  8512. if ((size_t) length > PY_SSIZE_T_MAX / (3 * sizeof(Py_UCS4))) {
  8513. PyErr_SetString(PyExc_OverflowError, "string is too long");
  8514. return NULL;
  8515. }
  8516. tmp = PyMem_Malloc(sizeof(Py_UCS4) * 3 * length);
  8517. if (tmp == NULL)
  8518. return PyErr_NoMemory();
  8519. newlength = perform(kind, data, length, tmp, &maxchar);
  8520. res = PyUnicode_New(newlength, maxchar);
  8521. if (res == NULL)
  8522. goto leave;
  8523. tmpend = tmp + newlength;
  8524. outdata = PyUnicode_DATA(res);
  8525. outkind = PyUnicode_KIND(res);
  8526. switch (outkind) {
  8527. case PyUnicode_1BYTE_KIND:
  8528. _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, tmp, tmpend, outdata);
  8529. break;
  8530. case PyUnicode_2BYTE_KIND:
  8531. _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, tmp, tmpend, outdata);
  8532. break;
  8533. case PyUnicode_4BYTE_KIND:
  8534. memcpy(outdata, tmp, sizeof(Py_UCS4) * newlength);
  8535. break;
  8536. default:
  8537. Py_UNREACHABLE();
  8538. }
  8539. leave:
  8540. PyMem_Free(tmp);
  8541. return res;
  8542. }
  8543. PyObject *
  8544. PyUnicode_Join(PyObject *separator, PyObject *seq)
  8545. {
  8546. PyObject *res;
  8547. PyObject *fseq;
  8548. Py_ssize_t seqlen;
  8549. PyObject **items;
  8550. fseq = PySequence_Fast(seq, "can only join an iterable");
  8551. if (fseq == NULL) {
  8552. return NULL;
  8553. }
  8554. /* NOTE: the following code can't call back into Python code,
  8555. * so we are sure that fseq won't be mutated.
  8556. */
  8557. items = PySequence_Fast_ITEMS(fseq);
  8558. seqlen = PySequence_Fast_GET_SIZE(fseq);
  8559. res = _PyUnicode_JoinArray(separator, items, seqlen);
  8560. Py_DECREF(fseq);
  8561. return res;
  8562. }
  8563. PyObject *
  8564. _PyUnicode_JoinArray(PyObject *separator, PyObject *const *items, Py_ssize_t seqlen)
  8565. {
  8566. PyObject *res = NULL; /* the result */
  8567. PyObject *sep = NULL;
  8568. Py_ssize_t seplen;
  8569. PyObject *item;
  8570. Py_ssize_t sz, i, res_offset;
  8571. Py_UCS4 maxchar;
  8572. Py_UCS4 item_maxchar;
  8573. int use_memcpy;
  8574. unsigned char *res_data = NULL, *sep_data = NULL;
  8575. PyObject *last_obj;
  8576. int kind = 0;
  8577. /* If empty sequence, return u"". */
  8578. if (seqlen == 0) {
  8579. _Py_RETURN_UNICODE_EMPTY();
  8580. }
  8581. /* If singleton sequence with an exact Unicode, return that. */
  8582. last_obj = NULL;
  8583. if (seqlen == 1) {
  8584. if (PyUnicode_CheckExact(items[0])) {
  8585. res = items[0];
  8586. return Py_NewRef(res);
  8587. }
  8588. seplen = 0;
  8589. maxchar = 0;
  8590. }
  8591. else {
  8592. /* Set up sep and seplen */
  8593. if (separator == NULL) {
  8594. /* fall back to a blank space separator */
  8595. sep = PyUnicode_FromOrdinal(' ');
  8596. if (!sep)
  8597. goto onError;
  8598. seplen = 1;
  8599. maxchar = 32;
  8600. }
  8601. else {
  8602. if (!PyUnicode_Check(separator)) {
  8603. PyErr_Format(PyExc_TypeError,
  8604. "separator: expected str instance,"
  8605. " %.80s found",
  8606. Py_TYPE(separator)->tp_name);
  8607. goto onError;
  8608. }
  8609. sep = separator;
  8610. seplen = PyUnicode_GET_LENGTH(separator);
  8611. maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
  8612. /* inc refcount to keep this code path symmetric with the
  8613. above case of a blank separator */
  8614. Py_INCREF(sep);
  8615. }
  8616. last_obj = sep;
  8617. }
  8618. /* There are at least two things to join, or else we have a subclass
  8619. * of str in the sequence.
  8620. * Do a pre-pass to figure out the total amount of space we'll
  8621. * need (sz), and see whether all argument are strings.
  8622. */
  8623. sz = 0;
  8624. #ifdef Py_DEBUG
  8625. use_memcpy = 0;
  8626. #else
  8627. use_memcpy = 1;
  8628. #endif
  8629. for (i = 0; i < seqlen; i++) {
  8630. size_t add_sz;
  8631. item = items[i];
  8632. if (!PyUnicode_Check(item)) {
  8633. PyErr_Format(PyExc_TypeError,
  8634. "sequence item %zd: expected str instance,"
  8635. " %.80s found",
  8636. i, Py_TYPE(item)->tp_name);
  8637. goto onError;
  8638. }
  8639. add_sz = PyUnicode_GET_LENGTH(item);
  8640. item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
  8641. maxchar = Py_MAX(maxchar, item_maxchar);
  8642. if (i != 0) {
  8643. add_sz += seplen;
  8644. }
  8645. if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {
  8646. PyErr_SetString(PyExc_OverflowError,
  8647. "join() result is too long for a Python string");
  8648. goto onError;
  8649. }
  8650. sz += add_sz;
  8651. if (use_memcpy && last_obj != NULL) {
  8652. if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
  8653. use_memcpy = 0;
  8654. }
  8655. last_obj = item;
  8656. }
  8657. res = PyUnicode_New(sz, maxchar);
  8658. if (res == NULL)
  8659. goto onError;
  8660. /* Catenate everything. */
  8661. #ifdef Py_DEBUG
  8662. use_memcpy = 0;
  8663. #else
  8664. if (use_memcpy) {
  8665. res_data = PyUnicode_1BYTE_DATA(res);
  8666. kind = PyUnicode_KIND(res);
  8667. if (seplen != 0)
  8668. sep_data = PyUnicode_1BYTE_DATA(sep);
  8669. }
  8670. #endif
  8671. if (use_memcpy) {
  8672. for (i = 0; i < seqlen; ++i) {
  8673. Py_ssize_t itemlen;
  8674. item = items[i];
  8675. /* Copy item, and maybe the separator. */
  8676. if (i && seplen != 0) {
  8677. memcpy(res_data,
  8678. sep_data,
  8679. kind * seplen);
  8680. res_data += kind * seplen;
  8681. }
  8682. itemlen = PyUnicode_GET_LENGTH(item);
  8683. if (itemlen != 0) {
  8684. memcpy(res_data,
  8685. PyUnicode_DATA(item),
  8686. kind * itemlen);
  8687. res_data += kind * itemlen;
  8688. }
  8689. }
  8690. assert(res_data == PyUnicode_1BYTE_DATA(res)
  8691. + kind * PyUnicode_GET_LENGTH(res));
  8692. }
  8693. else {
  8694. for (i = 0, res_offset = 0; i < seqlen; ++i) {
  8695. Py_ssize_t itemlen;
  8696. item = items[i];
  8697. /* Copy item, and maybe the separator. */
  8698. if (i && seplen != 0) {
  8699. _PyUnicode_FastCopyCharacters(res, res_offset, sep, 0, seplen);
  8700. res_offset += seplen;
  8701. }
  8702. itemlen = PyUnicode_GET_LENGTH(item);
  8703. if (itemlen != 0) {
  8704. _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);
  8705. res_offset += itemlen;
  8706. }
  8707. }
  8708. assert(res_offset == PyUnicode_GET_LENGTH(res));
  8709. }
  8710. Py_XDECREF(sep);
  8711. assert(_PyUnicode_CheckConsistency(res, 1));
  8712. return res;
  8713. onError:
  8714. Py_XDECREF(sep);
  8715. Py_XDECREF(res);
  8716. return NULL;
  8717. }
  8718. void
  8719. _PyUnicode_FastFill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
  8720. Py_UCS4 fill_char)
  8721. {
  8722. const int kind = PyUnicode_KIND(unicode);
  8723. void *data = PyUnicode_DATA(unicode);
  8724. assert(unicode_modifiable(unicode));
  8725. assert(fill_char <= PyUnicode_MAX_CHAR_VALUE(unicode));
  8726. assert(start >= 0);
  8727. assert(start + length <= PyUnicode_GET_LENGTH(unicode));
  8728. unicode_fill(kind, data, fill_char, start, length);
  8729. }
  8730. Py_ssize_t
  8731. PyUnicode_Fill(PyObject *unicode, Py_ssize_t start, Py_ssize_t length,
  8732. Py_UCS4 fill_char)
  8733. {
  8734. Py_ssize_t maxlen;
  8735. if (!PyUnicode_Check(unicode)) {
  8736. PyErr_BadInternalCall();
  8737. return -1;
  8738. }
  8739. if (unicode_check_modifiable(unicode))
  8740. return -1;
  8741. if (start < 0) {
  8742. PyErr_SetString(PyExc_IndexError, "string index out of range");
  8743. return -1;
  8744. }
  8745. if (fill_char > PyUnicode_MAX_CHAR_VALUE(unicode)) {
  8746. PyErr_SetString(PyExc_ValueError,
  8747. "fill character is bigger than "
  8748. "the string maximum character");
  8749. return -1;
  8750. }
  8751. maxlen = PyUnicode_GET_LENGTH(unicode) - start;
  8752. length = Py_MIN(maxlen, length);
  8753. if (length <= 0)
  8754. return 0;
  8755. _PyUnicode_FastFill(unicode, start, length, fill_char);
  8756. return length;
  8757. }
  8758. static PyObject *
  8759. pad(PyObject *self,
  8760. Py_ssize_t left,
  8761. Py_ssize_t right,
  8762. Py_UCS4 fill)
  8763. {
  8764. PyObject *u;
  8765. Py_UCS4 maxchar;
  8766. int kind;
  8767. void *data;
  8768. if (left < 0)
  8769. left = 0;
  8770. if (right < 0)
  8771. right = 0;
  8772. if (left == 0 && right == 0)
  8773. return unicode_result_unchanged(self);
  8774. if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
  8775. right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
  8776. PyErr_SetString(PyExc_OverflowError, "padded string is too long");
  8777. return NULL;
  8778. }
  8779. maxchar = PyUnicode_MAX_CHAR_VALUE(self);
  8780. maxchar = Py_MAX(maxchar, fill);
  8781. u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
  8782. if (!u)
  8783. return NULL;
  8784. kind = PyUnicode_KIND(u);
  8785. data = PyUnicode_DATA(u);
  8786. if (left)
  8787. unicode_fill(kind, data, fill, 0, left);
  8788. if (right)
  8789. unicode_fill(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
  8790. _PyUnicode_FastCopyCharacters(u, left, self, 0, _PyUnicode_LENGTH(self));
  8791. assert(_PyUnicode_CheckConsistency(u, 1));
  8792. return u;
  8793. }
  8794. PyObject *
  8795. PyUnicode_Splitlines(PyObject *string, int keepends)
  8796. {
  8797. PyObject *list;
  8798. if (ensure_unicode(string) < 0)
  8799. return NULL;
  8800. switch (PyUnicode_KIND(string)) {
  8801. case PyUnicode_1BYTE_KIND:
  8802. if (PyUnicode_IS_ASCII(string))
  8803. list = asciilib_splitlines(
  8804. string, PyUnicode_1BYTE_DATA(string),
  8805. PyUnicode_GET_LENGTH(string), keepends);
  8806. else
  8807. list = ucs1lib_splitlines(
  8808. string, PyUnicode_1BYTE_DATA(string),
  8809. PyUnicode_GET_LENGTH(string), keepends);
  8810. break;
  8811. case PyUnicode_2BYTE_KIND:
  8812. list = ucs2lib_splitlines(
  8813. string, PyUnicode_2BYTE_DATA(string),
  8814. PyUnicode_GET_LENGTH(string), keepends);
  8815. break;
  8816. case PyUnicode_4BYTE_KIND:
  8817. list = ucs4lib_splitlines(
  8818. string, PyUnicode_4BYTE_DATA(string),
  8819. PyUnicode_GET_LENGTH(string), keepends);
  8820. break;
  8821. default:
  8822. Py_UNREACHABLE();
  8823. }
  8824. return list;
  8825. }
  8826. static PyObject *
  8827. split(PyObject *self,
  8828. PyObject *substring,
  8829. Py_ssize_t maxcount)
  8830. {
  8831. int kind1, kind2;
  8832. const void *buf1, *buf2;
  8833. Py_ssize_t len1, len2;
  8834. PyObject* out;
  8835. len1 = PyUnicode_GET_LENGTH(self);
  8836. kind1 = PyUnicode_KIND(self);
  8837. if (substring == NULL) {
  8838. if (maxcount < 0) {
  8839. maxcount = (len1 - 1) / 2 + 1;
  8840. }
  8841. switch (kind1) {
  8842. case PyUnicode_1BYTE_KIND:
  8843. if (PyUnicode_IS_ASCII(self))
  8844. return asciilib_split_whitespace(
  8845. self, PyUnicode_1BYTE_DATA(self),
  8846. len1, maxcount
  8847. );
  8848. else
  8849. return ucs1lib_split_whitespace(
  8850. self, PyUnicode_1BYTE_DATA(self),
  8851. len1, maxcount
  8852. );
  8853. case PyUnicode_2BYTE_KIND:
  8854. return ucs2lib_split_whitespace(
  8855. self, PyUnicode_2BYTE_DATA(self),
  8856. len1, maxcount
  8857. );
  8858. case PyUnicode_4BYTE_KIND:
  8859. return ucs4lib_split_whitespace(
  8860. self, PyUnicode_4BYTE_DATA(self),
  8861. len1, maxcount
  8862. );
  8863. default:
  8864. Py_UNREACHABLE();
  8865. }
  8866. }
  8867. kind2 = PyUnicode_KIND(substring);
  8868. len2 = PyUnicode_GET_LENGTH(substring);
  8869. if (maxcount < 0) {
  8870. // if len2 == 0, it will raise ValueError.
  8871. maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
  8872. // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
  8873. maxcount = maxcount < 0 ? len1 : maxcount;
  8874. }
  8875. if (kind1 < kind2 || len1 < len2) {
  8876. out = PyList_New(1);
  8877. if (out == NULL)
  8878. return NULL;
  8879. PyList_SET_ITEM(out, 0, Py_NewRef(self));
  8880. return out;
  8881. }
  8882. buf1 = PyUnicode_DATA(self);
  8883. buf2 = PyUnicode_DATA(substring);
  8884. if (kind2 != kind1) {
  8885. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  8886. if (!buf2)
  8887. return NULL;
  8888. }
  8889. switch (kind1) {
  8890. case PyUnicode_1BYTE_KIND:
  8891. if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
  8892. out = asciilib_split(
  8893. self, buf1, len1, buf2, len2, maxcount);
  8894. else
  8895. out = ucs1lib_split(
  8896. self, buf1, len1, buf2, len2, maxcount);
  8897. break;
  8898. case PyUnicode_2BYTE_KIND:
  8899. out = ucs2lib_split(
  8900. self, buf1, len1, buf2, len2, maxcount);
  8901. break;
  8902. case PyUnicode_4BYTE_KIND:
  8903. out = ucs4lib_split(
  8904. self, buf1, len1, buf2, len2, maxcount);
  8905. break;
  8906. default:
  8907. out = NULL;
  8908. }
  8909. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
  8910. if (kind2 != kind1)
  8911. PyMem_Free((void *)buf2);
  8912. return out;
  8913. }
  8914. static PyObject *
  8915. rsplit(PyObject *self,
  8916. PyObject *substring,
  8917. Py_ssize_t maxcount)
  8918. {
  8919. int kind1, kind2;
  8920. const void *buf1, *buf2;
  8921. Py_ssize_t len1, len2;
  8922. PyObject* out;
  8923. len1 = PyUnicode_GET_LENGTH(self);
  8924. kind1 = PyUnicode_KIND(self);
  8925. if (substring == NULL) {
  8926. if (maxcount < 0) {
  8927. maxcount = (len1 - 1) / 2 + 1;
  8928. }
  8929. switch (kind1) {
  8930. case PyUnicode_1BYTE_KIND:
  8931. if (PyUnicode_IS_ASCII(self))
  8932. return asciilib_rsplit_whitespace(
  8933. self, PyUnicode_1BYTE_DATA(self),
  8934. len1, maxcount
  8935. );
  8936. else
  8937. return ucs1lib_rsplit_whitespace(
  8938. self, PyUnicode_1BYTE_DATA(self),
  8939. len1, maxcount
  8940. );
  8941. case PyUnicode_2BYTE_KIND:
  8942. return ucs2lib_rsplit_whitespace(
  8943. self, PyUnicode_2BYTE_DATA(self),
  8944. len1, maxcount
  8945. );
  8946. case PyUnicode_4BYTE_KIND:
  8947. return ucs4lib_rsplit_whitespace(
  8948. self, PyUnicode_4BYTE_DATA(self),
  8949. len1, maxcount
  8950. );
  8951. default:
  8952. Py_UNREACHABLE();
  8953. }
  8954. }
  8955. kind2 = PyUnicode_KIND(substring);
  8956. len2 = PyUnicode_GET_LENGTH(substring);
  8957. if (maxcount < 0) {
  8958. // if len2 == 0, it will raise ValueError.
  8959. maxcount = len2 == 0 ? 0 : (len1 / len2) + 1;
  8960. // handle expected overflow case: (Py_SSIZE_T_MAX / 1) + 1
  8961. maxcount = maxcount < 0 ? len1 : maxcount;
  8962. }
  8963. if (kind1 < kind2 || len1 < len2) {
  8964. out = PyList_New(1);
  8965. if (out == NULL)
  8966. return NULL;
  8967. PyList_SET_ITEM(out, 0, Py_NewRef(self));
  8968. return out;
  8969. }
  8970. buf1 = PyUnicode_DATA(self);
  8971. buf2 = PyUnicode_DATA(substring);
  8972. if (kind2 != kind1) {
  8973. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  8974. if (!buf2)
  8975. return NULL;
  8976. }
  8977. switch (kind1) {
  8978. case PyUnicode_1BYTE_KIND:
  8979. if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
  8980. out = asciilib_rsplit(
  8981. self, buf1, len1, buf2, len2, maxcount);
  8982. else
  8983. out = ucs1lib_rsplit(
  8984. self, buf1, len1, buf2, len2, maxcount);
  8985. break;
  8986. case PyUnicode_2BYTE_KIND:
  8987. out = ucs2lib_rsplit(
  8988. self, buf1, len1, buf2, len2, maxcount);
  8989. break;
  8990. case PyUnicode_4BYTE_KIND:
  8991. out = ucs4lib_rsplit(
  8992. self, buf1, len1, buf2, len2, maxcount);
  8993. break;
  8994. default:
  8995. out = NULL;
  8996. }
  8997. assert((kind2 != kind1) == (buf2 != PyUnicode_DATA(substring)));
  8998. if (kind2 != kind1)
  8999. PyMem_Free((void *)buf2);
  9000. return out;
  9001. }
  9002. static Py_ssize_t
  9003. anylib_find(int kind, PyObject *str1, const void *buf1, Py_ssize_t len1,
  9004. PyObject *str2, const void *buf2, Py_ssize_t len2, Py_ssize_t offset)
  9005. {
  9006. switch (kind) {
  9007. case PyUnicode_1BYTE_KIND:
  9008. if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
  9009. return asciilib_find(buf1, len1, buf2, len2, offset);
  9010. else
  9011. return ucs1lib_find(buf1, len1, buf2, len2, offset);
  9012. case PyUnicode_2BYTE_KIND:
  9013. return ucs2lib_find(buf1, len1, buf2, len2, offset);
  9014. case PyUnicode_4BYTE_KIND:
  9015. return ucs4lib_find(buf1, len1, buf2, len2, offset);
  9016. }
  9017. Py_UNREACHABLE();
  9018. }
  9019. static Py_ssize_t
  9020. anylib_count(int kind, PyObject *sstr, const void* sbuf, Py_ssize_t slen,
  9021. PyObject *str1, const void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
  9022. {
  9023. switch (kind) {
  9024. case PyUnicode_1BYTE_KIND:
  9025. return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
  9026. case PyUnicode_2BYTE_KIND:
  9027. return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
  9028. case PyUnicode_4BYTE_KIND:
  9029. return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
  9030. }
  9031. Py_UNREACHABLE();
  9032. }
  9033. static void
  9034. replace_1char_inplace(PyObject *u, Py_ssize_t pos,
  9035. Py_UCS4 u1, Py_UCS4 u2, Py_ssize_t maxcount)
  9036. {
  9037. int kind = PyUnicode_KIND(u);
  9038. void *data = PyUnicode_DATA(u);
  9039. Py_ssize_t len = PyUnicode_GET_LENGTH(u);
  9040. if (kind == PyUnicode_1BYTE_KIND) {
  9041. ucs1lib_replace_1char_inplace((Py_UCS1 *)data + pos,
  9042. (Py_UCS1 *)data + len,
  9043. u1, u2, maxcount);
  9044. }
  9045. else if (kind == PyUnicode_2BYTE_KIND) {
  9046. ucs2lib_replace_1char_inplace((Py_UCS2 *)data + pos,
  9047. (Py_UCS2 *)data + len,
  9048. u1, u2, maxcount);
  9049. }
  9050. else {
  9051. assert(kind == PyUnicode_4BYTE_KIND);
  9052. ucs4lib_replace_1char_inplace((Py_UCS4 *)data + pos,
  9053. (Py_UCS4 *)data + len,
  9054. u1, u2, maxcount);
  9055. }
  9056. }
  9057. static PyObject *
  9058. replace(PyObject *self, PyObject *str1,
  9059. PyObject *str2, Py_ssize_t maxcount)
  9060. {
  9061. PyObject *u;
  9062. const char *sbuf = PyUnicode_DATA(self);
  9063. const void *buf1 = PyUnicode_DATA(str1);
  9064. const void *buf2 = PyUnicode_DATA(str2);
  9065. int srelease = 0, release1 = 0, release2 = 0;
  9066. int skind = PyUnicode_KIND(self);
  9067. int kind1 = PyUnicode_KIND(str1);
  9068. int kind2 = PyUnicode_KIND(str2);
  9069. Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
  9070. Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
  9071. Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
  9072. int mayshrink;
  9073. Py_UCS4 maxchar, maxchar_str1, maxchar_str2;
  9074. if (slen < len1)
  9075. goto nothing;
  9076. if (maxcount < 0)
  9077. maxcount = PY_SSIZE_T_MAX;
  9078. else if (maxcount == 0)
  9079. goto nothing;
  9080. if (str1 == str2)
  9081. goto nothing;
  9082. maxchar = PyUnicode_MAX_CHAR_VALUE(self);
  9083. maxchar_str1 = PyUnicode_MAX_CHAR_VALUE(str1);
  9084. if (maxchar < maxchar_str1)
  9085. /* substring too wide to be present */
  9086. goto nothing;
  9087. maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
  9088. /* Replacing str1 with str2 may cause a maxchar reduction in the
  9089. result string. */
  9090. mayshrink = (maxchar_str2 < maxchar_str1) && (maxchar == maxchar_str1);
  9091. maxchar = Py_MAX(maxchar, maxchar_str2);
  9092. if (len1 == len2) {
  9093. /* same length */
  9094. if (len1 == 0)
  9095. goto nothing;
  9096. if (len1 == 1) {
  9097. /* replace characters */
  9098. Py_UCS4 u1, u2;
  9099. Py_ssize_t pos;
  9100. u1 = PyUnicode_READ(kind1, buf1, 0);
  9101. pos = findchar(sbuf, skind, slen, u1, 1);
  9102. if (pos < 0)
  9103. goto nothing;
  9104. u2 = PyUnicode_READ(kind2, buf2, 0);
  9105. u = PyUnicode_New(slen, maxchar);
  9106. if (!u)
  9107. goto error;
  9108. _PyUnicode_FastCopyCharacters(u, 0, self, 0, slen);
  9109. replace_1char_inplace(u, pos, u1, u2, maxcount);
  9110. }
  9111. else {
  9112. int rkind = skind;
  9113. char *res;
  9114. Py_ssize_t i;
  9115. if (kind1 < rkind) {
  9116. /* widen substring */
  9117. buf1 = unicode_askind(kind1, buf1, len1, rkind);
  9118. if (!buf1) goto error;
  9119. release1 = 1;
  9120. }
  9121. i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
  9122. if (i < 0)
  9123. goto nothing;
  9124. if (rkind > kind2) {
  9125. /* widen replacement */
  9126. buf2 = unicode_askind(kind2, buf2, len2, rkind);
  9127. if (!buf2) goto error;
  9128. release2 = 1;
  9129. }
  9130. else if (rkind < kind2) {
  9131. /* widen self and buf1 */
  9132. rkind = kind2;
  9133. if (release1) {
  9134. assert(buf1 != PyUnicode_DATA(str1));
  9135. PyMem_Free((void *)buf1);
  9136. buf1 = PyUnicode_DATA(str1);
  9137. release1 = 0;
  9138. }
  9139. sbuf = unicode_askind(skind, sbuf, slen, rkind);
  9140. if (!sbuf) goto error;
  9141. srelease = 1;
  9142. buf1 = unicode_askind(kind1, buf1, len1, rkind);
  9143. if (!buf1) goto error;
  9144. release1 = 1;
  9145. }
  9146. u = PyUnicode_New(slen, maxchar);
  9147. if (!u)
  9148. goto error;
  9149. assert(PyUnicode_KIND(u) == rkind);
  9150. res = PyUnicode_DATA(u);
  9151. memcpy(res, sbuf, rkind * slen);
  9152. /* change everything in-place, starting with this one */
  9153. memcpy(res + rkind * i,
  9154. buf2,
  9155. rkind * len2);
  9156. i += len1;
  9157. while ( --maxcount > 0) {
  9158. i = anylib_find(rkind, self,
  9159. sbuf+rkind*i, slen-i,
  9160. str1, buf1, len1, i);
  9161. if (i == -1)
  9162. break;
  9163. memcpy(res + rkind * i,
  9164. buf2,
  9165. rkind * len2);
  9166. i += len1;
  9167. }
  9168. }
  9169. }
  9170. else {
  9171. Py_ssize_t n, i, j, ires;
  9172. Py_ssize_t new_size;
  9173. int rkind = skind;
  9174. char *res;
  9175. if (kind1 < rkind) {
  9176. /* widen substring */
  9177. buf1 = unicode_askind(kind1, buf1, len1, rkind);
  9178. if (!buf1) goto error;
  9179. release1 = 1;
  9180. }
  9181. n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
  9182. if (n == 0)
  9183. goto nothing;
  9184. if (kind2 < rkind) {
  9185. /* widen replacement */
  9186. buf2 = unicode_askind(kind2, buf2, len2, rkind);
  9187. if (!buf2) goto error;
  9188. release2 = 1;
  9189. }
  9190. else if (kind2 > rkind) {
  9191. /* widen self and buf1 */
  9192. rkind = kind2;
  9193. sbuf = unicode_askind(skind, sbuf, slen, rkind);
  9194. if (!sbuf) goto error;
  9195. srelease = 1;
  9196. if (release1) {
  9197. assert(buf1 != PyUnicode_DATA(str1));
  9198. PyMem_Free((void *)buf1);
  9199. buf1 = PyUnicode_DATA(str1);
  9200. release1 = 0;
  9201. }
  9202. buf1 = unicode_askind(kind1, buf1, len1, rkind);
  9203. if (!buf1) goto error;
  9204. release1 = 1;
  9205. }
  9206. /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
  9207. PyUnicode_GET_LENGTH(str1)); */
  9208. if (len1 < len2 && len2 - len1 > (PY_SSIZE_T_MAX - slen) / n) {
  9209. PyErr_SetString(PyExc_OverflowError,
  9210. "replace string is too long");
  9211. goto error;
  9212. }
  9213. new_size = slen + n * (len2 - len1);
  9214. if (new_size == 0) {
  9215. u = unicode_new_empty();
  9216. goto done;
  9217. }
  9218. if (new_size > (PY_SSIZE_T_MAX / rkind)) {
  9219. PyErr_SetString(PyExc_OverflowError,
  9220. "replace string is too long");
  9221. goto error;
  9222. }
  9223. u = PyUnicode_New(new_size, maxchar);
  9224. if (!u)
  9225. goto error;
  9226. assert(PyUnicode_KIND(u) == rkind);
  9227. res = PyUnicode_DATA(u);
  9228. ires = i = 0;
  9229. if (len1 > 0) {
  9230. while (n-- > 0) {
  9231. /* look for next match */
  9232. j = anylib_find(rkind, self,
  9233. sbuf + rkind * i, slen-i,
  9234. str1, buf1, len1, i);
  9235. if (j == -1)
  9236. break;
  9237. else if (j > i) {
  9238. /* copy unchanged part [i:j] */
  9239. memcpy(res + rkind * ires,
  9240. sbuf + rkind * i,
  9241. rkind * (j-i));
  9242. ires += j - i;
  9243. }
  9244. /* copy substitution string */
  9245. if (len2 > 0) {
  9246. memcpy(res + rkind * ires,
  9247. buf2,
  9248. rkind * len2);
  9249. ires += len2;
  9250. }
  9251. i = j + len1;
  9252. }
  9253. if (i < slen)
  9254. /* copy tail [i:] */
  9255. memcpy(res + rkind * ires,
  9256. sbuf + rkind * i,
  9257. rkind * (slen-i));
  9258. }
  9259. else {
  9260. /* interleave */
  9261. while (n > 0) {
  9262. memcpy(res + rkind * ires,
  9263. buf2,
  9264. rkind * len2);
  9265. ires += len2;
  9266. if (--n <= 0)
  9267. break;
  9268. memcpy(res + rkind * ires,
  9269. sbuf + rkind * i,
  9270. rkind);
  9271. ires++;
  9272. i++;
  9273. }
  9274. memcpy(res + rkind * ires,
  9275. sbuf + rkind * i,
  9276. rkind * (slen-i));
  9277. }
  9278. }
  9279. if (mayshrink) {
  9280. unicode_adjust_maxchar(&u);
  9281. if (u == NULL)
  9282. goto error;
  9283. }
  9284. done:
  9285. assert(srelease == (sbuf != PyUnicode_DATA(self)));
  9286. assert(release1 == (buf1 != PyUnicode_DATA(str1)));
  9287. assert(release2 == (buf2 != PyUnicode_DATA(str2)));
  9288. if (srelease)
  9289. PyMem_Free((void *)sbuf);
  9290. if (release1)
  9291. PyMem_Free((void *)buf1);
  9292. if (release2)
  9293. PyMem_Free((void *)buf2);
  9294. assert(_PyUnicode_CheckConsistency(u, 1));
  9295. return u;
  9296. nothing:
  9297. /* nothing to replace; return original string (when possible) */
  9298. assert(srelease == (sbuf != PyUnicode_DATA(self)));
  9299. assert(release1 == (buf1 != PyUnicode_DATA(str1)));
  9300. assert(release2 == (buf2 != PyUnicode_DATA(str2)));
  9301. if (srelease)
  9302. PyMem_Free((void *)sbuf);
  9303. if (release1)
  9304. PyMem_Free((void *)buf1);
  9305. if (release2)
  9306. PyMem_Free((void *)buf2);
  9307. return unicode_result_unchanged(self);
  9308. error:
  9309. assert(srelease == (sbuf != PyUnicode_DATA(self)));
  9310. assert(release1 == (buf1 != PyUnicode_DATA(str1)));
  9311. assert(release2 == (buf2 != PyUnicode_DATA(str2)));
  9312. if (srelease)
  9313. PyMem_Free((void *)sbuf);
  9314. if (release1)
  9315. PyMem_Free((void *)buf1);
  9316. if (release2)
  9317. PyMem_Free((void *)buf2);
  9318. return NULL;
  9319. }
  9320. /* --- Unicode Object Methods --------------------------------------------- */
  9321. /*[clinic input]
  9322. str.title as unicode_title
  9323. Return a version of the string where each word is titlecased.
  9324. More specifically, words start with uppercased characters and all remaining
  9325. cased characters have lower case.
  9326. [clinic start generated code]*/
  9327. static PyObject *
  9328. unicode_title_impl(PyObject *self)
  9329. /*[clinic end generated code: output=c75ae03809574902 input=fa945d669b26e683]*/
  9330. {
  9331. return case_operation(self, do_title);
  9332. }
  9333. /*[clinic input]
  9334. str.capitalize as unicode_capitalize
  9335. Return a capitalized version of the string.
  9336. More specifically, make the first character have upper case and the rest lower
  9337. case.
  9338. [clinic start generated code]*/
  9339. static PyObject *
  9340. unicode_capitalize_impl(PyObject *self)
  9341. /*[clinic end generated code: output=e49a4c333cdb7667 input=f4cbf1016938da6d]*/
  9342. {
  9343. if (PyUnicode_GET_LENGTH(self) == 0)
  9344. return unicode_result_unchanged(self);
  9345. return case_operation(self, do_capitalize);
  9346. }
  9347. /*[clinic input]
  9348. str.casefold as unicode_casefold
  9349. Return a version of the string suitable for caseless comparisons.
  9350. [clinic start generated code]*/
  9351. static PyObject *
  9352. unicode_casefold_impl(PyObject *self)
  9353. /*[clinic end generated code: output=0120daf657ca40af input=384d66cc2ae30daf]*/
  9354. {
  9355. if (PyUnicode_IS_ASCII(self))
  9356. return ascii_upper_or_lower(self, 1);
  9357. return case_operation(self, do_casefold);
  9358. }
  9359. /* Argument converter. Accepts a single Unicode character. */
  9360. static int
  9361. convert_uc(PyObject *obj, void *addr)
  9362. {
  9363. Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
  9364. if (!PyUnicode_Check(obj)) {
  9365. PyErr_Format(PyExc_TypeError,
  9366. "The fill character must be a unicode character, "
  9367. "not %.100s", Py_TYPE(obj)->tp_name);
  9368. return 0;
  9369. }
  9370. if (PyUnicode_GET_LENGTH(obj) != 1) {
  9371. PyErr_SetString(PyExc_TypeError,
  9372. "The fill character must be exactly one character long");
  9373. return 0;
  9374. }
  9375. *fillcharloc = PyUnicode_READ_CHAR(obj, 0);
  9376. return 1;
  9377. }
  9378. /*[clinic input]
  9379. str.center as unicode_center
  9380. width: Py_ssize_t
  9381. fillchar: Py_UCS4 = ' '
  9382. /
  9383. Return a centered string of length width.
  9384. Padding is done using the specified fill character (default is a space).
  9385. [clinic start generated code]*/
  9386. static PyObject *
  9387. unicode_center_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
  9388. /*[clinic end generated code: output=420c8859effc7c0c input=b42b247eb26e6519]*/
  9389. {
  9390. Py_ssize_t marg, left;
  9391. if (PyUnicode_GET_LENGTH(self) >= width)
  9392. return unicode_result_unchanged(self);
  9393. marg = width - PyUnicode_GET_LENGTH(self);
  9394. left = marg / 2 + (marg & width & 1);
  9395. return pad(self, left, marg - left, fillchar);
  9396. }
  9397. /* This function assumes that str1 and str2 are readied by the caller. */
  9398. static int
  9399. unicode_compare(PyObject *str1, PyObject *str2)
  9400. {
  9401. #define COMPARE(TYPE1, TYPE2) \
  9402. do { \
  9403. TYPE1* p1 = (TYPE1 *)data1; \
  9404. TYPE2* p2 = (TYPE2 *)data2; \
  9405. TYPE1* end = p1 + len; \
  9406. Py_UCS4 c1, c2; \
  9407. for (; p1 != end; p1++, p2++) { \
  9408. c1 = *p1; \
  9409. c2 = *p2; \
  9410. if (c1 != c2) \
  9411. return (c1 < c2) ? -1 : 1; \
  9412. } \
  9413. } \
  9414. while (0)
  9415. int kind1, kind2;
  9416. const void *data1, *data2;
  9417. Py_ssize_t len1, len2, len;
  9418. kind1 = PyUnicode_KIND(str1);
  9419. kind2 = PyUnicode_KIND(str2);
  9420. data1 = PyUnicode_DATA(str1);
  9421. data2 = PyUnicode_DATA(str2);
  9422. len1 = PyUnicode_GET_LENGTH(str1);
  9423. len2 = PyUnicode_GET_LENGTH(str2);
  9424. len = Py_MIN(len1, len2);
  9425. switch(kind1) {
  9426. case PyUnicode_1BYTE_KIND:
  9427. {
  9428. switch(kind2) {
  9429. case PyUnicode_1BYTE_KIND:
  9430. {
  9431. int cmp = memcmp(data1, data2, len);
  9432. /* normalize result of memcmp() into the range [-1; 1] */
  9433. if (cmp < 0)
  9434. return -1;
  9435. if (cmp > 0)
  9436. return 1;
  9437. break;
  9438. }
  9439. case PyUnicode_2BYTE_KIND:
  9440. COMPARE(Py_UCS1, Py_UCS2);
  9441. break;
  9442. case PyUnicode_4BYTE_KIND:
  9443. COMPARE(Py_UCS1, Py_UCS4);
  9444. break;
  9445. default:
  9446. Py_UNREACHABLE();
  9447. }
  9448. break;
  9449. }
  9450. case PyUnicode_2BYTE_KIND:
  9451. {
  9452. switch(kind2) {
  9453. case PyUnicode_1BYTE_KIND:
  9454. COMPARE(Py_UCS2, Py_UCS1);
  9455. break;
  9456. case PyUnicode_2BYTE_KIND:
  9457. {
  9458. COMPARE(Py_UCS2, Py_UCS2);
  9459. break;
  9460. }
  9461. case PyUnicode_4BYTE_KIND:
  9462. COMPARE(Py_UCS2, Py_UCS4);
  9463. break;
  9464. default:
  9465. Py_UNREACHABLE();
  9466. }
  9467. break;
  9468. }
  9469. case PyUnicode_4BYTE_KIND:
  9470. {
  9471. switch(kind2) {
  9472. case PyUnicode_1BYTE_KIND:
  9473. COMPARE(Py_UCS4, Py_UCS1);
  9474. break;
  9475. case PyUnicode_2BYTE_KIND:
  9476. COMPARE(Py_UCS4, Py_UCS2);
  9477. break;
  9478. case PyUnicode_4BYTE_KIND:
  9479. {
  9480. #if defined(HAVE_WMEMCMP) && SIZEOF_WCHAR_T == 4
  9481. int cmp = wmemcmp((wchar_t *)data1, (wchar_t *)data2, len);
  9482. /* normalize result of wmemcmp() into the range [-1; 1] */
  9483. if (cmp < 0)
  9484. return -1;
  9485. if (cmp > 0)
  9486. return 1;
  9487. #else
  9488. COMPARE(Py_UCS4, Py_UCS4);
  9489. #endif
  9490. break;
  9491. }
  9492. default:
  9493. Py_UNREACHABLE();
  9494. }
  9495. break;
  9496. }
  9497. default:
  9498. Py_UNREACHABLE();
  9499. }
  9500. if (len1 == len2)
  9501. return 0;
  9502. if (len1 < len2)
  9503. return -1;
  9504. else
  9505. return 1;
  9506. #undef COMPARE
  9507. }
  9508. static int
  9509. unicode_compare_eq(PyObject *str1, PyObject *str2)
  9510. {
  9511. int kind;
  9512. const void *data1, *data2;
  9513. Py_ssize_t len;
  9514. int cmp;
  9515. len = PyUnicode_GET_LENGTH(str1);
  9516. if (PyUnicode_GET_LENGTH(str2) != len)
  9517. return 0;
  9518. kind = PyUnicode_KIND(str1);
  9519. if (PyUnicode_KIND(str2) != kind)
  9520. return 0;
  9521. data1 = PyUnicode_DATA(str1);
  9522. data2 = PyUnicode_DATA(str2);
  9523. cmp = memcmp(data1, data2, len * kind);
  9524. return (cmp == 0);
  9525. }
  9526. int
  9527. _PyUnicode_Equal(PyObject *str1, PyObject *str2)
  9528. {
  9529. assert(PyUnicode_Check(str1));
  9530. assert(PyUnicode_Check(str2));
  9531. if (str1 == str2) {
  9532. return 1;
  9533. }
  9534. return unicode_compare_eq(str1, str2);
  9535. }
  9536. int
  9537. PyUnicode_Compare(PyObject *left, PyObject *right)
  9538. {
  9539. if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
  9540. /* a string is equal to itself */
  9541. if (left == right)
  9542. return 0;
  9543. return unicode_compare(left, right);
  9544. }
  9545. PyErr_Format(PyExc_TypeError,
  9546. "Can't compare %.100s and %.100s",
  9547. Py_TYPE(left)->tp_name,
  9548. Py_TYPE(right)->tp_name);
  9549. return -1;
  9550. }
  9551. int
  9552. PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
  9553. {
  9554. Py_ssize_t i;
  9555. int kind;
  9556. Py_UCS4 chr;
  9557. assert(_PyUnicode_CHECK(uni));
  9558. kind = PyUnicode_KIND(uni);
  9559. if (kind == PyUnicode_1BYTE_KIND) {
  9560. const void *data = PyUnicode_1BYTE_DATA(uni);
  9561. size_t len1 = (size_t)PyUnicode_GET_LENGTH(uni);
  9562. size_t len, len2 = strlen(str);
  9563. int cmp;
  9564. len = Py_MIN(len1, len2);
  9565. cmp = memcmp(data, str, len);
  9566. if (cmp != 0) {
  9567. if (cmp < 0)
  9568. return -1;
  9569. else
  9570. return 1;
  9571. }
  9572. if (len1 > len2)
  9573. return 1; /* uni is longer */
  9574. if (len1 < len2)
  9575. return -1; /* str is longer */
  9576. return 0;
  9577. }
  9578. else {
  9579. const void *data = PyUnicode_DATA(uni);
  9580. /* Compare Unicode string and source character set string */
  9581. for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
  9582. if (chr != (unsigned char)str[i])
  9583. return (chr < (unsigned char)(str[i])) ? -1 : 1;
  9584. /* This check keeps Python strings that end in '\0' from comparing equal
  9585. to C strings identical up to that point. */
  9586. if (PyUnicode_GET_LENGTH(uni) != i || chr)
  9587. return 1; /* uni is longer */
  9588. if (str[i])
  9589. return -1; /* str is longer */
  9590. return 0;
  9591. }
  9592. }
  9593. int
  9594. _PyUnicode_EqualToASCIIString(PyObject *unicode, const char *str)
  9595. {
  9596. size_t len;
  9597. assert(_PyUnicode_CHECK(unicode));
  9598. assert(str);
  9599. #ifndef NDEBUG
  9600. for (const char *p = str; *p; p++) {
  9601. assert((unsigned char)*p < 128);
  9602. }
  9603. #endif
  9604. if (!PyUnicode_IS_ASCII(unicode))
  9605. return 0;
  9606. len = (size_t)PyUnicode_GET_LENGTH(unicode);
  9607. return strlen(str) == len &&
  9608. memcmp(PyUnicode_1BYTE_DATA(unicode), str, len) == 0;
  9609. }
  9610. int
  9611. _PyUnicode_EqualToASCIIId(PyObject *left, _Py_Identifier *right)
  9612. {
  9613. PyObject *right_uni;
  9614. assert(_PyUnicode_CHECK(left));
  9615. assert(right->string);
  9616. #ifndef NDEBUG
  9617. for (const char *p = right->string; *p; p++) {
  9618. assert((unsigned char)*p < 128);
  9619. }
  9620. #endif
  9621. if (!PyUnicode_IS_ASCII(left))
  9622. return 0;
  9623. right_uni = _PyUnicode_FromId(right); /* borrowed */
  9624. if (right_uni == NULL) {
  9625. /* memory error or bad data */
  9626. PyErr_Clear();
  9627. return _PyUnicode_EqualToASCIIString(left, right->string);
  9628. }
  9629. if (left == right_uni)
  9630. return 1;
  9631. if (PyUnicode_CHECK_INTERNED(left))
  9632. return 0;
  9633. assert(_PyUnicode_HASH(right_uni) != -1);
  9634. Py_hash_t hash = _PyUnicode_HASH(left);
  9635. if (hash != -1 && hash != _PyUnicode_HASH(right_uni)) {
  9636. return 0;
  9637. }
  9638. return unicode_compare_eq(left, right_uni);
  9639. }
  9640. PyObject *
  9641. PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
  9642. {
  9643. int result;
  9644. if (!PyUnicode_Check(left) || !PyUnicode_Check(right))
  9645. Py_RETURN_NOTIMPLEMENTED;
  9646. if (left == right) {
  9647. switch (op) {
  9648. case Py_EQ:
  9649. case Py_LE:
  9650. case Py_GE:
  9651. /* a string is equal to itself */
  9652. Py_RETURN_TRUE;
  9653. case Py_NE:
  9654. case Py_LT:
  9655. case Py_GT:
  9656. Py_RETURN_FALSE;
  9657. default:
  9658. PyErr_BadArgument();
  9659. return NULL;
  9660. }
  9661. }
  9662. else if (op == Py_EQ || op == Py_NE) {
  9663. result = unicode_compare_eq(left, right);
  9664. result ^= (op == Py_NE);
  9665. return PyBool_FromLong(result);
  9666. }
  9667. else {
  9668. result = unicode_compare(left, right);
  9669. Py_RETURN_RICHCOMPARE(result, 0, op);
  9670. }
  9671. }
  9672. int
  9673. _PyUnicode_EQ(PyObject *aa, PyObject *bb)
  9674. {
  9675. return unicode_eq(aa, bb);
  9676. }
  9677. int
  9678. PyUnicode_Contains(PyObject *str, PyObject *substr)
  9679. {
  9680. int kind1, kind2;
  9681. const void *buf1, *buf2;
  9682. Py_ssize_t len1, len2;
  9683. int result;
  9684. if (!PyUnicode_Check(substr)) {
  9685. PyErr_Format(PyExc_TypeError,
  9686. "'in <string>' requires string as left operand, not %.100s",
  9687. Py_TYPE(substr)->tp_name);
  9688. return -1;
  9689. }
  9690. if (ensure_unicode(str) < 0)
  9691. return -1;
  9692. kind1 = PyUnicode_KIND(str);
  9693. kind2 = PyUnicode_KIND(substr);
  9694. if (kind1 < kind2)
  9695. return 0;
  9696. len1 = PyUnicode_GET_LENGTH(str);
  9697. len2 = PyUnicode_GET_LENGTH(substr);
  9698. if (len1 < len2)
  9699. return 0;
  9700. buf1 = PyUnicode_DATA(str);
  9701. buf2 = PyUnicode_DATA(substr);
  9702. if (len2 == 1) {
  9703. Py_UCS4 ch = PyUnicode_READ(kind2, buf2, 0);
  9704. result = findchar((const char *)buf1, kind1, len1, ch, 1) != -1;
  9705. return result;
  9706. }
  9707. if (kind2 != kind1) {
  9708. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  9709. if (!buf2)
  9710. return -1;
  9711. }
  9712. switch (kind1) {
  9713. case PyUnicode_1BYTE_KIND:
  9714. result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
  9715. break;
  9716. case PyUnicode_2BYTE_KIND:
  9717. result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
  9718. break;
  9719. case PyUnicode_4BYTE_KIND:
  9720. result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
  9721. break;
  9722. default:
  9723. Py_UNREACHABLE();
  9724. }
  9725. assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(substr)));
  9726. if (kind2 != kind1)
  9727. PyMem_Free((void *)buf2);
  9728. return result;
  9729. }
  9730. /* Concat to string or Unicode object giving a new Unicode object. */
  9731. PyObject *
  9732. PyUnicode_Concat(PyObject *left, PyObject *right)
  9733. {
  9734. PyObject *result;
  9735. Py_UCS4 maxchar, maxchar2;
  9736. Py_ssize_t left_len, right_len, new_len;
  9737. if (ensure_unicode(left) < 0)
  9738. return NULL;
  9739. if (!PyUnicode_Check(right)) {
  9740. PyErr_Format(PyExc_TypeError,
  9741. "can only concatenate str (not \"%.200s\") to str",
  9742. Py_TYPE(right)->tp_name);
  9743. return NULL;
  9744. }
  9745. /* Shortcuts */
  9746. PyObject *empty = unicode_get_empty(); // Borrowed reference
  9747. if (left == empty) {
  9748. return PyUnicode_FromObject(right);
  9749. }
  9750. if (right == empty) {
  9751. return PyUnicode_FromObject(left);
  9752. }
  9753. left_len = PyUnicode_GET_LENGTH(left);
  9754. right_len = PyUnicode_GET_LENGTH(right);
  9755. if (left_len > PY_SSIZE_T_MAX - right_len) {
  9756. PyErr_SetString(PyExc_OverflowError,
  9757. "strings are too large to concat");
  9758. return NULL;
  9759. }
  9760. new_len = left_len + right_len;
  9761. maxchar = PyUnicode_MAX_CHAR_VALUE(left);
  9762. maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
  9763. maxchar = Py_MAX(maxchar, maxchar2);
  9764. /* Concat the two Unicode strings */
  9765. result = PyUnicode_New(new_len, maxchar);
  9766. if (result == NULL)
  9767. return NULL;
  9768. _PyUnicode_FastCopyCharacters(result, 0, left, 0, left_len);
  9769. _PyUnicode_FastCopyCharacters(result, left_len, right, 0, right_len);
  9770. assert(_PyUnicode_CheckConsistency(result, 1));
  9771. return result;
  9772. }
  9773. void
  9774. PyUnicode_Append(PyObject **p_left, PyObject *right)
  9775. {
  9776. PyObject *left, *res;
  9777. Py_UCS4 maxchar, maxchar2;
  9778. Py_ssize_t left_len, right_len, new_len;
  9779. if (p_left == NULL) {
  9780. if (!PyErr_Occurred())
  9781. PyErr_BadInternalCall();
  9782. return;
  9783. }
  9784. left = *p_left;
  9785. if (right == NULL || left == NULL
  9786. || !PyUnicode_Check(left) || !PyUnicode_Check(right)) {
  9787. if (!PyErr_Occurred())
  9788. PyErr_BadInternalCall();
  9789. goto error;
  9790. }
  9791. /* Shortcuts */
  9792. PyObject *empty = unicode_get_empty(); // Borrowed reference
  9793. if (left == empty) {
  9794. Py_DECREF(left);
  9795. *p_left = Py_NewRef(right);
  9796. return;
  9797. }
  9798. if (right == empty) {
  9799. return;
  9800. }
  9801. left_len = PyUnicode_GET_LENGTH(left);
  9802. right_len = PyUnicode_GET_LENGTH(right);
  9803. if (left_len > PY_SSIZE_T_MAX - right_len) {
  9804. PyErr_SetString(PyExc_OverflowError,
  9805. "strings are too large to concat");
  9806. goto error;
  9807. }
  9808. new_len = left_len + right_len;
  9809. if (unicode_modifiable(left)
  9810. && PyUnicode_CheckExact(right)
  9811. && PyUnicode_KIND(right) <= PyUnicode_KIND(left)
  9812. /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
  9813. to change the structure size, but characters are stored just after
  9814. the structure, and so it requires to move all characters which is
  9815. not so different than duplicating the string. */
  9816. && !(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
  9817. {
  9818. /* append inplace */
  9819. if (unicode_resize(p_left, new_len) != 0)
  9820. goto error;
  9821. /* copy 'right' into the newly allocated area of 'left' */
  9822. _PyUnicode_FastCopyCharacters(*p_left, left_len, right, 0, right_len);
  9823. }
  9824. else {
  9825. maxchar = PyUnicode_MAX_CHAR_VALUE(left);
  9826. maxchar2 = PyUnicode_MAX_CHAR_VALUE(right);
  9827. maxchar = Py_MAX(maxchar, maxchar2);
  9828. /* Concat the two Unicode strings */
  9829. res = PyUnicode_New(new_len, maxchar);
  9830. if (res == NULL)
  9831. goto error;
  9832. _PyUnicode_FastCopyCharacters(res, 0, left, 0, left_len);
  9833. _PyUnicode_FastCopyCharacters(res, left_len, right, 0, right_len);
  9834. Py_DECREF(left);
  9835. *p_left = res;
  9836. }
  9837. assert(_PyUnicode_CheckConsistency(*p_left, 1));
  9838. return;
  9839. error:
  9840. Py_CLEAR(*p_left);
  9841. }
  9842. void
  9843. PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
  9844. {
  9845. PyUnicode_Append(pleft, right);
  9846. Py_XDECREF(right);
  9847. }
  9848. /*
  9849. Wraps asciilib_parse_args_finds() and additionally ensures that the
  9850. first argument is a unicode object.
  9851. */
  9852. static inline int
  9853. parse_args_finds_unicode(const char * function_name, PyObject *args,
  9854. PyObject **substring,
  9855. Py_ssize_t *start, Py_ssize_t *end)
  9856. {
  9857. if (asciilib_parse_args_finds(function_name, args, substring, start, end)) {
  9858. if (ensure_unicode(*substring) < 0)
  9859. return 0;
  9860. return 1;
  9861. }
  9862. return 0;
  9863. }
  9864. PyDoc_STRVAR(count__doc__,
  9865. "S.count(sub[, start[, end]]) -> int\n\
  9866. \n\
  9867. Return the number of non-overlapping occurrences of substring sub in\n\
  9868. string S[start:end]. Optional arguments start and end are\n\
  9869. interpreted as in slice notation.");
  9870. static PyObject *
  9871. unicode_count(PyObject *self, PyObject *args)
  9872. {
  9873. PyObject *substring = NULL; /* initialize to fix a compiler warning */
  9874. Py_ssize_t start = 0;
  9875. Py_ssize_t end = PY_SSIZE_T_MAX;
  9876. Py_ssize_t result;
  9877. if (!parse_args_finds_unicode("count", args, &substring, &start, &end))
  9878. return NULL;
  9879. result = unicode_count_impl(self, substring, start, end);
  9880. if (result == -1)
  9881. return NULL;
  9882. return PyLong_FromSsize_t(result);
  9883. }
  9884. /*[clinic input]
  9885. str.encode as unicode_encode
  9886. encoding: str(c_default="NULL") = 'utf-8'
  9887. The encoding in which to encode the string.
  9888. errors: str(c_default="NULL") = 'strict'
  9889. The error handling scheme to use for encoding errors.
  9890. The default is 'strict' meaning that encoding errors raise a
  9891. UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
  9892. 'xmlcharrefreplace' as well as any other name registered with
  9893. codecs.register_error that can handle UnicodeEncodeErrors.
  9894. Encode the string using the codec registered for encoding.
  9895. [clinic start generated code]*/
  9896. static PyObject *
  9897. unicode_encode_impl(PyObject *self, const char *encoding, const char *errors)
  9898. /*[clinic end generated code: output=bf78b6e2a9470e3c input=f0a9eb293d08fe02]*/
  9899. {
  9900. return PyUnicode_AsEncodedString(self, encoding, errors);
  9901. }
  9902. /*[clinic input]
  9903. str.expandtabs as unicode_expandtabs
  9904. tabsize: int = 8
  9905. Return a copy where all tab characters are expanded using spaces.
  9906. If tabsize is not given, a tab size of 8 characters is assumed.
  9907. [clinic start generated code]*/
  9908. static PyObject *
  9909. unicode_expandtabs_impl(PyObject *self, int tabsize)
  9910. /*[clinic end generated code: output=3457c5dcee26928f input=8a01914034af4c85]*/
  9911. {
  9912. Py_ssize_t i, j, line_pos, src_len, incr;
  9913. Py_UCS4 ch;
  9914. PyObject *u;
  9915. const void *src_data;
  9916. void *dest_data;
  9917. int kind;
  9918. int found;
  9919. /* First pass: determine size of output string */
  9920. src_len = PyUnicode_GET_LENGTH(self);
  9921. i = j = line_pos = 0;
  9922. kind = PyUnicode_KIND(self);
  9923. src_data = PyUnicode_DATA(self);
  9924. found = 0;
  9925. for (; i < src_len; i++) {
  9926. ch = PyUnicode_READ(kind, src_data, i);
  9927. if (ch == '\t') {
  9928. found = 1;
  9929. if (tabsize > 0) {
  9930. incr = tabsize - (line_pos % tabsize); /* cannot overflow */
  9931. if (j > PY_SSIZE_T_MAX - incr)
  9932. goto overflow;
  9933. line_pos += incr;
  9934. j += incr;
  9935. }
  9936. }
  9937. else {
  9938. if (j > PY_SSIZE_T_MAX - 1)
  9939. goto overflow;
  9940. line_pos++;
  9941. j++;
  9942. if (ch == '\n' || ch == '\r')
  9943. line_pos = 0;
  9944. }
  9945. }
  9946. if (!found)
  9947. return unicode_result_unchanged(self);
  9948. /* Second pass: create output string and fill it */
  9949. u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
  9950. if (!u)
  9951. return NULL;
  9952. dest_data = PyUnicode_DATA(u);
  9953. i = j = line_pos = 0;
  9954. for (; i < src_len; i++) {
  9955. ch = PyUnicode_READ(kind, src_data, i);
  9956. if (ch == '\t') {
  9957. if (tabsize > 0) {
  9958. incr = tabsize - (line_pos % tabsize);
  9959. line_pos += incr;
  9960. unicode_fill(kind, dest_data, ' ', j, incr);
  9961. j += incr;
  9962. }
  9963. }
  9964. else {
  9965. line_pos++;
  9966. PyUnicode_WRITE(kind, dest_data, j, ch);
  9967. j++;
  9968. if (ch == '\n' || ch == '\r')
  9969. line_pos = 0;
  9970. }
  9971. }
  9972. assert (j == PyUnicode_GET_LENGTH(u));
  9973. return unicode_result(u);
  9974. overflow:
  9975. PyErr_SetString(PyExc_OverflowError, "new string is too long");
  9976. return NULL;
  9977. }
  9978. PyDoc_STRVAR(find__doc__,
  9979. "S.find(sub[, start[, end]]) -> int\n\
  9980. \n\
  9981. Return the lowest index in S where substring sub is found,\n\
  9982. such that sub is contained within S[start:end]. Optional\n\
  9983. arguments start and end are interpreted as in slice notation.\n\
  9984. \n\
  9985. Return -1 on failure.");
  9986. static PyObject *
  9987. unicode_find(PyObject *self, PyObject *args)
  9988. {
  9989. /* initialize variables to prevent gcc warning */
  9990. PyObject *substring = NULL;
  9991. Py_ssize_t start = 0;
  9992. Py_ssize_t end = 0;
  9993. Py_ssize_t result;
  9994. if (!parse_args_finds_unicode("find", args, &substring, &start, &end))
  9995. return NULL;
  9996. result = any_find_slice(self, substring, start, end, 1);
  9997. if (result == -2)
  9998. return NULL;
  9999. return PyLong_FromSsize_t(result);
  10000. }
  10001. static PyObject *
  10002. unicode_getitem(PyObject *self, Py_ssize_t index)
  10003. {
  10004. const void *data;
  10005. int kind;
  10006. Py_UCS4 ch;
  10007. if (!PyUnicode_Check(self)) {
  10008. PyErr_BadArgument();
  10009. return NULL;
  10010. }
  10011. if (index < 0 || index >= PyUnicode_GET_LENGTH(self)) {
  10012. PyErr_SetString(PyExc_IndexError, "string index out of range");
  10013. return NULL;
  10014. }
  10015. kind = PyUnicode_KIND(self);
  10016. data = PyUnicode_DATA(self);
  10017. ch = PyUnicode_READ(kind, data, index);
  10018. return unicode_char(ch);
  10019. }
  10020. /* Believe it or not, this produces the same value for ASCII strings
  10021. as bytes_hash(). */
  10022. static Py_hash_t
  10023. unicode_hash(PyObject *self)
  10024. {
  10025. Py_uhash_t x; /* Unsigned for defined overflow behavior. */
  10026. #ifdef Py_DEBUG
  10027. assert(_Py_HashSecret_Initialized);
  10028. #endif
  10029. if (_PyUnicode_HASH(self) != -1)
  10030. return _PyUnicode_HASH(self);
  10031. x = _Py_HashBytes(PyUnicode_DATA(self),
  10032. PyUnicode_GET_LENGTH(self) * PyUnicode_KIND(self));
  10033. _PyUnicode_HASH(self) = x;
  10034. return x;
  10035. }
  10036. PyDoc_STRVAR(index__doc__,
  10037. "S.index(sub[, start[, end]]) -> int\n\
  10038. \n\
  10039. Return the lowest index in S where substring sub is found,\n\
  10040. such that sub is contained within S[start:end]. Optional\n\
  10041. arguments start and end are interpreted as in slice notation.\n\
  10042. \n\
  10043. Raises ValueError when the substring is not found.");
  10044. static PyObject *
  10045. unicode_index(PyObject *self, PyObject *args)
  10046. {
  10047. /* initialize variables to prevent gcc warning */
  10048. Py_ssize_t result;
  10049. PyObject *substring = NULL;
  10050. Py_ssize_t start = 0;
  10051. Py_ssize_t end = 0;
  10052. if (!parse_args_finds_unicode("index", args, &substring, &start, &end))
  10053. return NULL;
  10054. result = any_find_slice(self, substring, start, end, 1);
  10055. if (result == -2)
  10056. return NULL;
  10057. if (result < 0) {
  10058. PyErr_SetString(PyExc_ValueError, "substring not found");
  10059. return NULL;
  10060. }
  10061. return PyLong_FromSsize_t(result);
  10062. }
  10063. /*[clinic input]
  10064. str.isascii as unicode_isascii
  10065. Return True if all characters in the string are ASCII, False otherwise.
  10066. ASCII characters have code points in the range U+0000-U+007F.
  10067. Empty string is ASCII too.
  10068. [clinic start generated code]*/
  10069. static PyObject *
  10070. unicode_isascii_impl(PyObject *self)
  10071. /*[clinic end generated code: output=c5910d64b5a8003f input=5a43cbc6399621d5]*/
  10072. {
  10073. return PyBool_FromLong(PyUnicode_IS_ASCII(self));
  10074. }
  10075. /*[clinic input]
  10076. str.islower as unicode_islower
  10077. Return True if the string is a lowercase string, False otherwise.
  10078. A string is lowercase if all cased characters in the string are lowercase and
  10079. there is at least one cased character in the string.
  10080. [clinic start generated code]*/
  10081. static PyObject *
  10082. unicode_islower_impl(PyObject *self)
  10083. /*[clinic end generated code: output=dbd41995bd005b81 input=acec65ac6821ae47]*/
  10084. {
  10085. Py_ssize_t i, length;
  10086. int kind;
  10087. const void *data;
  10088. int cased;
  10089. length = PyUnicode_GET_LENGTH(self);
  10090. kind = PyUnicode_KIND(self);
  10091. data = PyUnicode_DATA(self);
  10092. /* Shortcut for single character strings */
  10093. if (length == 1)
  10094. return PyBool_FromLong(
  10095. Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
  10096. /* Special case for empty strings */
  10097. if (length == 0)
  10098. Py_RETURN_FALSE;
  10099. cased = 0;
  10100. for (i = 0; i < length; i++) {
  10101. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10102. if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
  10103. Py_RETURN_FALSE;
  10104. else if (!cased && Py_UNICODE_ISLOWER(ch))
  10105. cased = 1;
  10106. }
  10107. return PyBool_FromLong(cased);
  10108. }
  10109. /*[clinic input]
  10110. str.isupper as unicode_isupper
  10111. Return True if the string is an uppercase string, False otherwise.
  10112. A string is uppercase if all cased characters in the string are uppercase and
  10113. there is at least one cased character in the string.
  10114. [clinic start generated code]*/
  10115. static PyObject *
  10116. unicode_isupper_impl(PyObject *self)
  10117. /*[clinic end generated code: output=049209c8e7f15f59 input=e9b1feda5d17f2d3]*/
  10118. {
  10119. Py_ssize_t i, length;
  10120. int kind;
  10121. const void *data;
  10122. int cased;
  10123. length = PyUnicode_GET_LENGTH(self);
  10124. kind = PyUnicode_KIND(self);
  10125. data = PyUnicode_DATA(self);
  10126. /* Shortcut for single character strings */
  10127. if (length == 1)
  10128. return PyBool_FromLong(
  10129. Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
  10130. /* Special case for empty strings */
  10131. if (length == 0)
  10132. Py_RETURN_FALSE;
  10133. cased = 0;
  10134. for (i = 0; i < length; i++) {
  10135. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10136. if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
  10137. Py_RETURN_FALSE;
  10138. else if (!cased && Py_UNICODE_ISUPPER(ch))
  10139. cased = 1;
  10140. }
  10141. return PyBool_FromLong(cased);
  10142. }
  10143. /*[clinic input]
  10144. str.istitle as unicode_istitle
  10145. Return True if the string is a title-cased string, False otherwise.
  10146. In a title-cased string, upper- and title-case characters may only
  10147. follow uncased characters and lowercase characters only cased ones.
  10148. [clinic start generated code]*/
  10149. static PyObject *
  10150. unicode_istitle_impl(PyObject *self)
  10151. /*[clinic end generated code: output=e9bf6eb91f5d3f0e input=98d32bd2e1f06f8c]*/
  10152. {
  10153. Py_ssize_t i, length;
  10154. int kind;
  10155. const void *data;
  10156. int cased, previous_is_cased;
  10157. length = PyUnicode_GET_LENGTH(self);
  10158. kind = PyUnicode_KIND(self);
  10159. data = PyUnicode_DATA(self);
  10160. /* Shortcut for single character strings */
  10161. if (length == 1) {
  10162. Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
  10163. return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
  10164. (Py_UNICODE_ISUPPER(ch) != 0));
  10165. }
  10166. /* Special case for empty strings */
  10167. if (length == 0)
  10168. Py_RETURN_FALSE;
  10169. cased = 0;
  10170. previous_is_cased = 0;
  10171. for (i = 0; i < length; i++) {
  10172. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10173. if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
  10174. if (previous_is_cased)
  10175. Py_RETURN_FALSE;
  10176. previous_is_cased = 1;
  10177. cased = 1;
  10178. }
  10179. else if (Py_UNICODE_ISLOWER(ch)) {
  10180. if (!previous_is_cased)
  10181. Py_RETURN_FALSE;
  10182. previous_is_cased = 1;
  10183. cased = 1;
  10184. }
  10185. else
  10186. previous_is_cased = 0;
  10187. }
  10188. return PyBool_FromLong(cased);
  10189. }
  10190. /*[clinic input]
  10191. str.isspace as unicode_isspace
  10192. Return True if the string is a whitespace string, False otherwise.
  10193. A string is whitespace if all characters in the string are whitespace and there
  10194. is at least one character in the string.
  10195. [clinic start generated code]*/
  10196. static PyObject *
  10197. unicode_isspace_impl(PyObject *self)
  10198. /*[clinic end generated code: output=163a63bfa08ac2b9 input=fe462cb74f8437d8]*/
  10199. {
  10200. Py_ssize_t i, length;
  10201. int kind;
  10202. const void *data;
  10203. length = PyUnicode_GET_LENGTH(self);
  10204. kind = PyUnicode_KIND(self);
  10205. data = PyUnicode_DATA(self);
  10206. /* Shortcut for single character strings */
  10207. if (length == 1)
  10208. return PyBool_FromLong(
  10209. Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
  10210. /* Special case for empty strings */
  10211. if (length == 0)
  10212. Py_RETURN_FALSE;
  10213. for (i = 0; i < length; i++) {
  10214. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10215. if (!Py_UNICODE_ISSPACE(ch))
  10216. Py_RETURN_FALSE;
  10217. }
  10218. Py_RETURN_TRUE;
  10219. }
  10220. /*[clinic input]
  10221. str.isalpha as unicode_isalpha
  10222. Return True if the string is an alphabetic string, False otherwise.
  10223. A string is alphabetic if all characters in the string are alphabetic and there
  10224. is at least one character in the string.
  10225. [clinic start generated code]*/
  10226. static PyObject *
  10227. unicode_isalpha_impl(PyObject *self)
  10228. /*[clinic end generated code: output=cc81b9ac3883ec4f input=d0fd18a96cbca5eb]*/
  10229. {
  10230. Py_ssize_t i, length;
  10231. int kind;
  10232. const void *data;
  10233. length = PyUnicode_GET_LENGTH(self);
  10234. kind = PyUnicode_KIND(self);
  10235. data = PyUnicode_DATA(self);
  10236. /* Shortcut for single character strings */
  10237. if (length == 1)
  10238. return PyBool_FromLong(
  10239. Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
  10240. /* Special case for empty strings */
  10241. if (length == 0)
  10242. Py_RETURN_FALSE;
  10243. for (i = 0; i < length; i++) {
  10244. if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
  10245. Py_RETURN_FALSE;
  10246. }
  10247. Py_RETURN_TRUE;
  10248. }
  10249. /*[clinic input]
  10250. str.isalnum as unicode_isalnum
  10251. Return True if the string is an alpha-numeric string, False otherwise.
  10252. A string is alpha-numeric if all characters in the string are alpha-numeric and
  10253. there is at least one character in the string.
  10254. [clinic start generated code]*/
  10255. static PyObject *
  10256. unicode_isalnum_impl(PyObject *self)
  10257. /*[clinic end generated code: output=a5a23490ffc3660c input=5c6579bf2e04758c]*/
  10258. {
  10259. int kind;
  10260. const void *data;
  10261. Py_ssize_t len, i;
  10262. kind = PyUnicode_KIND(self);
  10263. data = PyUnicode_DATA(self);
  10264. len = PyUnicode_GET_LENGTH(self);
  10265. /* Shortcut for single character strings */
  10266. if (len == 1) {
  10267. const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
  10268. return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
  10269. }
  10270. /* Special case for empty strings */
  10271. if (len == 0)
  10272. Py_RETURN_FALSE;
  10273. for (i = 0; i < len; i++) {
  10274. const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10275. if (!Py_UNICODE_ISALNUM(ch))
  10276. Py_RETURN_FALSE;
  10277. }
  10278. Py_RETURN_TRUE;
  10279. }
  10280. /*[clinic input]
  10281. str.isdecimal as unicode_isdecimal
  10282. Return True if the string is a decimal string, False otherwise.
  10283. A string is a decimal string if all characters in the string are decimal and
  10284. there is at least one character in the string.
  10285. [clinic start generated code]*/
  10286. static PyObject *
  10287. unicode_isdecimal_impl(PyObject *self)
  10288. /*[clinic end generated code: output=fb2dcdb62d3fc548 input=336bc97ab4c8268f]*/
  10289. {
  10290. Py_ssize_t i, length;
  10291. int kind;
  10292. const void *data;
  10293. length = PyUnicode_GET_LENGTH(self);
  10294. kind = PyUnicode_KIND(self);
  10295. data = PyUnicode_DATA(self);
  10296. /* Shortcut for single character strings */
  10297. if (length == 1)
  10298. return PyBool_FromLong(
  10299. Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
  10300. /* Special case for empty strings */
  10301. if (length == 0)
  10302. Py_RETURN_FALSE;
  10303. for (i = 0; i < length; i++) {
  10304. if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
  10305. Py_RETURN_FALSE;
  10306. }
  10307. Py_RETURN_TRUE;
  10308. }
  10309. /*[clinic input]
  10310. str.isdigit as unicode_isdigit
  10311. Return True if the string is a digit string, False otherwise.
  10312. A string is a digit string if all characters in the string are digits and there
  10313. is at least one character in the string.
  10314. [clinic start generated code]*/
  10315. static PyObject *
  10316. unicode_isdigit_impl(PyObject *self)
  10317. /*[clinic end generated code: output=10a6985311da6858 input=901116c31deeea4c]*/
  10318. {
  10319. Py_ssize_t i, length;
  10320. int kind;
  10321. const void *data;
  10322. length = PyUnicode_GET_LENGTH(self);
  10323. kind = PyUnicode_KIND(self);
  10324. data = PyUnicode_DATA(self);
  10325. /* Shortcut for single character strings */
  10326. if (length == 1) {
  10327. const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
  10328. return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
  10329. }
  10330. /* Special case for empty strings */
  10331. if (length == 0)
  10332. Py_RETURN_FALSE;
  10333. for (i = 0; i < length; i++) {
  10334. if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
  10335. Py_RETURN_FALSE;
  10336. }
  10337. Py_RETURN_TRUE;
  10338. }
  10339. /*[clinic input]
  10340. str.isnumeric as unicode_isnumeric
  10341. Return True if the string is a numeric string, False otherwise.
  10342. A string is numeric if all characters in the string are numeric and there is at
  10343. least one character in the string.
  10344. [clinic start generated code]*/
  10345. static PyObject *
  10346. unicode_isnumeric_impl(PyObject *self)
  10347. /*[clinic end generated code: output=9172a32d9013051a input=722507db976f826c]*/
  10348. {
  10349. Py_ssize_t i, length;
  10350. int kind;
  10351. const void *data;
  10352. length = PyUnicode_GET_LENGTH(self);
  10353. kind = PyUnicode_KIND(self);
  10354. data = PyUnicode_DATA(self);
  10355. /* Shortcut for single character strings */
  10356. if (length == 1)
  10357. return PyBool_FromLong(
  10358. Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
  10359. /* Special case for empty strings */
  10360. if (length == 0)
  10361. Py_RETURN_FALSE;
  10362. for (i = 0; i < length; i++) {
  10363. if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
  10364. Py_RETURN_FALSE;
  10365. }
  10366. Py_RETURN_TRUE;
  10367. }
  10368. Py_ssize_t
  10369. _PyUnicode_ScanIdentifier(PyObject *self)
  10370. {
  10371. Py_ssize_t i;
  10372. Py_ssize_t len = PyUnicode_GET_LENGTH(self);
  10373. if (len == 0) {
  10374. /* an empty string is not a valid identifier */
  10375. return 0;
  10376. }
  10377. int kind = PyUnicode_KIND(self);
  10378. const void *data = PyUnicode_DATA(self);
  10379. Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
  10380. /* PEP 3131 says that the first character must be in
  10381. XID_Start and subsequent characters in XID_Continue,
  10382. and for the ASCII range, the 2.x rules apply (i.e
  10383. start with letters and underscore, continue with
  10384. letters, digits, underscore). However, given the current
  10385. definition of XID_Start and XID_Continue, it is sufficient
  10386. to check just for these, except that _ must be allowed
  10387. as starting an identifier. */
  10388. if (!_PyUnicode_IsXidStart(ch) && ch != 0x5F /* LOW LINE */) {
  10389. return 0;
  10390. }
  10391. for (i = 1; i < len; i++) {
  10392. ch = PyUnicode_READ(kind, data, i);
  10393. if (!_PyUnicode_IsXidContinue(ch)) {
  10394. return i;
  10395. }
  10396. }
  10397. return i;
  10398. }
  10399. int
  10400. PyUnicode_IsIdentifier(PyObject *self)
  10401. {
  10402. Py_ssize_t i = _PyUnicode_ScanIdentifier(self);
  10403. Py_ssize_t len = PyUnicode_GET_LENGTH(self);
  10404. /* an empty string is not a valid identifier */
  10405. return len && i == len;
  10406. }
  10407. /*[clinic input]
  10408. str.isidentifier as unicode_isidentifier
  10409. Return True if the string is a valid Python identifier, False otherwise.
  10410. Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
  10411. such as "def" or "class".
  10412. [clinic start generated code]*/
  10413. static PyObject *
  10414. unicode_isidentifier_impl(PyObject *self)
  10415. /*[clinic end generated code: output=fe585a9666572905 input=2d807a104f21c0c5]*/
  10416. {
  10417. return PyBool_FromLong(PyUnicode_IsIdentifier(self));
  10418. }
  10419. /*[clinic input]
  10420. str.isprintable as unicode_isprintable
  10421. Return True if the string is printable, False otherwise.
  10422. A string is printable if all of its characters are considered printable in
  10423. repr() or if it is empty.
  10424. [clinic start generated code]*/
  10425. static PyObject *
  10426. unicode_isprintable_impl(PyObject *self)
  10427. /*[clinic end generated code: output=3ab9626cd32dd1a0 input=98a0e1c2c1813209]*/
  10428. {
  10429. Py_ssize_t i, length;
  10430. int kind;
  10431. const void *data;
  10432. length = PyUnicode_GET_LENGTH(self);
  10433. kind = PyUnicode_KIND(self);
  10434. data = PyUnicode_DATA(self);
  10435. /* Shortcut for single character strings */
  10436. if (length == 1)
  10437. return PyBool_FromLong(
  10438. Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
  10439. for (i = 0; i < length; i++) {
  10440. if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
  10441. Py_RETURN_FALSE;
  10442. }
  10443. }
  10444. Py_RETURN_TRUE;
  10445. }
  10446. /*[clinic input]
  10447. str.join as unicode_join
  10448. iterable: object
  10449. /
  10450. Concatenate any number of strings.
  10451. The string whose method is called is inserted in between each given string.
  10452. The result is returned as a new string.
  10453. Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
  10454. [clinic start generated code]*/
  10455. static PyObject *
  10456. unicode_join(PyObject *self, PyObject *iterable)
  10457. /*[clinic end generated code: output=6857e7cecfe7bf98 input=2f70422bfb8fa189]*/
  10458. {
  10459. return PyUnicode_Join(self, iterable);
  10460. }
  10461. static Py_ssize_t
  10462. unicode_length(PyObject *self)
  10463. {
  10464. return PyUnicode_GET_LENGTH(self);
  10465. }
  10466. /*[clinic input]
  10467. str.ljust as unicode_ljust
  10468. width: Py_ssize_t
  10469. fillchar: Py_UCS4 = ' '
  10470. /
  10471. Return a left-justified string of length width.
  10472. Padding is done using the specified fill character (default is a space).
  10473. [clinic start generated code]*/
  10474. static PyObject *
  10475. unicode_ljust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
  10476. /*[clinic end generated code: output=1cce0e0e0a0b84b3 input=3ab599e335e60a32]*/
  10477. {
  10478. if (PyUnicode_GET_LENGTH(self) >= width)
  10479. return unicode_result_unchanged(self);
  10480. return pad(self, 0, width - PyUnicode_GET_LENGTH(self), fillchar);
  10481. }
  10482. /*[clinic input]
  10483. str.lower as unicode_lower
  10484. Return a copy of the string converted to lowercase.
  10485. [clinic start generated code]*/
  10486. static PyObject *
  10487. unicode_lower_impl(PyObject *self)
  10488. /*[clinic end generated code: output=84ef9ed42efad663 input=60a2984b8beff23a]*/
  10489. {
  10490. if (PyUnicode_IS_ASCII(self))
  10491. return ascii_upper_or_lower(self, 1);
  10492. return case_operation(self, do_lower);
  10493. }
  10494. #define LEFTSTRIP 0
  10495. #define RIGHTSTRIP 1
  10496. #define BOTHSTRIP 2
  10497. /* Arrays indexed by above */
  10498. static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};
  10499. #define STRIPNAME(i) (stripfuncnames[i])
  10500. /* externally visible for str.strip(unicode) */
  10501. PyObject *
  10502. _PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
  10503. {
  10504. const void *data;
  10505. int kind;
  10506. Py_ssize_t i, j, len;
  10507. BLOOM_MASK sepmask;
  10508. Py_ssize_t seplen;
  10509. kind = PyUnicode_KIND(self);
  10510. data = PyUnicode_DATA(self);
  10511. len = PyUnicode_GET_LENGTH(self);
  10512. seplen = PyUnicode_GET_LENGTH(sepobj);
  10513. sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
  10514. PyUnicode_DATA(sepobj),
  10515. seplen);
  10516. i = 0;
  10517. if (striptype != RIGHTSTRIP) {
  10518. while (i < len) {
  10519. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10520. if (!BLOOM(sepmask, ch))
  10521. break;
  10522. if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
  10523. break;
  10524. i++;
  10525. }
  10526. }
  10527. j = len;
  10528. if (striptype != LEFTSTRIP) {
  10529. j--;
  10530. while (j >= i) {
  10531. Py_UCS4 ch = PyUnicode_READ(kind, data, j);
  10532. if (!BLOOM(sepmask, ch))
  10533. break;
  10534. if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
  10535. break;
  10536. j--;
  10537. }
  10538. j++;
  10539. }
  10540. return PyUnicode_Substring(self, i, j);
  10541. }
  10542. PyObject*
  10543. PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
  10544. {
  10545. const unsigned char *data;
  10546. int kind;
  10547. Py_ssize_t length;
  10548. length = PyUnicode_GET_LENGTH(self);
  10549. end = Py_MIN(end, length);
  10550. if (start == 0 && end == length)
  10551. return unicode_result_unchanged(self);
  10552. if (start < 0 || end < 0) {
  10553. PyErr_SetString(PyExc_IndexError, "string index out of range");
  10554. return NULL;
  10555. }
  10556. if (start >= length || end < start)
  10557. _Py_RETURN_UNICODE_EMPTY();
  10558. length = end - start;
  10559. if (PyUnicode_IS_ASCII(self)) {
  10560. data = PyUnicode_1BYTE_DATA(self);
  10561. return _PyUnicode_FromASCII((const char*)(data + start), length);
  10562. }
  10563. else {
  10564. kind = PyUnicode_KIND(self);
  10565. data = PyUnicode_1BYTE_DATA(self);
  10566. return PyUnicode_FromKindAndData(kind,
  10567. data + kind * start,
  10568. length);
  10569. }
  10570. }
  10571. static PyObject *
  10572. do_strip(PyObject *self, int striptype)
  10573. {
  10574. Py_ssize_t len, i, j;
  10575. len = PyUnicode_GET_LENGTH(self);
  10576. if (PyUnicode_IS_ASCII(self)) {
  10577. const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);
  10578. i = 0;
  10579. if (striptype != RIGHTSTRIP) {
  10580. while (i < len) {
  10581. Py_UCS1 ch = data[i];
  10582. if (!_Py_ascii_whitespace[ch])
  10583. break;
  10584. i++;
  10585. }
  10586. }
  10587. j = len;
  10588. if (striptype != LEFTSTRIP) {
  10589. j--;
  10590. while (j >= i) {
  10591. Py_UCS1 ch = data[j];
  10592. if (!_Py_ascii_whitespace[ch])
  10593. break;
  10594. j--;
  10595. }
  10596. j++;
  10597. }
  10598. }
  10599. else {
  10600. int kind = PyUnicode_KIND(self);
  10601. const void *data = PyUnicode_DATA(self);
  10602. i = 0;
  10603. if (striptype != RIGHTSTRIP) {
  10604. while (i < len) {
  10605. Py_UCS4 ch = PyUnicode_READ(kind, data, i);
  10606. if (!Py_UNICODE_ISSPACE(ch))
  10607. break;
  10608. i++;
  10609. }
  10610. }
  10611. j = len;
  10612. if (striptype != LEFTSTRIP) {
  10613. j--;
  10614. while (j >= i) {
  10615. Py_UCS4 ch = PyUnicode_READ(kind, data, j);
  10616. if (!Py_UNICODE_ISSPACE(ch))
  10617. break;
  10618. j--;
  10619. }
  10620. j++;
  10621. }
  10622. }
  10623. return PyUnicode_Substring(self, i, j);
  10624. }
  10625. static PyObject *
  10626. do_argstrip(PyObject *self, int striptype, PyObject *sep)
  10627. {
  10628. if (sep != Py_None) {
  10629. if (PyUnicode_Check(sep))
  10630. return _PyUnicode_XStrip(self, striptype, sep);
  10631. else {
  10632. PyErr_Format(PyExc_TypeError,
  10633. "%s arg must be None or str",
  10634. STRIPNAME(striptype));
  10635. return NULL;
  10636. }
  10637. }
  10638. return do_strip(self, striptype);
  10639. }
  10640. /*[clinic input]
  10641. str.strip as unicode_strip
  10642. chars: object = None
  10643. /
  10644. Return a copy of the string with leading and trailing whitespace removed.
  10645. If chars is given and not None, remove characters in chars instead.
  10646. [clinic start generated code]*/
  10647. static PyObject *
  10648. unicode_strip_impl(PyObject *self, PyObject *chars)
  10649. /*[clinic end generated code: output=ca19018454345d57 input=385289c6f423b954]*/
  10650. {
  10651. return do_argstrip(self, BOTHSTRIP, chars);
  10652. }
  10653. /*[clinic input]
  10654. str.lstrip as unicode_lstrip
  10655. chars: object = None
  10656. /
  10657. Return a copy of the string with leading whitespace removed.
  10658. If chars is given and not None, remove characters in chars instead.
  10659. [clinic start generated code]*/
  10660. static PyObject *
  10661. unicode_lstrip_impl(PyObject *self, PyObject *chars)
  10662. /*[clinic end generated code: output=3b43683251f79ca7 input=529f9f3834448671]*/
  10663. {
  10664. return do_argstrip(self, LEFTSTRIP, chars);
  10665. }
  10666. /*[clinic input]
  10667. str.rstrip as unicode_rstrip
  10668. chars: object = None
  10669. /
  10670. Return a copy of the string with trailing whitespace removed.
  10671. If chars is given and not None, remove characters in chars instead.
  10672. [clinic start generated code]*/
  10673. static PyObject *
  10674. unicode_rstrip_impl(PyObject *self, PyObject *chars)
  10675. /*[clinic end generated code: output=4a59230017cc3b7a input=62566c627916557f]*/
  10676. {
  10677. return do_argstrip(self, RIGHTSTRIP, chars);
  10678. }
  10679. static PyObject*
  10680. unicode_repeat(PyObject *str, Py_ssize_t len)
  10681. {
  10682. PyObject *u;
  10683. Py_ssize_t nchars, n;
  10684. if (len < 1)
  10685. _Py_RETURN_UNICODE_EMPTY();
  10686. /* no repeat, return original string */
  10687. if (len == 1)
  10688. return unicode_result_unchanged(str);
  10689. if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
  10690. PyErr_SetString(PyExc_OverflowError,
  10691. "repeated string is too long");
  10692. return NULL;
  10693. }
  10694. nchars = len * PyUnicode_GET_LENGTH(str);
  10695. u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
  10696. if (!u)
  10697. return NULL;
  10698. assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
  10699. if (PyUnicode_GET_LENGTH(str) == 1) {
  10700. int kind = PyUnicode_KIND(str);
  10701. Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
  10702. if (kind == PyUnicode_1BYTE_KIND) {
  10703. void *to = PyUnicode_DATA(u);
  10704. memset(to, (unsigned char)fill_char, len);
  10705. }
  10706. else if (kind == PyUnicode_2BYTE_KIND) {
  10707. Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
  10708. for (n = 0; n < len; ++n)
  10709. ucs2[n] = fill_char;
  10710. } else {
  10711. Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
  10712. assert(kind == PyUnicode_4BYTE_KIND);
  10713. for (n = 0; n < len; ++n)
  10714. ucs4[n] = fill_char;
  10715. }
  10716. }
  10717. else {
  10718. Py_ssize_t char_size = PyUnicode_KIND(str);
  10719. char *to = (char *) PyUnicode_DATA(u);
  10720. _PyBytes_Repeat(to, nchars * char_size, PyUnicode_DATA(str),
  10721. PyUnicode_GET_LENGTH(str) * char_size);
  10722. }
  10723. assert(_PyUnicode_CheckConsistency(u, 1));
  10724. return u;
  10725. }
  10726. PyObject *
  10727. PyUnicode_Replace(PyObject *str,
  10728. PyObject *substr,
  10729. PyObject *replstr,
  10730. Py_ssize_t maxcount)
  10731. {
  10732. if (ensure_unicode(str) < 0 || ensure_unicode(substr) < 0 ||
  10733. ensure_unicode(replstr) < 0)
  10734. return NULL;
  10735. return replace(str, substr, replstr, maxcount);
  10736. }
  10737. /*[clinic input]
  10738. str.replace as unicode_replace
  10739. old: unicode
  10740. new: unicode
  10741. count: Py_ssize_t = -1
  10742. Maximum number of occurrences to replace.
  10743. -1 (the default value) means replace all occurrences.
  10744. /
  10745. Return a copy with all occurrences of substring old replaced by new.
  10746. If the optional argument count is given, only the first count occurrences are
  10747. replaced.
  10748. [clinic start generated code]*/
  10749. static PyObject *
  10750. unicode_replace_impl(PyObject *self, PyObject *old, PyObject *new,
  10751. Py_ssize_t count)
  10752. /*[clinic end generated code: output=b63f1a8b5eebf448 input=147d12206276ebeb]*/
  10753. {
  10754. return replace(self, old, new, count);
  10755. }
  10756. /*[clinic input]
  10757. str.removeprefix as unicode_removeprefix
  10758. prefix: unicode
  10759. /
  10760. Return a str with the given prefix string removed if present.
  10761. If the string starts with the prefix string, return string[len(prefix):].
  10762. Otherwise, return a copy of the original string.
  10763. [clinic start generated code]*/
  10764. static PyObject *
  10765. unicode_removeprefix_impl(PyObject *self, PyObject *prefix)
  10766. /*[clinic end generated code: output=f1e5945e9763bcb9 input=27ec40b99a37eb88]*/
  10767. {
  10768. int match = tailmatch(self, prefix, 0, PY_SSIZE_T_MAX, -1);
  10769. if (match == -1) {
  10770. return NULL;
  10771. }
  10772. if (match) {
  10773. return PyUnicode_Substring(self, PyUnicode_GET_LENGTH(prefix),
  10774. PyUnicode_GET_LENGTH(self));
  10775. }
  10776. return unicode_result_unchanged(self);
  10777. }
  10778. /*[clinic input]
  10779. str.removesuffix as unicode_removesuffix
  10780. suffix: unicode
  10781. /
  10782. Return a str with the given suffix string removed if present.
  10783. If the string ends with the suffix string and that suffix is not empty,
  10784. return string[:-len(suffix)]. Otherwise, return a copy of the original
  10785. string.
  10786. [clinic start generated code]*/
  10787. static PyObject *
  10788. unicode_removesuffix_impl(PyObject *self, PyObject *suffix)
  10789. /*[clinic end generated code: output=d36629e227636822 input=12cc32561e769be4]*/
  10790. {
  10791. int match = tailmatch(self, suffix, 0, PY_SSIZE_T_MAX, +1);
  10792. if (match == -1) {
  10793. return NULL;
  10794. }
  10795. if (match) {
  10796. return PyUnicode_Substring(self, 0, PyUnicode_GET_LENGTH(self)
  10797. - PyUnicode_GET_LENGTH(suffix));
  10798. }
  10799. return unicode_result_unchanged(self);
  10800. }
  10801. static PyObject *
  10802. unicode_repr(PyObject *unicode)
  10803. {
  10804. PyObject *repr;
  10805. Py_ssize_t isize;
  10806. Py_ssize_t osize, squote, dquote, i, o;
  10807. Py_UCS4 max, quote;
  10808. int ikind, okind, unchanged;
  10809. const void *idata;
  10810. void *odata;
  10811. isize = PyUnicode_GET_LENGTH(unicode);
  10812. idata = PyUnicode_DATA(unicode);
  10813. /* Compute length of output, quote characters, and
  10814. maximum character */
  10815. osize = 0;
  10816. max = 127;
  10817. squote = dquote = 0;
  10818. ikind = PyUnicode_KIND(unicode);
  10819. for (i = 0; i < isize; i++) {
  10820. Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
  10821. Py_ssize_t incr = 1;
  10822. switch (ch) {
  10823. case '\'': squote++; break;
  10824. case '"': dquote++; break;
  10825. case '\\': case '\t': case '\r': case '\n':
  10826. incr = 2;
  10827. break;
  10828. default:
  10829. /* Fast-path ASCII */
  10830. if (ch < ' ' || ch == 0x7f)
  10831. incr = 4; /* \xHH */
  10832. else if (ch < 0x7f)
  10833. ;
  10834. else if (Py_UNICODE_ISPRINTABLE(ch))
  10835. max = ch > max ? ch : max;
  10836. else if (ch < 0x100)
  10837. incr = 4; /* \xHH */
  10838. else if (ch < 0x10000)
  10839. incr = 6; /* \uHHHH */
  10840. else
  10841. incr = 10; /* \uHHHHHHHH */
  10842. }
  10843. if (osize > PY_SSIZE_T_MAX - incr) {
  10844. PyErr_SetString(PyExc_OverflowError,
  10845. "string is too long to generate repr");
  10846. return NULL;
  10847. }
  10848. osize += incr;
  10849. }
  10850. quote = '\'';
  10851. unchanged = (osize == isize);
  10852. if (squote) {
  10853. unchanged = 0;
  10854. if (dquote)
  10855. /* Both squote and dquote present. Use squote,
  10856. and escape them */
  10857. osize += squote;
  10858. else
  10859. quote = '"';
  10860. }
  10861. osize += 2; /* quotes */
  10862. repr = PyUnicode_New(osize, max);
  10863. if (repr == NULL)
  10864. return NULL;
  10865. okind = PyUnicode_KIND(repr);
  10866. odata = PyUnicode_DATA(repr);
  10867. PyUnicode_WRITE(okind, odata, 0, quote);
  10868. PyUnicode_WRITE(okind, odata, osize-1, quote);
  10869. if (unchanged) {
  10870. _PyUnicode_FastCopyCharacters(repr, 1,
  10871. unicode, 0,
  10872. isize);
  10873. }
  10874. else {
  10875. for (i = 0, o = 1; i < isize; i++) {
  10876. Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
  10877. /* Escape quotes and backslashes */
  10878. if ((ch == quote) || (ch == '\\')) {
  10879. PyUnicode_WRITE(okind, odata, o++, '\\');
  10880. PyUnicode_WRITE(okind, odata, o++, ch);
  10881. continue;
  10882. }
  10883. /* Map special whitespace to '\t', \n', '\r' */
  10884. if (ch == '\t') {
  10885. PyUnicode_WRITE(okind, odata, o++, '\\');
  10886. PyUnicode_WRITE(okind, odata, o++, 't');
  10887. }
  10888. else if (ch == '\n') {
  10889. PyUnicode_WRITE(okind, odata, o++, '\\');
  10890. PyUnicode_WRITE(okind, odata, o++, 'n');
  10891. }
  10892. else if (ch == '\r') {
  10893. PyUnicode_WRITE(okind, odata, o++, '\\');
  10894. PyUnicode_WRITE(okind, odata, o++, 'r');
  10895. }
  10896. /* Map non-printable US ASCII to '\xhh' */
  10897. else if (ch < ' ' || ch == 0x7F) {
  10898. PyUnicode_WRITE(okind, odata, o++, '\\');
  10899. PyUnicode_WRITE(okind, odata, o++, 'x');
  10900. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
  10901. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
  10902. }
  10903. /* Copy ASCII characters as-is */
  10904. else if (ch < 0x7F) {
  10905. PyUnicode_WRITE(okind, odata, o++, ch);
  10906. }
  10907. /* Non-ASCII characters */
  10908. else {
  10909. /* Map Unicode whitespace and control characters
  10910. (categories Z* and C* except ASCII space)
  10911. */
  10912. if (!Py_UNICODE_ISPRINTABLE(ch)) {
  10913. PyUnicode_WRITE(okind, odata, o++, '\\');
  10914. /* Map 8-bit characters to '\xhh' */
  10915. if (ch <= 0xff) {
  10916. PyUnicode_WRITE(okind, odata, o++, 'x');
  10917. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
  10918. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
  10919. }
  10920. /* Map 16-bit characters to '\uxxxx' */
  10921. else if (ch <= 0xffff) {
  10922. PyUnicode_WRITE(okind, odata, o++, 'u');
  10923. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
  10924. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
  10925. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
  10926. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
  10927. }
  10928. /* Map 21-bit characters to '\U00xxxxxx' */
  10929. else {
  10930. PyUnicode_WRITE(okind, odata, o++, 'U');
  10931. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
  10932. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
  10933. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
  10934. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
  10935. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
  10936. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
  10937. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
  10938. PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
  10939. }
  10940. }
  10941. /* Copy characters as-is */
  10942. else {
  10943. PyUnicode_WRITE(okind, odata, o++, ch);
  10944. }
  10945. }
  10946. }
  10947. }
  10948. /* Closing quote already added at the beginning */
  10949. assert(_PyUnicode_CheckConsistency(repr, 1));
  10950. return repr;
  10951. }
  10952. PyDoc_STRVAR(rfind__doc__,
  10953. "S.rfind(sub[, start[, end]]) -> int\n\
  10954. \n\
  10955. Return the highest index in S where substring sub is found,\n\
  10956. such that sub is contained within S[start:end]. Optional\n\
  10957. arguments start and end are interpreted as in slice notation.\n\
  10958. \n\
  10959. Return -1 on failure.");
  10960. static PyObject *
  10961. unicode_rfind(PyObject *self, PyObject *args)
  10962. {
  10963. /* initialize variables to prevent gcc warning */
  10964. PyObject *substring = NULL;
  10965. Py_ssize_t start = 0;
  10966. Py_ssize_t end = 0;
  10967. Py_ssize_t result;
  10968. if (!parse_args_finds_unicode("rfind", args, &substring, &start, &end))
  10969. return NULL;
  10970. result = any_find_slice(self, substring, start, end, -1);
  10971. if (result == -2)
  10972. return NULL;
  10973. return PyLong_FromSsize_t(result);
  10974. }
  10975. PyDoc_STRVAR(rindex__doc__,
  10976. "S.rindex(sub[, start[, end]]) -> int\n\
  10977. \n\
  10978. Return the highest index in S where substring sub is found,\n\
  10979. such that sub is contained within S[start:end]. Optional\n\
  10980. arguments start and end are interpreted as in slice notation.\n\
  10981. \n\
  10982. Raises ValueError when the substring is not found.");
  10983. static PyObject *
  10984. unicode_rindex(PyObject *self, PyObject *args)
  10985. {
  10986. /* initialize variables to prevent gcc warning */
  10987. PyObject *substring = NULL;
  10988. Py_ssize_t start = 0;
  10989. Py_ssize_t end = 0;
  10990. Py_ssize_t result;
  10991. if (!parse_args_finds_unicode("rindex", args, &substring, &start, &end))
  10992. return NULL;
  10993. result = any_find_slice(self, substring, start, end, -1);
  10994. if (result == -2)
  10995. return NULL;
  10996. if (result < 0) {
  10997. PyErr_SetString(PyExc_ValueError, "substring not found");
  10998. return NULL;
  10999. }
  11000. return PyLong_FromSsize_t(result);
  11001. }
  11002. /*[clinic input]
  11003. str.rjust as unicode_rjust
  11004. width: Py_ssize_t
  11005. fillchar: Py_UCS4 = ' '
  11006. /
  11007. Return a right-justified string of length width.
  11008. Padding is done using the specified fill character (default is a space).
  11009. [clinic start generated code]*/
  11010. static PyObject *
  11011. unicode_rjust_impl(PyObject *self, Py_ssize_t width, Py_UCS4 fillchar)
  11012. /*[clinic end generated code: output=804a1a57fbe8d5cf input=d05f550b5beb1f72]*/
  11013. {
  11014. if (PyUnicode_GET_LENGTH(self) >= width)
  11015. return unicode_result_unchanged(self);
  11016. return pad(self, width - PyUnicode_GET_LENGTH(self), 0, fillchar);
  11017. }
  11018. PyObject *
  11019. PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
  11020. {
  11021. if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
  11022. return NULL;
  11023. return split(s, sep, maxsplit);
  11024. }
  11025. /*[clinic input]
  11026. str.split as unicode_split
  11027. sep: object = None
  11028. The separator used to split the string.
  11029. When set to None (the default value), will split on any whitespace
  11030. character (including \n \r \t \f and spaces) and will discard
  11031. empty strings from the result.
  11032. maxsplit: Py_ssize_t = -1
  11033. Maximum number of splits.
  11034. -1 (the default value) means no limit.
  11035. Return a list of the substrings in the string, using sep as the separator string.
  11036. Splitting starts at the front of the string and works to the end.
  11037. Note, str.split() is mainly useful for data that has been intentionally
  11038. delimited. With natural text that includes punctuation, consider using
  11039. the regular expression module.
  11040. [clinic start generated code]*/
  11041. static PyObject *
  11042. unicode_split_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
  11043. /*[clinic end generated code: output=3a65b1db356948dc input=a29bcc0c7a5af0eb]*/
  11044. {
  11045. if (sep == Py_None)
  11046. return split(self, NULL, maxsplit);
  11047. if (PyUnicode_Check(sep))
  11048. return split(self, sep, maxsplit);
  11049. PyErr_Format(PyExc_TypeError,
  11050. "must be str or None, not %.100s",
  11051. Py_TYPE(sep)->tp_name);
  11052. return NULL;
  11053. }
  11054. PyObject *
  11055. PyUnicode_Partition(PyObject *str_obj, PyObject *sep_obj)
  11056. {
  11057. PyObject* out;
  11058. int kind1, kind2;
  11059. const void *buf1, *buf2;
  11060. Py_ssize_t len1, len2;
  11061. if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
  11062. return NULL;
  11063. kind1 = PyUnicode_KIND(str_obj);
  11064. kind2 = PyUnicode_KIND(sep_obj);
  11065. len1 = PyUnicode_GET_LENGTH(str_obj);
  11066. len2 = PyUnicode_GET_LENGTH(sep_obj);
  11067. if (kind1 < kind2 || len1 < len2) {
  11068. PyObject *empty = unicode_get_empty(); // Borrowed reference
  11069. return PyTuple_Pack(3, str_obj, empty, empty);
  11070. }
  11071. buf1 = PyUnicode_DATA(str_obj);
  11072. buf2 = PyUnicode_DATA(sep_obj);
  11073. if (kind2 != kind1) {
  11074. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  11075. if (!buf2)
  11076. return NULL;
  11077. }
  11078. switch (kind1) {
  11079. case PyUnicode_1BYTE_KIND:
  11080. if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
  11081. out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11082. else
  11083. out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11084. break;
  11085. case PyUnicode_2BYTE_KIND:
  11086. out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11087. break;
  11088. case PyUnicode_4BYTE_KIND:
  11089. out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11090. break;
  11091. default:
  11092. Py_UNREACHABLE();
  11093. }
  11094. assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
  11095. if (kind2 != kind1)
  11096. PyMem_Free((void *)buf2);
  11097. return out;
  11098. }
  11099. PyObject *
  11100. PyUnicode_RPartition(PyObject *str_obj, PyObject *sep_obj)
  11101. {
  11102. PyObject* out;
  11103. int kind1, kind2;
  11104. const void *buf1, *buf2;
  11105. Py_ssize_t len1, len2;
  11106. if (ensure_unicode(str_obj) < 0 || ensure_unicode(sep_obj) < 0)
  11107. return NULL;
  11108. kind1 = PyUnicode_KIND(str_obj);
  11109. kind2 = PyUnicode_KIND(sep_obj);
  11110. len1 = PyUnicode_GET_LENGTH(str_obj);
  11111. len2 = PyUnicode_GET_LENGTH(sep_obj);
  11112. if (kind1 < kind2 || len1 < len2) {
  11113. PyObject *empty = unicode_get_empty(); // Borrowed reference
  11114. return PyTuple_Pack(3, empty, empty, str_obj);
  11115. }
  11116. buf1 = PyUnicode_DATA(str_obj);
  11117. buf2 = PyUnicode_DATA(sep_obj);
  11118. if (kind2 != kind1) {
  11119. buf2 = unicode_askind(kind2, buf2, len2, kind1);
  11120. if (!buf2)
  11121. return NULL;
  11122. }
  11123. switch (kind1) {
  11124. case PyUnicode_1BYTE_KIND:
  11125. if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
  11126. out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11127. else
  11128. out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11129. break;
  11130. case PyUnicode_2BYTE_KIND:
  11131. out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11132. break;
  11133. case PyUnicode_4BYTE_KIND:
  11134. out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
  11135. break;
  11136. default:
  11137. Py_UNREACHABLE();
  11138. }
  11139. assert((kind2 == kind1) == (buf2 == PyUnicode_DATA(sep_obj)));
  11140. if (kind2 != kind1)
  11141. PyMem_Free((void *)buf2);
  11142. return out;
  11143. }
  11144. /*[clinic input]
  11145. str.partition as unicode_partition
  11146. sep: object
  11147. /
  11148. Partition the string into three parts using the given separator.
  11149. This will search for the separator in the string. If the separator is found,
  11150. returns a 3-tuple containing the part before the separator, the separator
  11151. itself, and the part after it.
  11152. If the separator is not found, returns a 3-tuple containing the original string
  11153. and two empty strings.
  11154. [clinic start generated code]*/
  11155. static PyObject *
  11156. unicode_partition(PyObject *self, PyObject *sep)
  11157. /*[clinic end generated code: output=e4ced7bd253ca3c4 input=f29b8d06c63e50be]*/
  11158. {
  11159. return PyUnicode_Partition(self, sep);
  11160. }
  11161. /*[clinic input]
  11162. str.rpartition as unicode_rpartition = str.partition
  11163. Partition the string into three parts using the given separator.
  11164. This will search for the separator in the string, starting at the end. If
  11165. the separator is found, returns a 3-tuple containing the part before the
  11166. separator, the separator itself, and the part after it.
  11167. If the separator is not found, returns a 3-tuple containing two empty strings
  11168. and the original string.
  11169. [clinic start generated code]*/
  11170. static PyObject *
  11171. unicode_rpartition(PyObject *self, PyObject *sep)
  11172. /*[clinic end generated code: output=1aa13cf1156572aa input=c4b7db3ef5cf336a]*/
  11173. {
  11174. return PyUnicode_RPartition(self, sep);
  11175. }
  11176. PyObject *
  11177. PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
  11178. {
  11179. if (ensure_unicode(s) < 0 || (sep != NULL && ensure_unicode(sep) < 0))
  11180. return NULL;
  11181. return rsplit(s, sep, maxsplit);
  11182. }
  11183. /*[clinic input]
  11184. str.rsplit as unicode_rsplit = str.split
  11185. Return a list of the substrings in the string, using sep as the separator string.
  11186. Splitting starts at the end of the string and works to the front.
  11187. [clinic start generated code]*/
  11188. static PyObject *
  11189. unicode_rsplit_impl(PyObject *self, PyObject *sep, Py_ssize_t maxsplit)
  11190. /*[clinic end generated code: output=c2b815c63bcabffc input=ea78406060fce33c]*/
  11191. {
  11192. if (sep == Py_None)
  11193. return rsplit(self, NULL, maxsplit);
  11194. if (PyUnicode_Check(sep))
  11195. return rsplit(self, sep, maxsplit);
  11196. PyErr_Format(PyExc_TypeError,
  11197. "must be str or None, not %.100s",
  11198. Py_TYPE(sep)->tp_name);
  11199. return NULL;
  11200. }
  11201. /*[clinic input]
  11202. str.splitlines as unicode_splitlines
  11203. keepends: bool = False
  11204. Return a list of the lines in the string, breaking at line boundaries.
  11205. Line breaks are not included in the resulting list unless keepends is given and
  11206. true.
  11207. [clinic start generated code]*/
  11208. static PyObject *
  11209. unicode_splitlines_impl(PyObject *self, int keepends)
  11210. /*[clinic end generated code: output=f664dcdad153ec40 input=ba6ad05ee85d2b55]*/
  11211. {
  11212. return PyUnicode_Splitlines(self, keepends);
  11213. }
  11214. static
  11215. PyObject *unicode_str(PyObject *self)
  11216. {
  11217. return unicode_result_unchanged(self);
  11218. }
  11219. /*[clinic input]
  11220. str.swapcase as unicode_swapcase
  11221. Convert uppercase characters to lowercase and lowercase characters to uppercase.
  11222. [clinic start generated code]*/
  11223. static PyObject *
  11224. unicode_swapcase_impl(PyObject *self)
  11225. /*[clinic end generated code: output=5d28966bf6d7b2af input=3f3ef96d5798a7bb]*/
  11226. {
  11227. return case_operation(self, do_swapcase);
  11228. }
  11229. /*[clinic input]
  11230. @staticmethod
  11231. str.maketrans as unicode_maketrans
  11232. x: object
  11233. y: unicode=NULL
  11234. z: unicode=NULL
  11235. /
  11236. Return a translation table usable for str.translate().
  11237. If there is only one argument, it must be a dictionary mapping Unicode
  11238. ordinals (integers) or characters to Unicode ordinals, strings or None.
  11239. Character keys will be then converted to ordinals.
  11240. If there are two arguments, they must be strings of equal length, and
  11241. in the resulting dictionary, each character in x will be mapped to the
  11242. character at the same position in y. If there is a third argument, it
  11243. must be a string, whose characters will be mapped to None in the result.
  11244. [clinic start generated code]*/
  11245. static PyObject *
  11246. unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z)
  11247. /*[clinic end generated code: output=a925c89452bd5881 input=7bfbf529a293c6c5]*/
  11248. {
  11249. PyObject *new = NULL, *key, *value;
  11250. Py_ssize_t i = 0;
  11251. int res;
  11252. new = PyDict_New();
  11253. if (!new)
  11254. return NULL;
  11255. if (y != NULL) {
  11256. int x_kind, y_kind, z_kind;
  11257. const void *x_data, *y_data, *z_data;
  11258. /* x must be a string too, of equal length */
  11259. if (!PyUnicode_Check(x)) {
  11260. PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
  11261. "be a string if there is a second argument");
  11262. goto err;
  11263. }
  11264. if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
  11265. PyErr_SetString(PyExc_ValueError, "the first two maketrans "
  11266. "arguments must have equal length");
  11267. goto err;
  11268. }
  11269. /* create entries for translating chars in x to those in y */
  11270. x_kind = PyUnicode_KIND(x);
  11271. y_kind = PyUnicode_KIND(y);
  11272. x_data = PyUnicode_DATA(x);
  11273. y_data = PyUnicode_DATA(y);
  11274. for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
  11275. key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
  11276. if (!key)
  11277. goto err;
  11278. value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
  11279. if (!value) {
  11280. Py_DECREF(key);
  11281. goto err;
  11282. }
  11283. res = PyDict_SetItem(new, key, value);
  11284. Py_DECREF(key);
  11285. Py_DECREF(value);
  11286. if (res < 0)
  11287. goto err;
  11288. }
  11289. /* create entries for deleting chars in z */
  11290. if (z != NULL) {
  11291. z_kind = PyUnicode_KIND(z);
  11292. z_data = PyUnicode_DATA(z);
  11293. for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
  11294. key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
  11295. if (!key)
  11296. goto err;
  11297. res = PyDict_SetItem(new, key, Py_None);
  11298. Py_DECREF(key);
  11299. if (res < 0)
  11300. goto err;
  11301. }
  11302. }
  11303. } else {
  11304. int kind;
  11305. const void *data;
  11306. /* x must be a dict */
  11307. if (!PyDict_CheckExact(x)) {
  11308. PyErr_SetString(PyExc_TypeError, "if you give only one argument "
  11309. "to maketrans it must be a dict");
  11310. goto err;
  11311. }
  11312. /* copy entries into the new dict, converting string keys to int keys */
  11313. while (PyDict_Next(x, &i, &key, &value)) {
  11314. if (PyUnicode_Check(key)) {
  11315. /* convert string keys to integer keys */
  11316. PyObject *newkey;
  11317. if (PyUnicode_GET_LENGTH(key) != 1) {
  11318. PyErr_SetString(PyExc_ValueError, "string keys in translate "
  11319. "table must be of length 1");
  11320. goto err;
  11321. }
  11322. kind = PyUnicode_KIND(key);
  11323. data = PyUnicode_DATA(key);
  11324. newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
  11325. if (!newkey)
  11326. goto err;
  11327. res = PyDict_SetItem(new, newkey, value);
  11328. Py_DECREF(newkey);
  11329. if (res < 0)
  11330. goto err;
  11331. } else if (PyLong_Check(key)) {
  11332. /* just keep integer keys */
  11333. if (PyDict_SetItem(new, key, value) < 0)
  11334. goto err;
  11335. } else {
  11336. PyErr_SetString(PyExc_TypeError, "keys in translate table must "
  11337. "be strings or integers");
  11338. goto err;
  11339. }
  11340. }
  11341. }
  11342. return new;
  11343. err:
  11344. Py_DECREF(new);
  11345. return NULL;
  11346. }
  11347. /*[clinic input]
  11348. str.translate as unicode_translate
  11349. table: object
  11350. Translation table, which must be a mapping of Unicode ordinals to
  11351. Unicode ordinals, strings, or None.
  11352. /
  11353. Replace each character in the string using the given translation table.
  11354. The table must implement lookup/indexing via __getitem__, for instance a
  11355. dictionary or list. If this operation raises LookupError, the character is
  11356. left untouched. Characters mapped to None are deleted.
  11357. [clinic start generated code]*/
  11358. static PyObject *
  11359. unicode_translate(PyObject *self, PyObject *table)
  11360. /*[clinic end generated code: output=3cb448ff2fd96bf3 input=6d38343db63d8eb0]*/
  11361. {
  11362. return _PyUnicode_TranslateCharmap(self, table, "ignore");
  11363. }
  11364. /*[clinic input]
  11365. str.upper as unicode_upper
  11366. Return a copy of the string converted to uppercase.
  11367. [clinic start generated code]*/
  11368. static PyObject *
  11369. unicode_upper_impl(PyObject *self)
  11370. /*[clinic end generated code: output=1b7ddd16bbcdc092 input=db3d55682dfe2e6c]*/
  11371. {
  11372. if (PyUnicode_IS_ASCII(self))
  11373. return ascii_upper_or_lower(self, 0);
  11374. return case_operation(self, do_upper);
  11375. }
  11376. /*[clinic input]
  11377. str.zfill as unicode_zfill
  11378. width: Py_ssize_t
  11379. /
  11380. Pad a numeric string with zeros on the left, to fill a field of the given width.
  11381. The string is never truncated.
  11382. [clinic start generated code]*/
  11383. static PyObject *
  11384. unicode_zfill_impl(PyObject *self, Py_ssize_t width)
  11385. /*[clinic end generated code: output=e13fb6bdf8e3b9df input=c6b2f772c6f27799]*/
  11386. {
  11387. Py_ssize_t fill;
  11388. PyObject *u;
  11389. int kind;
  11390. const void *data;
  11391. Py_UCS4 chr;
  11392. if (PyUnicode_GET_LENGTH(self) >= width)
  11393. return unicode_result_unchanged(self);
  11394. fill = width - PyUnicode_GET_LENGTH(self);
  11395. u = pad(self, fill, 0, '0');
  11396. if (u == NULL)
  11397. return NULL;
  11398. kind = PyUnicode_KIND(u);
  11399. data = PyUnicode_DATA(u);
  11400. chr = PyUnicode_READ(kind, data, fill);
  11401. if (chr == '+' || chr == '-') {
  11402. /* move sign to beginning of string */
  11403. PyUnicode_WRITE(kind, data, 0, chr);
  11404. PyUnicode_WRITE(kind, data, fill, '0');
  11405. }
  11406. assert(_PyUnicode_CheckConsistency(u, 1));
  11407. return u;
  11408. }
  11409. PyDoc_STRVAR(startswith__doc__,
  11410. "S.startswith(prefix[, start[, end]]) -> bool\n\
  11411. \n\
  11412. Return True if S starts with the specified prefix, False otherwise.\n\
  11413. With optional start, test S beginning at that position.\n\
  11414. With optional end, stop comparing S at that position.\n\
  11415. prefix can also be a tuple of strings to try.");
  11416. static PyObject *
  11417. unicode_startswith(PyObject *self,
  11418. PyObject *args)
  11419. {
  11420. PyObject *subobj;
  11421. PyObject *substring;
  11422. Py_ssize_t start = 0;
  11423. Py_ssize_t end = PY_SSIZE_T_MAX;
  11424. int result;
  11425. if (!asciilib_parse_args_finds("startswith", args, &subobj, &start, &end))
  11426. return NULL;
  11427. if (PyTuple_Check(subobj)) {
  11428. Py_ssize_t i;
  11429. for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
  11430. substring = PyTuple_GET_ITEM(subobj, i);
  11431. if (!PyUnicode_Check(substring)) {
  11432. PyErr_Format(PyExc_TypeError,
  11433. "tuple for startswith must only contain str, "
  11434. "not %.100s",
  11435. Py_TYPE(substring)->tp_name);
  11436. return NULL;
  11437. }
  11438. result = tailmatch(self, substring, start, end, -1);
  11439. if (result == -1)
  11440. return NULL;
  11441. if (result) {
  11442. Py_RETURN_TRUE;
  11443. }
  11444. }
  11445. /* nothing matched */
  11446. Py_RETURN_FALSE;
  11447. }
  11448. if (!PyUnicode_Check(subobj)) {
  11449. PyErr_Format(PyExc_TypeError,
  11450. "startswith first arg must be str or "
  11451. "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
  11452. return NULL;
  11453. }
  11454. result = tailmatch(self, subobj, start, end, -1);
  11455. if (result == -1)
  11456. return NULL;
  11457. return PyBool_FromLong(result);
  11458. }
  11459. PyDoc_STRVAR(endswith__doc__,
  11460. "S.endswith(suffix[, start[, end]]) -> bool\n\
  11461. \n\
  11462. Return True if S ends with the specified suffix, False otherwise.\n\
  11463. With optional start, test S beginning at that position.\n\
  11464. With optional end, stop comparing S at that position.\n\
  11465. suffix can also be a tuple of strings to try.");
  11466. static PyObject *
  11467. unicode_endswith(PyObject *self,
  11468. PyObject *args)
  11469. {
  11470. PyObject *subobj;
  11471. PyObject *substring;
  11472. Py_ssize_t start = 0;
  11473. Py_ssize_t end = PY_SSIZE_T_MAX;
  11474. int result;
  11475. if (!asciilib_parse_args_finds("endswith", args, &subobj, &start, &end))
  11476. return NULL;
  11477. if (PyTuple_Check(subobj)) {
  11478. Py_ssize_t i;
  11479. for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
  11480. substring = PyTuple_GET_ITEM(subobj, i);
  11481. if (!PyUnicode_Check(substring)) {
  11482. PyErr_Format(PyExc_TypeError,
  11483. "tuple for endswith must only contain str, "
  11484. "not %.100s",
  11485. Py_TYPE(substring)->tp_name);
  11486. return NULL;
  11487. }
  11488. result = tailmatch(self, substring, start, end, +1);
  11489. if (result == -1)
  11490. return NULL;
  11491. if (result) {
  11492. Py_RETURN_TRUE;
  11493. }
  11494. }
  11495. Py_RETURN_FALSE;
  11496. }
  11497. if (!PyUnicode_Check(subobj)) {
  11498. PyErr_Format(PyExc_TypeError,
  11499. "endswith first arg must be str or "
  11500. "a tuple of str, not %.100s", Py_TYPE(subobj)->tp_name);
  11501. return NULL;
  11502. }
  11503. result = tailmatch(self, subobj, start, end, +1);
  11504. if (result == -1)
  11505. return NULL;
  11506. return PyBool_FromLong(result);
  11507. }
  11508. static inline void
  11509. _PyUnicodeWriter_Update(_PyUnicodeWriter *writer)
  11510. {
  11511. writer->maxchar = PyUnicode_MAX_CHAR_VALUE(writer->buffer);
  11512. writer->data = PyUnicode_DATA(writer->buffer);
  11513. if (!writer->readonly) {
  11514. writer->kind = PyUnicode_KIND(writer->buffer);
  11515. writer->size = PyUnicode_GET_LENGTH(writer->buffer);
  11516. }
  11517. else {
  11518. /* use a value smaller than PyUnicode_1BYTE_KIND() so
  11519. _PyUnicodeWriter_PrepareKind() will copy the buffer. */
  11520. writer->kind = 0;
  11521. assert(writer->kind <= PyUnicode_1BYTE_KIND);
  11522. /* Copy-on-write mode: set buffer size to 0 so
  11523. * _PyUnicodeWriter_Prepare() will copy (and enlarge) the buffer on
  11524. * next write. */
  11525. writer->size = 0;
  11526. }
  11527. }
  11528. void
  11529. _PyUnicodeWriter_Init(_PyUnicodeWriter *writer)
  11530. {
  11531. memset(writer, 0, sizeof(*writer));
  11532. /* ASCII is the bare minimum */
  11533. writer->min_char = 127;
  11534. /* use a value smaller than PyUnicode_1BYTE_KIND() so
  11535. _PyUnicodeWriter_PrepareKind() will copy the buffer. */
  11536. writer->kind = 0;
  11537. assert(writer->kind <= PyUnicode_1BYTE_KIND);
  11538. }
  11539. // Initialize _PyUnicodeWriter with initial buffer
  11540. static inline void
  11541. _PyUnicodeWriter_InitWithBuffer(_PyUnicodeWriter *writer, PyObject *buffer)
  11542. {
  11543. memset(writer, 0, sizeof(*writer));
  11544. writer->buffer = buffer;
  11545. _PyUnicodeWriter_Update(writer);
  11546. writer->min_length = writer->size;
  11547. }
  11548. int
  11549. _PyUnicodeWriter_PrepareInternal(_PyUnicodeWriter *writer,
  11550. Py_ssize_t length, Py_UCS4 maxchar)
  11551. {
  11552. Py_ssize_t newlen;
  11553. PyObject *newbuffer;
  11554. assert(maxchar <= MAX_UNICODE);
  11555. /* ensure that the _PyUnicodeWriter_Prepare macro was used */
  11556. assert((maxchar > writer->maxchar && length >= 0)
  11557. || length > 0);
  11558. if (length > PY_SSIZE_T_MAX - writer->pos) {
  11559. PyErr_NoMemory();
  11560. return -1;
  11561. }
  11562. newlen = writer->pos + length;
  11563. maxchar = Py_MAX(maxchar, writer->min_char);
  11564. if (writer->buffer == NULL) {
  11565. assert(!writer->readonly);
  11566. if (writer->overallocate
  11567. && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
  11568. /* overallocate to limit the number of realloc() */
  11569. newlen += newlen / OVERALLOCATE_FACTOR;
  11570. }
  11571. if (newlen < writer->min_length)
  11572. newlen = writer->min_length;
  11573. writer->buffer = PyUnicode_New(newlen, maxchar);
  11574. if (writer->buffer == NULL)
  11575. return -1;
  11576. }
  11577. else if (newlen > writer->size) {
  11578. if (writer->overallocate
  11579. && newlen <= (PY_SSIZE_T_MAX - newlen / OVERALLOCATE_FACTOR)) {
  11580. /* overallocate to limit the number of realloc() */
  11581. newlen += newlen / OVERALLOCATE_FACTOR;
  11582. }
  11583. if (newlen < writer->min_length)
  11584. newlen = writer->min_length;
  11585. if (maxchar > writer->maxchar || writer->readonly) {
  11586. /* resize + widen */
  11587. maxchar = Py_MAX(maxchar, writer->maxchar);
  11588. newbuffer = PyUnicode_New(newlen, maxchar);
  11589. if (newbuffer == NULL)
  11590. return -1;
  11591. _PyUnicode_FastCopyCharacters(newbuffer, 0,
  11592. writer->buffer, 0, writer->pos);
  11593. Py_DECREF(writer->buffer);
  11594. writer->readonly = 0;
  11595. }
  11596. else {
  11597. newbuffer = resize_compact(writer->buffer, newlen);
  11598. if (newbuffer == NULL)
  11599. return -1;
  11600. }
  11601. writer->buffer = newbuffer;
  11602. }
  11603. else if (maxchar > writer->maxchar) {
  11604. assert(!writer->readonly);
  11605. newbuffer = PyUnicode_New(writer->size, maxchar);
  11606. if (newbuffer == NULL)
  11607. return -1;
  11608. _PyUnicode_FastCopyCharacters(newbuffer, 0,
  11609. writer->buffer, 0, writer->pos);
  11610. Py_SETREF(writer->buffer, newbuffer);
  11611. }
  11612. _PyUnicodeWriter_Update(writer);
  11613. return 0;
  11614. #undef OVERALLOCATE_FACTOR
  11615. }
  11616. int
  11617. _PyUnicodeWriter_PrepareKindInternal(_PyUnicodeWriter *writer,
  11618. int kind)
  11619. {
  11620. Py_UCS4 maxchar;
  11621. /* ensure that the _PyUnicodeWriter_PrepareKind macro was used */
  11622. assert(writer->kind < kind);
  11623. switch (kind)
  11624. {
  11625. case PyUnicode_1BYTE_KIND: maxchar = 0xff; break;
  11626. case PyUnicode_2BYTE_KIND: maxchar = 0xffff; break;
  11627. case PyUnicode_4BYTE_KIND: maxchar = MAX_UNICODE; break;
  11628. default:
  11629. Py_UNREACHABLE();
  11630. }
  11631. return _PyUnicodeWriter_PrepareInternal(writer, 0, maxchar);
  11632. }
  11633. static inline int
  11634. _PyUnicodeWriter_WriteCharInline(_PyUnicodeWriter *writer, Py_UCS4 ch)
  11635. {
  11636. assert(ch <= MAX_UNICODE);
  11637. if (_PyUnicodeWriter_Prepare(writer, 1, ch) < 0)
  11638. return -1;
  11639. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, ch);
  11640. writer->pos++;
  11641. return 0;
  11642. }
  11643. int
  11644. _PyUnicodeWriter_WriteChar(_PyUnicodeWriter *writer, Py_UCS4 ch)
  11645. {
  11646. return _PyUnicodeWriter_WriteCharInline(writer, ch);
  11647. }
  11648. int
  11649. _PyUnicodeWriter_WriteStr(_PyUnicodeWriter *writer, PyObject *str)
  11650. {
  11651. Py_UCS4 maxchar;
  11652. Py_ssize_t len;
  11653. len = PyUnicode_GET_LENGTH(str);
  11654. if (len == 0)
  11655. return 0;
  11656. maxchar = PyUnicode_MAX_CHAR_VALUE(str);
  11657. if (maxchar > writer->maxchar || len > writer->size - writer->pos) {
  11658. if (writer->buffer == NULL && !writer->overallocate) {
  11659. assert(_PyUnicode_CheckConsistency(str, 1));
  11660. writer->readonly = 1;
  11661. writer->buffer = Py_NewRef(str);
  11662. _PyUnicodeWriter_Update(writer);
  11663. writer->pos += len;
  11664. return 0;
  11665. }
  11666. if (_PyUnicodeWriter_PrepareInternal(writer, len, maxchar) == -1)
  11667. return -1;
  11668. }
  11669. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  11670. str, 0, len);
  11671. writer->pos += len;
  11672. return 0;
  11673. }
  11674. int
  11675. _PyUnicodeWriter_WriteSubstring(_PyUnicodeWriter *writer, PyObject *str,
  11676. Py_ssize_t start, Py_ssize_t end)
  11677. {
  11678. Py_UCS4 maxchar;
  11679. Py_ssize_t len;
  11680. assert(0 <= start);
  11681. assert(end <= PyUnicode_GET_LENGTH(str));
  11682. assert(start <= end);
  11683. if (end == 0)
  11684. return 0;
  11685. if (start == 0 && end == PyUnicode_GET_LENGTH(str))
  11686. return _PyUnicodeWriter_WriteStr(writer, str);
  11687. if (PyUnicode_MAX_CHAR_VALUE(str) > writer->maxchar)
  11688. maxchar = _PyUnicode_FindMaxChar(str, start, end);
  11689. else
  11690. maxchar = writer->maxchar;
  11691. len = end - start;
  11692. if (_PyUnicodeWriter_Prepare(writer, len, maxchar) < 0)
  11693. return -1;
  11694. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  11695. str, start, len);
  11696. writer->pos += len;
  11697. return 0;
  11698. }
  11699. int
  11700. _PyUnicodeWriter_WriteASCIIString(_PyUnicodeWriter *writer,
  11701. const char *ascii, Py_ssize_t len)
  11702. {
  11703. if (len == -1)
  11704. len = strlen(ascii);
  11705. assert(ucs1lib_find_max_char((const Py_UCS1*)ascii, (const Py_UCS1*)ascii + len) < 128);
  11706. if (writer->buffer == NULL && !writer->overallocate) {
  11707. PyObject *str;
  11708. str = _PyUnicode_FromASCII(ascii, len);
  11709. if (str == NULL)
  11710. return -1;
  11711. writer->readonly = 1;
  11712. writer->buffer = str;
  11713. _PyUnicodeWriter_Update(writer);
  11714. writer->pos += len;
  11715. return 0;
  11716. }
  11717. if (_PyUnicodeWriter_Prepare(writer, len, 127) == -1)
  11718. return -1;
  11719. switch (writer->kind)
  11720. {
  11721. case PyUnicode_1BYTE_KIND:
  11722. {
  11723. const Py_UCS1 *str = (const Py_UCS1 *)ascii;
  11724. Py_UCS1 *data = writer->data;
  11725. memcpy(data + writer->pos, str, len);
  11726. break;
  11727. }
  11728. case PyUnicode_2BYTE_KIND:
  11729. {
  11730. _PyUnicode_CONVERT_BYTES(
  11731. Py_UCS1, Py_UCS2,
  11732. ascii, ascii + len,
  11733. (Py_UCS2 *)writer->data + writer->pos);
  11734. break;
  11735. }
  11736. case PyUnicode_4BYTE_KIND:
  11737. {
  11738. _PyUnicode_CONVERT_BYTES(
  11739. Py_UCS1, Py_UCS4,
  11740. ascii, ascii + len,
  11741. (Py_UCS4 *)writer->data + writer->pos);
  11742. break;
  11743. }
  11744. default:
  11745. Py_UNREACHABLE();
  11746. }
  11747. writer->pos += len;
  11748. return 0;
  11749. }
  11750. int
  11751. _PyUnicodeWriter_WriteLatin1String(_PyUnicodeWriter *writer,
  11752. const char *str, Py_ssize_t len)
  11753. {
  11754. Py_UCS4 maxchar;
  11755. maxchar = ucs1lib_find_max_char((const Py_UCS1*)str, (const Py_UCS1*)str + len);
  11756. if (_PyUnicodeWriter_Prepare(writer, len, maxchar) == -1)
  11757. return -1;
  11758. unicode_write_cstr(writer->buffer, writer->pos, str, len);
  11759. writer->pos += len;
  11760. return 0;
  11761. }
  11762. PyObject *
  11763. _PyUnicodeWriter_Finish(_PyUnicodeWriter *writer)
  11764. {
  11765. PyObject *str;
  11766. if (writer->pos == 0) {
  11767. Py_CLEAR(writer->buffer);
  11768. _Py_RETURN_UNICODE_EMPTY();
  11769. }
  11770. str = writer->buffer;
  11771. writer->buffer = NULL;
  11772. if (writer->readonly) {
  11773. assert(PyUnicode_GET_LENGTH(str) == writer->pos);
  11774. return str;
  11775. }
  11776. if (PyUnicode_GET_LENGTH(str) != writer->pos) {
  11777. PyObject *str2;
  11778. str2 = resize_compact(str, writer->pos);
  11779. if (str2 == NULL) {
  11780. Py_DECREF(str);
  11781. return NULL;
  11782. }
  11783. str = str2;
  11784. }
  11785. assert(_PyUnicode_CheckConsistency(str, 1));
  11786. return unicode_result(str);
  11787. }
  11788. void
  11789. _PyUnicodeWriter_Dealloc(_PyUnicodeWriter *writer)
  11790. {
  11791. Py_CLEAR(writer->buffer);
  11792. }
  11793. #include "stringlib/unicode_format.h"
  11794. PyDoc_STRVAR(format__doc__,
  11795. "S.format(*args, **kwargs) -> str\n\
  11796. \n\
  11797. Return a formatted version of S, using substitutions from args and kwargs.\n\
  11798. The substitutions are identified by braces ('{' and '}').");
  11799. PyDoc_STRVAR(format_map__doc__,
  11800. "S.format_map(mapping) -> str\n\
  11801. \n\
  11802. Return a formatted version of S, using substitutions from mapping.\n\
  11803. The substitutions are identified by braces ('{' and '}').");
  11804. /*[clinic input]
  11805. str.__format__ as unicode___format__
  11806. format_spec: unicode
  11807. /
  11808. Return a formatted version of the string as described by format_spec.
  11809. [clinic start generated code]*/
  11810. static PyObject *
  11811. unicode___format___impl(PyObject *self, PyObject *format_spec)
  11812. /*[clinic end generated code: output=45fceaca6d2ba4c8 input=5e135645d167a214]*/
  11813. {
  11814. _PyUnicodeWriter writer;
  11815. int ret;
  11816. _PyUnicodeWriter_Init(&writer);
  11817. ret = _PyUnicode_FormatAdvancedWriter(&writer,
  11818. self, format_spec, 0,
  11819. PyUnicode_GET_LENGTH(format_spec));
  11820. if (ret == -1) {
  11821. _PyUnicodeWriter_Dealloc(&writer);
  11822. return NULL;
  11823. }
  11824. return _PyUnicodeWriter_Finish(&writer);
  11825. }
  11826. /*[clinic input]
  11827. str.__sizeof__ as unicode_sizeof
  11828. Return the size of the string in memory, in bytes.
  11829. [clinic start generated code]*/
  11830. static PyObject *
  11831. unicode_sizeof_impl(PyObject *self)
  11832. /*[clinic end generated code: output=6dbc2f5a408b6d4f input=6dd011c108e33fb0]*/
  11833. {
  11834. Py_ssize_t size;
  11835. /* If it's a compact object, account for base structure +
  11836. character data. */
  11837. if (PyUnicode_IS_COMPACT_ASCII(self)) {
  11838. size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(self) + 1;
  11839. }
  11840. else if (PyUnicode_IS_COMPACT(self)) {
  11841. size = sizeof(PyCompactUnicodeObject) +
  11842. (PyUnicode_GET_LENGTH(self) + 1) * PyUnicode_KIND(self);
  11843. }
  11844. else {
  11845. /* If it is a two-block object, account for base object, and
  11846. for character block if present. */
  11847. size = sizeof(PyUnicodeObject);
  11848. if (_PyUnicode_DATA_ANY(self))
  11849. size += (PyUnicode_GET_LENGTH(self) + 1) *
  11850. PyUnicode_KIND(self);
  11851. }
  11852. if (_PyUnicode_HAS_UTF8_MEMORY(self))
  11853. size += PyUnicode_UTF8_LENGTH(self) + 1;
  11854. return PyLong_FromSsize_t(size);
  11855. }
  11856. static PyObject *
  11857. unicode_getnewargs(PyObject *v, PyObject *Py_UNUSED(ignored))
  11858. {
  11859. PyObject *copy = _PyUnicode_Copy(v);
  11860. if (!copy)
  11861. return NULL;
  11862. return Py_BuildValue("(N)", copy);
  11863. }
  11864. static PyMethodDef unicode_methods[] = {
  11865. UNICODE_ENCODE_METHODDEF
  11866. UNICODE_REPLACE_METHODDEF
  11867. UNICODE_SPLIT_METHODDEF
  11868. UNICODE_RSPLIT_METHODDEF
  11869. UNICODE_JOIN_METHODDEF
  11870. UNICODE_CAPITALIZE_METHODDEF
  11871. UNICODE_CASEFOLD_METHODDEF
  11872. UNICODE_TITLE_METHODDEF
  11873. UNICODE_CENTER_METHODDEF
  11874. {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
  11875. UNICODE_EXPANDTABS_METHODDEF
  11876. {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
  11877. UNICODE_PARTITION_METHODDEF
  11878. {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
  11879. UNICODE_LJUST_METHODDEF
  11880. UNICODE_LOWER_METHODDEF
  11881. UNICODE_LSTRIP_METHODDEF
  11882. {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
  11883. {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
  11884. UNICODE_RJUST_METHODDEF
  11885. UNICODE_RSTRIP_METHODDEF
  11886. UNICODE_RPARTITION_METHODDEF
  11887. UNICODE_SPLITLINES_METHODDEF
  11888. UNICODE_STRIP_METHODDEF
  11889. UNICODE_SWAPCASE_METHODDEF
  11890. UNICODE_TRANSLATE_METHODDEF
  11891. UNICODE_UPPER_METHODDEF
  11892. {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
  11893. {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
  11894. UNICODE_REMOVEPREFIX_METHODDEF
  11895. UNICODE_REMOVESUFFIX_METHODDEF
  11896. UNICODE_ISASCII_METHODDEF
  11897. UNICODE_ISLOWER_METHODDEF
  11898. UNICODE_ISUPPER_METHODDEF
  11899. UNICODE_ISTITLE_METHODDEF
  11900. UNICODE_ISSPACE_METHODDEF
  11901. UNICODE_ISDECIMAL_METHODDEF
  11902. UNICODE_ISDIGIT_METHODDEF
  11903. UNICODE_ISNUMERIC_METHODDEF
  11904. UNICODE_ISALPHA_METHODDEF
  11905. UNICODE_ISALNUM_METHODDEF
  11906. UNICODE_ISIDENTIFIER_METHODDEF
  11907. UNICODE_ISPRINTABLE_METHODDEF
  11908. UNICODE_ZFILL_METHODDEF
  11909. {"format", _PyCFunction_CAST(do_string_format), METH_VARARGS | METH_KEYWORDS, format__doc__},
  11910. {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
  11911. UNICODE___FORMAT___METHODDEF
  11912. UNICODE_MAKETRANS_METHODDEF
  11913. UNICODE_SIZEOF_METHODDEF
  11914. {"__getnewargs__", unicode_getnewargs, METH_NOARGS},
  11915. {NULL, NULL}
  11916. };
  11917. static PyObject *
  11918. unicode_mod(PyObject *v, PyObject *w)
  11919. {
  11920. if (!PyUnicode_Check(v))
  11921. Py_RETURN_NOTIMPLEMENTED;
  11922. return PyUnicode_Format(v, w);
  11923. }
  11924. static PyNumberMethods unicode_as_number = {
  11925. 0, /*nb_add*/
  11926. 0, /*nb_subtract*/
  11927. 0, /*nb_multiply*/
  11928. unicode_mod, /*nb_remainder*/
  11929. };
  11930. static PySequenceMethods unicode_as_sequence = {
  11931. (lenfunc) unicode_length, /* sq_length */
  11932. PyUnicode_Concat, /* sq_concat */
  11933. (ssizeargfunc) unicode_repeat, /* sq_repeat */
  11934. (ssizeargfunc) unicode_getitem, /* sq_item */
  11935. 0, /* sq_slice */
  11936. 0, /* sq_ass_item */
  11937. 0, /* sq_ass_slice */
  11938. PyUnicode_Contains, /* sq_contains */
  11939. };
  11940. static PyObject*
  11941. unicode_subscript(PyObject* self, PyObject* item)
  11942. {
  11943. if (_PyIndex_Check(item)) {
  11944. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  11945. if (i == -1 && PyErr_Occurred())
  11946. return NULL;
  11947. if (i < 0)
  11948. i += PyUnicode_GET_LENGTH(self);
  11949. return unicode_getitem(self, i);
  11950. } else if (PySlice_Check(item)) {
  11951. Py_ssize_t start, stop, step, slicelength, i;
  11952. size_t cur;
  11953. PyObject *result;
  11954. const void *src_data;
  11955. void *dest_data;
  11956. int src_kind, dest_kind;
  11957. Py_UCS4 ch, max_char, kind_limit;
  11958. if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
  11959. return NULL;
  11960. }
  11961. slicelength = PySlice_AdjustIndices(PyUnicode_GET_LENGTH(self),
  11962. &start, &stop, step);
  11963. if (slicelength <= 0) {
  11964. _Py_RETURN_UNICODE_EMPTY();
  11965. } else if (start == 0 && step == 1 &&
  11966. slicelength == PyUnicode_GET_LENGTH(self)) {
  11967. return unicode_result_unchanged(self);
  11968. } else if (step == 1) {
  11969. return PyUnicode_Substring(self,
  11970. start, start + slicelength);
  11971. }
  11972. /* General case */
  11973. src_kind = PyUnicode_KIND(self);
  11974. src_data = PyUnicode_DATA(self);
  11975. if (!PyUnicode_IS_ASCII(self)) {
  11976. kind_limit = kind_maxchar_limit(src_kind);
  11977. max_char = 0;
  11978. for (cur = start, i = 0; i < slicelength; cur += step, i++) {
  11979. ch = PyUnicode_READ(src_kind, src_data, cur);
  11980. if (ch > max_char) {
  11981. max_char = ch;
  11982. if (max_char >= kind_limit)
  11983. break;
  11984. }
  11985. }
  11986. }
  11987. else
  11988. max_char = 127;
  11989. result = PyUnicode_New(slicelength, max_char);
  11990. if (result == NULL)
  11991. return NULL;
  11992. dest_kind = PyUnicode_KIND(result);
  11993. dest_data = PyUnicode_DATA(result);
  11994. for (cur = start, i = 0; i < slicelength; cur += step, i++) {
  11995. Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
  11996. PyUnicode_WRITE(dest_kind, dest_data, i, ch);
  11997. }
  11998. assert(_PyUnicode_CheckConsistency(result, 1));
  11999. return result;
  12000. } else {
  12001. PyErr_Format(PyExc_TypeError, "string indices must be integers, not '%.200s'",
  12002. Py_TYPE(item)->tp_name);
  12003. return NULL;
  12004. }
  12005. }
  12006. static PyMappingMethods unicode_as_mapping = {
  12007. (lenfunc)unicode_length, /* mp_length */
  12008. (binaryfunc)unicode_subscript, /* mp_subscript */
  12009. (objobjargproc)0, /* mp_ass_subscript */
  12010. };
  12011. /* Helpers for PyUnicode_Format() */
  12012. struct unicode_formatter_t {
  12013. PyObject *args;
  12014. int args_owned;
  12015. Py_ssize_t arglen, argidx;
  12016. PyObject *dict;
  12017. int fmtkind;
  12018. Py_ssize_t fmtcnt, fmtpos;
  12019. const void *fmtdata;
  12020. PyObject *fmtstr;
  12021. _PyUnicodeWriter writer;
  12022. };
  12023. struct unicode_format_arg_t {
  12024. Py_UCS4 ch;
  12025. int flags;
  12026. Py_ssize_t width;
  12027. int prec;
  12028. int sign;
  12029. };
  12030. static PyObject *
  12031. unicode_format_getnextarg(struct unicode_formatter_t *ctx)
  12032. {
  12033. Py_ssize_t argidx = ctx->argidx;
  12034. if (argidx < ctx->arglen) {
  12035. ctx->argidx++;
  12036. if (ctx->arglen < 0)
  12037. return ctx->args;
  12038. else
  12039. return PyTuple_GetItem(ctx->args, argidx);
  12040. }
  12041. PyErr_SetString(PyExc_TypeError,
  12042. "not enough arguments for format string");
  12043. return NULL;
  12044. }
  12045. /* Returns a new reference to a PyUnicode object, or NULL on failure. */
  12046. /* Format a float into the writer if the writer is not NULL, or into *p_output
  12047. otherwise.
  12048. Return 0 on success, raise an exception and return -1 on error. */
  12049. static int
  12050. formatfloat(PyObject *v, struct unicode_format_arg_t *arg,
  12051. PyObject **p_output,
  12052. _PyUnicodeWriter *writer)
  12053. {
  12054. char *p;
  12055. double x;
  12056. Py_ssize_t len;
  12057. int prec;
  12058. int dtoa_flags = 0;
  12059. x = PyFloat_AsDouble(v);
  12060. if (x == -1.0 && PyErr_Occurred())
  12061. return -1;
  12062. prec = arg->prec;
  12063. if (prec < 0)
  12064. prec = 6;
  12065. if (arg->flags & F_ALT)
  12066. dtoa_flags |= Py_DTSF_ALT;
  12067. p = PyOS_double_to_string(x, arg->ch, prec, dtoa_flags, NULL);
  12068. if (p == NULL)
  12069. return -1;
  12070. len = strlen(p);
  12071. if (writer) {
  12072. if (_PyUnicodeWriter_WriteASCIIString(writer, p, len) < 0) {
  12073. PyMem_Free(p);
  12074. return -1;
  12075. }
  12076. }
  12077. else
  12078. *p_output = _PyUnicode_FromASCII(p, len);
  12079. PyMem_Free(p);
  12080. return 0;
  12081. }
  12082. /* formatlong() emulates the format codes d, u, o, x and X, and
  12083. * the F_ALT flag, for Python's long (unbounded) ints. It's not used for
  12084. * Python's regular ints.
  12085. * Return value: a new PyUnicodeObject*, or NULL if error.
  12086. * The output string is of the form
  12087. * "-"? ("0x" | "0X")? digit+
  12088. * "0x"/"0X" are present only for x and X conversions, with F_ALT
  12089. * set in flags. The case of hex digits will be correct,
  12090. * There will be at least prec digits, zero-filled on the left if
  12091. * necessary to get that many.
  12092. * val object to be converted
  12093. * flags bitmask of format flags; only F_ALT is looked at
  12094. * prec minimum number of digits; 0-fill on left if needed
  12095. * type a character in [duoxX]; u acts the same as d
  12096. *
  12097. * CAUTION: o, x and X conversions on regular ints can never
  12098. * produce a '-' sign, but can for Python's unbounded ints.
  12099. */
  12100. PyObject *
  12101. _PyUnicode_FormatLong(PyObject *val, int alt, int prec, int type)
  12102. {
  12103. PyObject *result = NULL;
  12104. char *buf;
  12105. Py_ssize_t i;
  12106. int sign; /* 1 if '-', else 0 */
  12107. int len; /* number of characters */
  12108. Py_ssize_t llen;
  12109. int numdigits; /* len == numnondigits + numdigits */
  12110. int numnondigits = 0;
  12111. /* Avoid exceeding SSIZE_T_MAX */
  12112. if (prec > INT_MAX-3) {
  12113. PyErr_SetString(PyExc_OverflowError,
  12114. "precision too large");
  12115. return NULL;
  12116. }
  12117. assert(PyLong_Check(val));
  12118. switch (type) {
  12119. default:
  12120. Py_UNREACHABLE();
  12121. case 'd':
  12122. case 'i':
  12123. case 'u':
  12124. /* int and int subclasses should print numerically when a numeric */
  12125. /* format code is used (see issue18780) */
  12126. result = PyNumber_ToBase(val, 10);
  12127. break;
  12128. case 'o':
  12129. numnondigits = 2;
  12130. result = PyNumber_ToBase(val, 8);
  12131. break;
  12132. case 'x':
  12133. case 'X':
  12134. numnondigits = 2;
  12135. result = PyNumber_ToBase(val, 16);
  12136. break;
  12137. }
  12138. if (!result)
  12139. return NULL;
  12140. assert(unicode_modifiable(result));
  12141. assert(PyUnicode_IS_ASCII(result));
  12142. /* To modify the string in-place, there can only be one reference. */
  12143. if (Py_REFCNT(result) != 1) {
  12144. Py_DECREF(result);
  12145. PyErr_BadInternalCall();
  12146. return NULL;
  12147. }
  12148. buf = PyUnicode_DATA(result);
  12149. llen = PyUnicode_GET_LENGTH(result);
  12150. if (llen > INT_MAX) {
  12151. Py_DECREF(result);
  12152. PyErr_SetString(PyExc_ValueError,
  12153. "string too large in _PyUnicode_FormatLong");
  12154. return NULL;
  12155. }
  12156. len = (int)llen;
  12157. sign = buf[0] == '-';
  12158. numnondigits += sign;
  12159. numdigits = len - numnondigits;
  12160. assert(numdigits > 0);
  12161. /* Get rid of base marker unless F_ALT */
  12162. if (((alt) == 0 &&
  12163. (type == 'o' || type == 'x' || type == 'X'))) {
  12164. assert(buf[sign] == '0');
  12165. assert(buf[sign+1] == 'x' || buf[sign+1] == 'X' ||
  12166. buf[sign+1] == 'o');
  12167. numnondigits -= 2;
  12168. buf += 2;
  12169. len -= 2;
  12170. if (sign)
  12171. buf[0] = '-';
  12172. assert(len == numnondigits + numdigits);
  12173. assert(numdigits > 0);
  12174. }
  12175. /* Fill with leading zeroes to meet minimum width. */
  12176. if (prec > numdigits) {
  12177. PyObject *r1 = PyBytes_FromStringAndSize(NULL,
  12178. numnondigits + prec);
  12179. char *b1;
  12180. if (!r1) {
  12181. Py_DECREF(result);
  12182. return NULL;
  12183. }
  12184. b1 = PyBytes_AS_STRING(r1);
  12185. for (i = 0; i < numnondigits; ++i)
  12186. *b1++ = *buf++;
  12187. for (i = 0; i < prec - numdigits; i++)
  12188. *b1++ = '0';
  12189. for (i = 0; i < numdigits; i++)
  12190. *b1++ = *buf++;
  12191. *b1 = '\0';
  12192. Py_SETREF(result, r1);
  12193. buf = PyBytes_AS_STRING(result);
  12194. len = numnondigits + prec;
  12195. }
  12196. /* Fix up case for hex conversions. */
  12197. if (type == 'X') {
  12198. /* Need to convert all lower case letters to upper case.
  12199. and need to convert 0x to 0X (and -0x to -0X). */
  12200. for (i = 0; i < len; i++)
  12201. if (buf[i] >= 'a' && buf[i] <= 'x')
  12202. buf[i] -= 'a'-'A';
  12203. }
  12204. if (!PyUnicode_Check(result)
  12205. || buf != PyUnicode_DATA(result)) {
  12206. PyObject *unicode;
  12207. unicode = _PyUnicode_FromASCII(buf, len);
  12208. Py_SETREF(result, unicode);
  12209. }
  12210. else if (len != PyUnicode_GET_LENGTH(result)) {
  12211. if (PyUnicode_Resize(&result, len) < 0)
  12212. Py_CLEAR(result);
  12213. }
  12214. return result;
  12215. }
  12216. /* Format an integer or a float as an integer.
  12217. * Return 1 if the number has been formatted into the writer,
  12218. * 0 if the number has been formatted into *p_output
  12219. * -1 and raise an exception on error */
  12220. static int
  12221. mainformatlong(PyObject *v,
  12222. struct unicode_format_arg_t *arg,
  12223. PyObject **p_output,
  12224. _PyUnicodeWriter *writer)
  12225. {
  12226. PyObject *iobj, *res;
  12227. char type = (char)arg->ch;
  12228. if (!PyNumber_Check(v))
  12229. goto wrongtype;
  12230. /* make sure number is a type of integer for o, x, and X */
  12231. if (!PyLong_Check(v)) {
  12232. if (type == 'o' || type == 'x' || type == 'X') {
  12233. iobj = _PyNumber_Index(v);
  12234. }
  12235. else {
  12236. iobj = PyNumber_Long(v);
  12237. }
  12238. if (iobj == NULL ) {
  12239. if (PyErr_ExceptionMatches(PyExc_TypeError))
  12240. goto wrongtype;
  12241. return -1;
  12242. }
  12243. assert(PyLong_Check(iobj));
  12244. }
  12245. else {
  12246. iobj = Py_NewRef(v);
  12247. }
  12248. if (PyLong_CheckExact(v)
  12249. && arg->width == -1 && arg->prec == -1
  12250. && !(arg->flags & (F_SIGN | F_BLANK))
  12251. && type != 'X')
  12252. {
  12253. /* Fast path */
  12254. int alternate = arg->flags & F_ALT;
  12255. int base;
  12256. switch(type)
  12257. {
  12258. default:
  12259. Py_UNREACHABLE();
  12260. case 'd':
  12261. case 'i':
  12262. case 'u':
  12263. base = 10;
  12264. break;
  12265. case 'o':
  12266. base = 8;
  12267. break;
  12268. case 'x':
  12269. case 'X':
  12270. base = 16;
  12271. break;
  12272. }
  12273. if (_PyLong_FormatWriter(writer, v, base, alternate) == -1) {
  12274. Py_DECREF(iobj);
  12275. return -1;
  12276. }
  12277. Py_DECREF(iobj);
  12278. return 1;
  12279. }
  12280. res = _PyUnicode_FormatLong(iobj, arg->flags & F_ALT, arg->prec, type);
  12281. Py_DECREF(iobj);
  12282. if (res == NULL)
  12283. return -1;
  12284. *p_output = res;
  12285. return 0;
  12286. wrongtype:
  12287. switch(type)
  12288. {
  12289. case 'o':
  12290. case 'x':
  12291. case 'X':
  12292. PyErr_Format(PyExc_TypeError,
  12293. "%%%c format: an integer is required, "
  12294. "not %.200s",
  12295. type, Py_TYPE(v)->tp_name);
  12296. break;
  12297. default:
  12298. PyErr_Format(PyExc_TypeError,
  12299. "%%%c format: a real number is required, "
  12300. "not %.200s",
  12301. type, Py_TYPE(v)->tp_name);
  12302. break;
  12303. }
  12304. return -1;
  12305. }
  12306. static Py_UCS4
  12307. formatchar(PyObject *v)
  12308. {
  12309. /* presume that the buffer is at least 3 characters long */
  12310. if (PyUnicode_Check(v)) {
  12311. if (PyUnicode_GET_LENGTH(v) == 1) {
  12312. return PyUnicode_READ_CHAR(v, 0);
  12313. }
  12314. goto onError;
  12315. }
  12316. else {
  12317. int overflow;
  12318. long x = PyLong_AsLongAndOverflow(v, &overflow);
  12319. if (x == -1 && PyErr_Occurred()) {
  12320. if (PyErr_ExceptionMatches(PyExc_TypeError)) {
  12321. goto onError;
  12322. }
  12323. return (Py_UCS4) -1;
  12324. }
  12325. if (x < 0 || x > MAX_UNICODE) {
  12326. /* this includes an overflow in converting to C long */
  12327. PyErr_SetString(PyExc_OverflowError,
  12328. "%c arg not in range(0x110000)");
  12329. return (Py_UCS4) -1;
  12330. }
  12331. return (Py_UCS4) x;
  12332. }
  12333. onError:
  12334. PyErr_SetString(PyExc_TypeError,
  12335. "%c requires int or char");
  12336. return (Py_UCS4) -1;
  12337. }
  12338. /* Parse options of an argument: flags, width, precision.
  12339. Handle also "%(name)" syntax.
  12340. Return 0 if the argument has been formatted into arg->str.
  12341. Return 1 if the argument has been written into ctx->writer,
  12342. Raise an exception and return -1 on error. */
  12343. static int
  12344. unicode_format_arg_parse(struct unicode_formatter_t *ctx,
  12345. struct unicode_format_arg_t *arg)
  12346. {
  12347. #define FORMAT_READ(ctx) \
  12348. PyUnicode_READ((ctx)->fmtkind, (ctx)->fmtdata, (ctx)->fmtpos)
  12349. PyObject *v;
  12350. if (arg->ch == '(') {
  12351. /* Get argument value from a dictionary. Example: "%(name)s". */
  12352. Py_ssize_t keystart;
  12353. Py_ssize_t keylen;
  12354. PyObject *key;
  12355. int pcount = 1;
  12356. if (ctx->dict == NULL) {
  12357. PyErr_SetString(PyExc_TypeError,
  12358. "format requires a mapping");
  12359. return -1;
  12360. }
  12361. ++ctx->fmtpos;
  12362. --ctx->fmtcnt;
  12363. keystart = ctx->fmtpos;
  12364. /* Skip over balanced parentheses */
  12365. while (pcount > 0 && --ctx->fmtcnt >= 0) {
  12366. arg->ch = FORMAT_READ(ctx);
  12367. if (arg->ch == ')')
  12368. --pcount;
  12369. else if (arg->ch == '(')
  12370. ++pcount;
  12371. ctx->fmtpos++;
  12372. }
  12373. keylen = ctx->fmtpos - keystart - 1;
  12374. if (ctx->fmtcnt < 0 || pcount > 0) {
  12375. PyErr_SetString(PyExc_ValueError,
  12376. "incomplete format key");
  12377. return -1;
  12378. }
  12379. key = PyUnicode_Substring(ctx->fmtstr,
  12380. keystart, keystart + keylen);
  12381. if (key == NULL)
  12382. return -1;
  12383. if (ctx->args_owned) {
  12384. ctx->args_owned = 0;
  12385. Py_DECREF(ctx->args);
  12386. }
  12387. ctx->args = PyObject_GetItem(ctx->dict, key);
  12388. Py_DECREF(key);
  12389. if (ctx->args == NULL)
  12390. return -1;
  12391. ctx->args_owned = 1;
  12392. ctx->arglen = -1;
  12393. ctx->argidx = -2;
  12394. }
  12395. /* Parse flags. Example: "%+i" => flags=F_SIGN. */
  12396. while (--ctx->fmtcnt >= 0) {
  12397. arg->ch = FORMAT_READ(ctx);
  12398. ctx->fmtpos++;
  12399. switch (arg->ch) {
  12400. case '-': arg->flags |= F_LJUST; continue;
  12401. case '+': arg->flags |= F_SIGN; continue;
  12402. case ' ': arg->flags |= F_BLANK; continue;
  12403. case '#': arg->flags |= F_ALT; continue;
  12404. case '0': arg->flags |= F_ZERO; continue;
  12405. }
  12406. break;
  12407. }
  12408. /* Parse width. Example: "%10s" => width=10 */
  12409. if (arg->ch == '*') {
  12410. v = unicode_format_getnextarg(ctx);
  12411. if (v == NULL)
  12412. return -1;
  12413. if (!PyLong_Check(v)) {
  12414. PyErr_SetString(PyExc_TypeError,
  12415. "* wants int");
  12416. return -1;
  12417. }
  12418. arg->width = PyLong_AsSsize_t(v);
  12419. if (arg->width == -1 && PyErr_Occurred())
  12420. return -1;
  12421. if (arg->width < 0) {
  12422. arg->flags |= F_LJUST;
  12423. arg->width = -arg->width;
  12424. }
  12425. if (--ctx->fmtcnt >= 0) {
  12426. arg->ch = FORMAT_READ(ctx);
  12427. ctx->fmtpos++;
  12428. }
  12429. }
  12430. else if (arg->ch >= '0' && arg->ch <= '9') {
  12431. arg->width = arg->ch - '0';
  12432. while (--ctx->fmtcnt >= 0) {
  12433. arg->ch = FORMAT_READ(ctx);
  12434. ctx->fmtpos++;
  12435. if (arg->ch < '0' || arg->ch > '9')
  12436. break;
  12437. /* Since arg->ch is unsigned, the RHS would end up as unsigned,
  12438. mixing signed and unsigned comparison. Since arg->ch is between
  12439. '0' and '9', casting to int is safe. */
  12440. if (arg->width > (PY_SSIZE_T_MAX - ((int)arg->ch - '0')) / 10) {
  12441. PyErr_SetString(PyExc_ValueError,
  12442. "width too big");
  12443. return -1;
  12444. }
  12445. arg->width = arg->width*10 + (arg->ch - '0');
  12446. }
  12447. }
  12448. /* Parse precision. Example: "%.3f" => prec=3 */
  12449. if (arg->ch == '.') {
  12450. arg->prec = 0;
  12451. if (--ctx->fmtcnt >= 0) {
  12452. arg->ch = FORMAT_READ(ctx);
  12453. ctx->fmtpos++;
  12454. }
  12455. if (arg->ch == '*') {
  12456. v = unicode_format_getnextarg(ctx);
  12457. if (v == NULL)
  12458. return -1;
  12459. if (!PyLong_Check(v)) {
  12460. PyErr_SetString(PyExc_TypeError,
  12461. "* wants int");
  12462. return -1;
  12463. }
  12464. arg->prec = _PyLong_AsInt(v);
  12465. if (arg->prec == -1 && PyErr_Occurred())
  12466. return -1;
  12467. if (arg->prec < 0)
  12468. arg->prec = 0;
  12469. if (--ctx->fmtcnt >= 0) {
  12470. arg->ch = FORMAT_READ(ctx);
  12471. ctx->fmtpos++;
  12472. }
  12473. }
  12474. else if (arg->ch >= '0' && arg->ch <= '9') {
  12475. arg->prec = arg->ch - '0';
  12476. while (--ctx->fmtcnt >= 0) {
  12477. arg->ch = FORMAT_READ(ctx);
  12478. ctx->fmtpos++;
  12479. if (arg->ch < '0' || arg->ch > '9')
  12480. break;
  12481. if (arg->prec > (INT_MAX - ((int)arg->ch - '0')) / 10) {
  12482. PyErr_SetString(PyExc_ValueError,
  12483. "precision too big");
  12484. return -1;
  12485. }
  12486. arg->prec = arg->prec*10 + (arg->ch - '0');
  12487. }
  12488. }
  12489. }
  12490. /* Ignore "h", "l" and "L" format prefix (ex: "%hi" or "%ls") */
  12491. if (ctx->fmtcnt >= 0) {
  12492. if (arg->ch == 'h' || arg->ch == 'l' || arg->ch == 'L') {
  12493. if (--ctx->fmtcnt >= 0) {
  12494. arg->ch = FORMAT_READ(ctx);
  12495. ctx->fmtpos++;
  12496. }
  12497. }
  12498. }
  12499. if (ctx->fmtcnt < 0) {
  12500. PyErr_SetString(PyExc_ValueError,
  12501. "incomplete format");
  12502. return -1;
  12503. }
  12504. return 0;
  12505. #undef FORMAT_READ
  12506. }
  12507. /* Format one argument. Supported conversion specifiers:
  12508. - "s", "r", "a": any type
  12509. - "i", "d", "u": int or float
  12510. - "o", "x", "X": int
  12511. - "e", "E", "f", "F", "g", "G": float
  12512. - "c": int or str (1 character)
  12513. When possible, the output is written directly into the Unicode writer
  12514. (ctx->writer). A string is created when padding is required.
  12515. Return 0 if the argument has been formatted into *p_str,
  12516. 1 if the argument has been written into ctx->writer,
  12517. -1 on error. */
  12518. static int
  12519. unicode_format_arg_format(struct unicode_formatter_t *ctx,
  12520. struct unicode_format_arg_t *arg,
  12521. PyObject **p_str)
  12522. {
  12523. PyObject *v;
  12524. _PyUnicodeWriter *writer = &ctx->writer;
  12525. if (ctx->fmtcnt == 0)
  12526. ctx->writer.overallocate = 0;
  12527. v = unicode_format_getnextarg(ctx);
  12528. if (v == NULL)
  12529. return -1;
  12530. switch (arg->ch) {
  12531. case 's':
  12532. case 'r':
  12533. case 'a':
  12534. if (PyLong_CheckExact(v) && arg->width == -1 && arg->prec == -1) {
  12535. /* Fast path */
  12536. if (_PyLong_FormatWriter(writer, v, 10, arg->flags & F_ALT) == -1)
  12537. return -1;
  12538. return 1;
  12539. }
  12540. if (PyUnicode_CheckExact(v) && arg->ch == 's') {
  12541. *p_str = Py_NewRef(v);
  12542. }
  12543. else {
  12544. if (arg->ch == 's')
  12545. *p_str = PyObject_Str(v);
  12546. else if (arg->ch == 'r')
  12547. *p_str = PyObject_Repr(v);
  12548. else
  12549. *p_str = PyObject_ASCII(v);
  12550. }
  12551. break;
  12552. case 'i':
  12553. case 'd':
  12554. case 'u':
  12555. case 'o':
  12556. case 'x':
  12557. case 'X':
  12558. {
  12559. int ret = mainformatlong(v, arg, p_str, writer);
  12560. if (ret != 0)
  12561. return ret;
  12562. arg->sign = 1;
  12563. break;
  12564. }
  12565. case 'e':
  12566. case 'E':
  12567. case 'f':
  12568. case 'F':
  12569. case 'g':
  12570. case 'G':
  12571. if (arg->width == -1 && arg->prec == -1
  12572. && !(arg->flags & (F_SIGN | F_BLANK)))
  12573. {
  12574. /* Fast path */
  12575. if (formatfloat(v, arg, NULL, writer) == -1)
  12576. return -1;
  12577. return 1;
  12578. }
  12579. arg->sign = 1;
  12580. if (formatfloat(v, arg, p_str, NULL) == -1)
  12581. return -1;
  12582. break;
  12583. case 'c':
  12584. {
  12585. Py_UCS4 ch = formatchar(v);
  12586. if (ch == (Py_UCS4) -1)
  12587. return -1;
  12588. if (arg->width == -1 && arg->prec == -1) {
  12589. /* Fast path */
  12590. if (_PyUnicodeWriter_WriteCharInline(writer, ch) < 0)
  12591. return -1;
  12592. return 1;
  12593. }
  12594. *p_str = PyUnicode_FromOrdinal(ch);
  12595. break;
  12596. }
  12597. default:
  12598. PyErr_Format(PyExc_ValueError,
  12599. "unsupported format character '%c' (0x%x) "
  12600. "at index %zd",
  12601. (31<=arg->ch && arg->ch<=126) ? (char)arg->ch : '?',
  12602. (int)arg->ch,
  12603. ctx->fmtpos - 1);
  12604. return -1;
  12605. }
  12606. if (*p_str == NULL)
  12607. return -1;
  12608. assert (PyUnicode_Check(*p_str));
  12609. return 0;
  12610. }
  12611. static int
  12612. unicode_format_arg_output(struct unicode_formatter_t *ctx,
  12613. struct unicode_format_arg_t *arg,
  12614. PyObject *str)
  12615. {
  12616. Py_ssize_t len;
  12617. int kind;
  12618. const void *pbuf;
  12619. Py_ssize_t pindex;
  12620. Py_UCS4 signchar;
  12621. Py_ssize_t buflen;
  12622. Py_UCS4 maxchar;
  12623. Py_ssize_t sublen;
  12624. _PyUnicodeWriter *writer = &ctx->writer;
  12625. Py_UCS4 fill;
  12626. fill = ' ';
  12627. if (arg->sign && arg->flags & F_ZERO)
  12628. fill = '0';
  12629. len = PyUnicode_GET_LENGTH(str);
  12630. if ((arg->width == -1 || arg->width <= len)
  12631. && (arg->prec == -1 || arg->prec >= len)
  12632. && !(arg->flags & (F_SIGN | F_BLANK)))
  12633. {
  12634. /* Fast path */
  12635. if (_PyUnicodeWriter_WriteStr(writer, str) == -1)
  12636. return -1;
  12637. return 0;
  12638. }
  12639. /* Truncate the string for "s", "r" and "a" formats
  12640. if the precision is set */
  12641. if (arg->ch == 's' || arg->ch == 'r' || arg->ch == 'a') {
  12642. if (arg->prec >= 0 && len > arg->prec)
  12643. len = arg->prec;
  12644. }
  12645. /* Adjust sign and width */
  12646. kind = PyUnicode_KIND(str);
  12647. pbuf = PyUnicode_DATA(str);
  12648. pindex = 0;
  12649. signchar = '\0';
  12650. if (arg->sign) {
  12651. Py_UCS4 ch = PyUnicode_READ(kind, pbuf, pindex);
  12652. if (ch == '-' || ch == '+') {
  12653. signchar = ch;
  12654. len--;
  12655. pindex++;
  12656. }
  12657. else if (arg->flags & F_SIGN)
  12658. signchar = '+';
  12659. else if (arg->flags & F_BLANK)
  12660. signchar = ' ';
  12661. else
  12662. arg->sign = 0;
  12663. }
  12664. if (arg->width < len)
  12665. arg->width = len;
  12666. /* Prepare the writer */
  12667. maxchar = writer->maxchar;
  12668. if (!(arg->flags & F_LJUST)) {
  12669. if (arg->sign) {
  12670. if ((arg->width-1) > len)
  12671. maxchar = Py_MAX(maxchar, fill);
  12672. }
  12673. else {
  12674. if (arg->width > len)
  12675. maxchar = Py_MAX(maxchar, fill);
  12676. }
  12677. }
  12678. if (PyUnicode_MAX_CHAR_VALUE(str) > maxchar) {
  12679. Py_UCS4 strmaxchar = _PyUnicode_FindMaxChar(str, 0, pindex+len);
  12680. maxchar = Py_MAX(maxchar, strmaxchar);
  12681. }
  12682. buflen = arg->width;
  12683. if (arg->sign && len == arg->width)
  12684. buflen++;
  12685. if (_PyUnicodeWriter_Prepare(writer, buflen, maxchar) == -1)
  12686. return -1;
  12687. /* Write the sign if needed */
  12688. if (arg->sign) {
  12689. if (fill != ' ') {
  12690. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
  12691. writer->pos += 1;
  12692. }
  12693. if (arg->width > len)
  12694. arg->width--;
  12695. }
  12696. /* Write the numeric prefix for "x", "X" and "o" formats
  12697. if the alternate form is used.
  12698. For example, write "0x" for the "%#x" format. */
  12699. if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
  12700. assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
  12701. assert(PyUnicode_READ(kind, pbuf, pindex + 1) == arg->ch);
  12702. if (fill != ' ') {
  12703. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
  12704. PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
  12705. writer->pos += 2;
  12706. pindex += 2;
  12707. }
  12708. arg->width -= 2;
  12709. if (arg->width < 0)
  12710. arg->width = 0;
  12711. len -= 2;
  12712. }
  12713. /* Pad left with the fill character if needed */
  12714. if (arg->width > len && !(arg->flags & F_LJUST)) {
  12715. sublen = arg->width - len;
  12716. unicode_fill(writer->kind, writer->data, fill, writer->pos, sublen);
  12717. writer->pos += sublen;
  12718. arg->width = len;
  12719. }
  12720. /* If padding with spaces: write sign if needed and/or numeric prefix if
  12721. the alternate form is used */
  12722. if (fill == ' ') {
  12723. if (arg->sign) {
  12724. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, signchar);
  12725. writer->pos += 1;
  12726. }
  12727. if ((arg->flags & F_ALT) && (arg->ch == 'x' || arg->ch == 'X' || arg->ch == 'o')) {
  12728. assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
  12729. assert(PyUnicode_READ(kind, pbuf, pindex+1) == arg->ch);
  12730. PyUnicode_WRITE(writer->kind, writer->data, writer->pos, '0');
  12731. PyUnicode_WRITE(writer->kind, writer->data, writer->pos+1, arg->ch);
  12732. writer->pos += 2;
  12733. pindex += 2;
  12734. }
  12735. }
  12736. /* Write characters */
  12737. if (len) {
  12738. _PyUnicode_FastCopyCharacters(writer->buffer, writer->pos,
  12739. str, pindex, len);
  12740. writer->pos += len;
  12741. }
  12742. /* Pad right with the fill character if needed */
  12743. if (arg->width > len) {
  12744. sublen = arg->width - len;
  12745. unicode_fill(writer->kind, writer->data, ' ', writer->pos, sublen);
  12746. writer->pos += sublen;
  12747. }
  12748. return 0;
  12749. }
  12750. /* Helper of PyUnicode_Format(): format one arg.
  12751. Return 0 on success, raise an exception and return -1 on error. */
  12752. static int
  12753. unicode_format_arg(struct unicode_formatter_t *ctx)
  12754. {
  12755. struct unicode_format_arg_t arg;
  12756. PyObject *str;
  12757. int ret;
  12758. arg.ch = PyUnicode_READ(ctx->fmtkind, ctx->fmtdata, ctx->fmtpos);
  12759. if (arg.ch == '%') {
  12760. ctx->fmtpos++;
  12761. ctx->fmtcnt--;
  12762. if (_PyUnicodeWriter_WriteCharInline(&ctx->writer, '%') < 0)
  12763. return -1;
  12764. return 0;
  12765. }
  12766. arg.flags = 0;
  12767. arg.width = -1;
  12768. arg.prec = -1;
  12769. arg.sign = 0;
  12770. str = NULL;
  12771. ret = unicode_format_arg_parse(ctx, &arg);
  12772. if (ret == -1)
  12773. return -1;
  12774. ret = unicode_format_arg_format(ctx, &arg, &str);
  12775. if (ret == -1)
  12776. return -1;
  12777. if (ret != 1) {
  12778. ret = unicode_format_arg_output(ctx, &arg, str);
  12779. Py_DECREF(str);
  12780. if (ret == -1)
  12781. return -1;
  12782. }
  12783. if (ctx->dict && (ctx->argidx < ctx->arglen)) {
  12784. PyErr_SetString(PyExc_TypeError,
  12785. "not all arguments converted during string formatting");
  12786. return -1;
  12787. }
  12788. return 0;
  12789. }
  12790. PyObject *
  12791. PyUnicode_Format(PyObject *format, PyObject *args)
  12792. {
  12793. struct unicode_formatter_t ctx;
  12794. if (format == NULL || args == NULL) {
  12795. PyErr_BadInternalCall();
  12796. return NULL;
  12797. }
  12798. if (ensure_unicode(format) < 0)
  12799. return NULL;
  12800. ctx.fmtstr = format;
  12801. ctx.fmtdata = PyUnicode_DATA(ctx.fmtstr);
  12802. ctx.fmtkind = PyUnicode_KIND(ctx.fmtstr);
  12803. ctx.fmtcnt = PyUnicode_GET_LENGTH(ctx.fmtstr);
  12804. ctx.fmtpos = 0;
  12805. _PyUnicodeWriter_Init(&ctx.writer);
  12806. ctx.writer.min_length = ctx.fmtcnt + 100;
  12807. ctx.writer.overallocate = 1;
  12808. if (PyTuple_Check(args)) {
  12809. ctx.arglen = PyTuple_Size(args);
  12810. ctx.argidx = 0;
  12811. }
  12812. else {
  12813. ctx.arglen = -1;
  12814. ctx.argidx = -2;
  12815. }
  12816. ctx.args_owned = 0;
  12817. if (PyMapping_Check(args) && !PyTuple_Check(args) && !PyUnicode_Check(args))
  12818. ctx.dict = args;
  12819. else
  12820. ctx.dict = NULL;
  12821. ctx.args = args;
  12822. while (--ctx.fmtcnt >= 0) {
  12823. if (PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
  12824. Py_ssize_t nonfmtpos;
  12825. nonfmtpos = ctx.fmtpos++;
  12826. while (ctx.fmtcnt >= 0 &&
  12827. PyUnicode_READ(ctx.fmtkind, ctx.fmtdata, ctx.fmtpos) != '%') {
  12828. ctx.fmtpos++;
  12829. ctx.fmtcnt--;
  12830. }
  12831. if (ctx.fmtcnt < 0) {
  12832. ctx.fmtpos--;
  12833. ctx.writer.overallocate = 0;
  12834. }
  12835. if (_PyUnicodeWriter_WriteSubstring(&ctx.writer, ctx.fmtstr,
  12836. nonfmtpos, ctx.fmtpos) < 0)
  12837. goto onError;
  12838. }
  12839. else {
  12840. ctx.fmtpos++;
  12841. if (unicode_format_arg(&ctx) == -1)
  12842. goto onError;
  12843. }
  12844. }
  12845. if (ctx.argidx < ctx.arglen && !ctx.dict) {
  12846. PyErr_SetString(PyExc_TypeError,
  12847. "not all arguments converted during string formatting");
  12848. goto onError;
  12849. }
  12850. if (ctx.args_owned) {
  12851. Py_DECREF(ctx.args);
  12852. }
  12853. return _PyUnicodeWriter_Finish(&ctx.writer);
  12854. onError:
  12855. _PyUnicodeWriter_Dealloc(&ctx.writer);
  12856. if (ctx.args_owned) {
  12857. Py_DECREF(ctx.args);
  12858. }
  12859. return NULL;
  12860. }
  12861. static PyObject *
  12862. unicode_subtype_new(PyTypeObject *type, PyObject *unicode);
  12863. /*[clinic input]
  12864. @classmethod
  12865. str.__new__ as unicode_new
  12866. object as x: object = NULL
  12867. encoding: str = NULL
  12868. errors: str = NULL
  12869. [clinic start generated code]*/
  12870. static PyObject *
  12871. unicode_new_impl(PyTypeObject *type, PyObject *x, const char *encoding,
  12872. const char *errors)
  12873. /*[clinic end generated code: output=fc72d4878b0b57e9 input=e81255e5676d174e]*/
  12874. {
  12875. PyObject *unicode;
  12876. if (x == NULL) {
  12877. unicode = unicode_new_empty();
  12878. }
  12879. else if (encoding == NULL && errors == NULL) {
  12880. unicode = PyObject_Str(x);
  12881. }
  12882. else {
  12883. unicode = PyUnicode_FromEncodedObject(x, encoding, errors);
  12884. }
  12885. if (unicode != NULL && type != &PyUnicode_Type) {
  12886. Py_SETREF(unicode, unicode_subtype_new(type, unicode));
  12887. }
  12888. return unicode;
  12889. }
  12890. static PyObject *
  12891. unicode_subtype_new(PyTypeObject *type, PyObject *unicode)
  12892. {
  12893. PyObject *self;
  12894. Py_ssize_t length, char_size;
  12895. int share_utf8;
  12896. int kind;
  12897. void *data;
  12898. assert(PyType_IsSubtype(type, &PyUnicode_Type));
  12899. assert(_PyUnicode_CHECK(unicode));
  12900. self = type->tp_alloc(type, 0);
  12901. if (self == NULL) {
  12902. return NULL;
  12903. }
  12904. kind = PyUnicode_KIND(unicode);
  12905. length = PyUnicode_GET_LENGTH(unicode);
  12906. _PyUnicode_LENGTH(self) = length;
  12907. #ifdef Py_DEBUG
  12908. _PyUnicode_HASH(self) = -1;
  12909. #else
  12910. _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
  12911. #endif
  12912. _PyUnicode_STATE(self).interned = 0;
  12913. _PyUnicode_STATE(self).kind = kind;
  12914. _PyUnicode_STATE(self).compact = 0;
  12915. _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
  12916. _PyUnicode_STATE(self).statically_allocated = 0;
  12917. _PyUnicode_UTF8_LENGTH(self) = 0;
  12918. _PyUnicode_UTF8(self) = NULL;
  12919. _PyUnicode_DATA_ANY(self) = NULL;
  12920. share_utf8 = 0;
  12921. if (kind == PyUnicode_1BYTE_KIND) {
  12922. char_size = 1;
  12923. if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
  12924. share_utf8 = 1;
  12925. }
  12926. else if (kind == PyUnicode_2BYTE_KIND) {
  12927. char_size = 2;
  12928. }
  12929. else {
  12930. assert(kind == PyUnicode_4BYTE_KIND);
  12931. char_size = 4;
  12932. }
  12933. /* Ensure we won't overflow the length. */
  12934. if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
  12935. PyErr_NoMemory();
  12936. goto onError;
  12937. }
  12938. data = PyObject_Malloc((length + 1) * char_size);
  12939. if (data == NULL) {
  12940. PyErr_NoMemory();
  12941. goto onError;
  12942. }
  12943. _PyUnicode_DATA_ANY(self) = data;
  12944. if (share_utf8) {
  12945. _PyUnicode_UTF8_LENGTH(self) = length;
  12946. _PyUnicode_UTF8(self) = data;
  12947. }
  12948. memcpy(data, PyUnicode_DATA(unicode), kind * (length + 1));
  12949. assert(_PyUnicode_CheckConsistency(self, 1));
  12950. #ifdef Py_DEBUG
  12951. _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
  12952. #endif
  12953. return self;
  12954. onError:
  12955. Py_DECREF(self);
  12956. return NULL;
  12957. }
  12958. void
  12959. _PyUnicode_ExactDealloc(PyObject *op)
  12960. {
  12961. assert(PyUnicode_CheckExact(op));
  12962. unicode_dealloc(op);
  12963. }
  12964. PyDoc_STRVAR(unicode_doc,
  12965. "str(object='') -> str\n\
  12966. str(bytes_or_buffer[, encoding[, errors]]) -> str\n\
  12967. \n\
  12968. Create a new string object from the given object. If encoding or\n\
  12969. errors is specified, then the object must expose a data buffer\n\
  12970. that will be decoded using the given encoding and error handler.\n\
  12971. Otherwise, returns the result of object.__str__() (if defined)\n\
  12972. or repr(object).\n\
  12973. encoding defaults to sys.getdefaultencoding().\n\
  12974. errors defaults to 'strict'.");
  12975. static PyObject *unicode_iter(PyObject *seq);
  12976. PyTypeObject PyUnicode_Type = {
  12977. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  12978. "str", /* tp_name */
  12979. sizeof(PyUnicodeObject), /* tp_basicsize */
  12980. 0, /* tp_itemsize */
  12981. /* Slots */
  12982. (destructor)unicode_dealloc, /* tp_dealloc */
  12983. 0, /* tp_vectorcall_offset */
  12984. 0, /* tp_getattr */
  12985. 0, /* tp_setattr */
  12986. 0, /* tp_as_async */
  12987. unicode_repr, /* tp_repr */
  12988. &unicode_as_number, /* tp_as_number */
  12989. &unicode_as_sequence, /* tp_as_sequence */
  12990. &unicode_as_mapping, /* tp_as_mapping */
  12991. (hashfunc) unicode_hash, /* tp_hash*/
  12992. 0, /* tp_call*/
  12993. (reprfunc) unicode_str, /* tp_str */
  12994. PyObject_GenericGetAttr, /* tp_getattro */
  12995. 0, /* tp_setattro */
  12996. 0, /* tp_as_buffer */
  12997. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  12998. Py_TPFLAGS_UNICODE_SUBCLASS |
  12999. _Py_TPFLAGS_MATCH_SELF, /* tp_flags */
  13000. unicode_doc, /* tp_doc */
  13001. 0, /* tp_traverse */
  13002. 0, /* tp_clear */
  13003. PyUnicode_RichCompare, /* tp_richcompare */
  13004. 0, /* tp_weaklistoffset */
  13005. unicode_iter, /* tp_iter */
  13006. 0, /* tp_iternext */
  13007. unicode_methods, /* tp_methods */
  13008. 0, /* tp_members */
  13009. 0, /* tp_getset */
  13010. 0, /* tp_base */
  13011. 0, /* tp_dict */
  13012. 0, /* tp_descr_get */
  13013. 0, /* tp_descr_set */
  13014. 0, /* tp_dictoffset */
  13015. 0, /* tp_init */
  13016. 0, /* tp_alloc */
  13017. unicode_new, /* tp_new */
  13018. PyObject_Del, /* tp_free */
  13019. };
  13020. /* Initialize the Unicode implementation */
  13021. static void
  13022. _init_global_state(void)
  13023. {
  13024. static int initialized = 0;
  13025. if (initialized) {
  13026. return;
  13027. }
  13028. initialized = 1;
  13029. /* initialize the linebreak bloom filter */
  13030. const Py_UCS2 linebreak[] = {
  13031. 0x000A, /* LINE FEED */
  13032. 0x000D, /* CARRIAGE RETURN */
  13033. 0x001C, /* FILE SEPARATOR */
  13034. 0x001D, /* GROUP SEPARATOR */
  13035. 0x001E, /* RECORD SEPARATOR */
  13036. 0x0085, /* NEXT LINE */
  13037. 0x2028, /* LINE SEPARATOR */
  13038. 0x2029, /* PARAGRAPH SEPARATOR */
  13039. };
  13040. bloom_linebreak = make_bloom_mask(
  13041. PyUnicode_2BYTE_KIND, linebreak,
  13042. Py_ARRAY_LENGTH(linebreak));
  13043. }
  13044. void
  13045. _PyUnicode_InitState(PyInterpreterState *interp)
  13046. {
  13047. if (!_Py_IsMainInterpreter(interp)) {
  13048. return;
  13049. }
  13050. _init_global_state();
  13051. }
  13052. PyStatus
  13053. _PyUnicode_InitGlobalObjects(PyInterpreterState *interp)
  13054. {
  13055. // Initialize the global interned dict
  13056. if (init_interned_dict(interp)) {
  13057. PyErr_Clear();
  13058. return _PyStatus_ERR("failed to create interned dict");
  13059. }
  13060. if (_Py_IsMainInterpreter(interp)) {
  13061. /* Intern statically allocated string identifiers and deepfreeze strings.
  13062. * This must be done before any module initialization so that statically
  13063. * allocated string identifiers are used instead of heap allocated strings.
  13064. * Deepfreeze uses the interned identifiers if present to save space
  13065. * else generates them and they are interned to speed up dict lookups.
  13066. */
  13067. _PyUnicode_InitStaticStrings(interp);
  13068. #ifdef Py_DEBUG
  13069. assert(_PyUnicode_CheckConsistency(&_Py_STR(empty), 1));
  13070. for (int i = 0; i < 256; i++) {
  13071. assert(_PyUnicode_CheckConsistency(LATIN1(i), 1));
  13072. }
  13073. #endif
  13074. }
  13075. return _PyStatus_OK();
  13076. }
  13077. PyStatus
  13078. _PyUnicode_InitTypes(PyInterpreterState *interp)
  13079. {
  13080. if (_PyStaticType_InitBuiltin(interp, &EncodingMapType) < 0) {
  13081. goto error;
  13082. }
  13083. if (_PyStaticType_InitBuiltin(interp, &PyFieldNameIter_Type) < 0) {
  13084. goto error;
  13085. }
  13086. if (_PyStaticType_InitBuiltin(interp, &PyFormatterIter_Type) < 0) {
  13087. goto error;
  13088. }
  13089. return _PyStatus_OK();
  13090. error:
  13091. return _PyStatus_ERR("Can't initialize unicode types");
  13092. }
  13093. void
  13094. _PyUnicode_InternInPlace(PyInterpreterState *interp, PyObject **p)
  13095. {
  13096. PyObject *s = *p;
  13097. #ifdef Py_DEBUG
  13098. assert(s != NULL);
  13099. assert(_PyUnicode_CHECK(s));
  13100. #else
  13101. if (s == NULL || !PyUnicode_Check(s)) {
  13102. return;
  13103. }
  13104. #endif
  13105. /* If it's a subclass, we don't really know what putting
  13106. it in the interned dict might do. */
  13107. if (!PyUnicode_CheckExact(s)) {
  13108. return;
  13109. }
  13110. if (PyUnicode_CHECK_INTERNED(s)) {
  13111. return;
  13112. }
  13113. /* Look in the global cache first. */
  13114. PyObject *r = (PyObject *)_Py_hashtable_get(INTERNED_STRINGS, s);
  13115. if (r != NULL && r != s) {
  13116. Py_SETREF(*p, Py_NewRef(r));
  13117. return;
  13118. }
  13119. /* Handle statically allocated strings. */
  13120. if (_PyUnicode_STATE(s).statically_allocated) {
  13121. assert(_Py_IsImmortal(s));
  13122. if (_Py_hashtable_set(INTERNED_STRINGS, s, s) == 0) {
  13123. _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL_STATIC;
  13124. }
  13125. return;
  13126. }
  13127. /* Look in the per-interpreter cache. */
  13128. PyObject *interned = get_interned_dict(interp);
  13129. assert(interned != NULL);
  13130. PyObject *t = PyDict_SetDefault(interned, s, s);
  13131. if (t == NULL) {
  13132. PyErr_Clear();
  13133. return;
  13134. }
  13135. if (t != s) {
  13136. Py_SETREF(*p, Py_NewRef(t));
  13137. return;
  13138. }
  13139. if (_Py_IsImmortal(s)) {
  13140. // XXX Restrict this to the main interpreter?
  13141. _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL_STATIC;
  13142. return;
  13143. }
  13144. #ifdef Py_REF_DEBUG
  13145. /* The reference count value excluding the 2 references from the
  13146. interned dictionary should be excluded from the RefTotal. The
  13147. decrements to these objects will not be registered so they
  13148. need to be accounted for in here. */
  13149. for (Py_ssize_t i = 0; i < Py_REFCNT(s) - 2; i++) {
  13150. _Py_DecRefTotal(_PyInterpreterState_GET());
  13151. }
  13152. #endif
  13153. _Py_SetImmortal(s);
  13154. _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
  13155. }
  13156. void
  13157. PyUnicode_InternInPlace(PyObject **p)
  13158. {
  13159. PyInterpreterState *interp = _PyInterpreterState_GET();
  13160. _PyUnicode_InternInPlace(interp, p);
  13161. }
  13162. // Function kept for the stable ABI.
  13163. PyAPI_FUNC(void) PyUnicode_InternImmortal(PyObject **);
  13164. void
  13165. PyUnicode_InternImmortal(PyObject **p)
  13166. {
  13167. PyUnicode_InternInPlace(p);
  13168. // Leak a reference on purpose
  13169. Py_INCREF(*p);
  13170. }
  13171. PyObject *
  13172. PyUnicode_InternFromString(const char *cp)
  13173. {
  13174. PyObject *s = PyUnicode_FromString(cp);
  13175. if (s == NULL)
  13176. return NULL;
  13177. PyUnicode_InternInPlace(&s);
  13178. return s;
  13179. }
  13180. void
  13181. _PyUnicode_ClearInterned(PyInterpreterState *interp)
  13182. {
  13183. PyObject *interned = get_interned_dict(interp);
  13184. if (interned == NULL) {
  13185. return;
  13186. }
  13187. assert(PyDict_CheckExact(interned));
  13188. /* TODO:
  13189. * Currently, the runtime is not able to guarantee that it can exit without
  13190. * allocations that carry over to a future initialization of Python within
  13191. * the same process. i.e:
  13192. * ./python -X showrefcount -c 'import itertools'
  13193. * [237 refs, 237 blocks]
  13194. *
  13195. * Therefore, this should remain disabled for until there is a strict guarantee
  13196. * that no memory will be left after `Py_Finalize`.
  13197. */
  13198. #ifdef Py_DEBUG
  13199. /* For all non-singleton interned strings, restore the two valid references
  13200. to that instance from within the intern string dictionary and let the
  13201. normal reference counting process clean up these instances. */
  13202. #ifdef INTERNED_STATS
  13203. fprintf(stderr, "releasing %zd interned strings\n",
  13204. PyDict_GET_SIZE(interned));
  13205. Py_ssize_t total_length = 0;
  13206. #endif
  13207. Py_ssize_t pos = 0;
  13208. PyObject *s, *ignored_value;
  13209. while (PyDict_Next(interned, &pos, &s, &ignored_value)) {
  13210. assert(PyUnicode_IS_READY(s));
  13211. int shared = 0;
  13212. switch (PyUnicode_CHECK_INTERNED(s)) {
  13213. case SSTATE_INTERNED_IMMORTAL:
  13214. // Skip the Immortal Instance check and restore
  13215. // the two references (key and value) ignored
  13216. // by PyUnicode_InternInPlace().
  13217. s->ob_refcnt = 2;
  13218. #ifdef INTERNED_STATS
  13219. total_length += PyUnicode_GET_LENGTH(s);
  13220. #endif
  13221. break;
  13222. case SSTATE_INTERNED_IMMORTAL_STATIC:
  13223. /* It is shared between interpreters, so we should unmark it
  13224. only when this is the last interpreter in which it's
  13225. interned. We immortalize all the statically initialized
  13226. strings during startup, so we can rely on the
  13227. main interpreter to be the last one. */
  13228. if (!_Py_IsMainInterpreter(interp)) {
  13229. shared = 1;
  13230. }
  13231. break;
  13232. case SSTATE_INTERNED_MORTAL:
  13233. /* fall through */
  13234. case SSTATE_NOT_INTERNED:
  13235. /* fall through */
  13236. default:
  13237. Py_UNREACHABLE();
  13238. }
  13239. if (!shared) {
  13240. _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
  13241. }
  13242. }
  13243. #ifdef INTERNED_STATS
  13244. fprintf(stderr,
  13245. "total length of all interned strings: %zd characters\n",
  13246. total_length);
  13247. #endif
  13248. struct _Py_unicode_state *state = &interp->unicode;
  13249. struct _Py_unicode_ids *ids = &state->ids;
  13250. for (Py_ssize_t i=0; i < ids->size; i++) {
  13251. Py_XINCREF(ids->array[i]);
  13252. }
  13253. #endif /* Py_DEBUG */
  13254. clear_interned_dict(interp);
  13255. }
  13256. /********************* Unicode Iterator **************************/
  13257. typedef struct {
  13258. PyObject_HEAD
  13259. Py_ssize_t it_index;
  13260. PyObject *it_seq; /* Set to NULL when iterator is exhausted */
  13261. } unicodeiterobject;
  13262. static void
  13263. unicodeiter_dealloc(unicodeiterobject *it)
  13264. {
  13265. _PyObject_GC_UNTRACK(it);
  13266. Py_XDECREF(it->it_seq);
  13267. PyObject_GC_Del(it);
  13268. }
  13269. static int
  13270. unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
  13271. {
  13272. Py_VISIT(it->it_seq);
  13273. return 0;
  13274. }
  13275. static PyObject *
  13276. unicodeiter_next(unicodeiterobject *it)
  13277. {
  13278. PyObject *seq;
  13279. assert(it != NULL);
  13280. seq = it->it_seq;
  13281. if (seq == NULL)
  13282. return NULL;
  13283. assert(_PyUnicode_CHECK(seq));
  13284. if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
  13285. int kind = PyUnicode_KIND(seq);
  13286. const void *data = PyUnicode_DATA(seq);
  13287. Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
  13288. it->it_index++;
  13289. return unicode_char(chr);
  13290. }
  13291. it->it_seq = NULL;
  13292. Py_DECREF(seq);
  13293. return NULL;
  13294. }
  13295. static PyObject *
  13296. unicode_ascii_iter_next(unicodeiterobject *it)
  13297. {
  13298. assert(it != NULL);
  13299. PyObject *seq = it->it_seq;
  13300. if (seq == NULL) {
  13301. return NULL;
  13302. }
  13303. assert(_PyUnicode_CHECK(seq));
  13304. assert(PyUnicode_IS_COMPACT_ASCII(seq));
  13305. if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
  13306. const void *data = ((void*)(_PyASCIIObject_CAST(seq) + 1));
  13307. Py_UCS1 chr = (Py_UCS1)PyUnicode_READ(PyUnicode_1BYTE_KIND,
  13308. data, it->it_index);
  13309. it->it_index++;
  13310. PyObject *item = (PyObject*)&_Py_SINGLETON(strings).ascii[chr];
  13311. return Py_NewRef(item);
  13312. }
  13313. it->it_seq = NULL;
  13314. Py_DECREF(seq);
  13315. return NULL;
  13316. }
  13317. static PyObject *
  13318. unicodeiter_len(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
  13319. {
  13320. Py_ssize_t len = 0;
  13321. if (it->it_seq)
  13322. len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
  13323. return PyLong_FromSsize_t(len);
  13324. }
  13325. PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
  13326. static PyObject *
  13327. unicodeiter_reduce(unicodeiterobject *it, PyObject *Py_UNUSED(ignored))
  13328. {
  13329. PyObject *iter = _PyEval_GetBuiltin(&_Py_ID(iter));
  13330. /* _PyEval_GetBuiltin can invoke arbitrary code,
  13331. * call must be before access of iterator pointers.
  13332. * see issue #101765 */
  13333. if (it->it_seq != NULL) {
  13334. return Py_BuildValue("N(O)n", iter, it->it_seq, it->it_index);
  13335. } else {
  13336. PyObject *u = unicode_new_empty();
  13337. if (u == NULL) {
  13338. Py_XDECREF(iter);
  13339. return NULL;
  13340. }
  13341. return Py_BuildValue("N(N)", iter, u);
  13342. }
  13343. }
  13344. PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
  13345. static PyObject *
  13346. unicodeiter_setstate(unicodeiterobject *it, PyObject *state)
  13347. {
  13348. Py_ssize_t index = PyLong_AsSsize_t(state);
  13349. if (index == -1 && PyErr_Occurred())
  13350. return NULL;
  13351. if (it->it_seq != NULL) {
  13352. if (index < 0)
  13353. index = 0;
  13354. else if (index > PyUnicode_GET_LENGTH(it->it_seq))
  13355. index = PyUnicode_GET_LENGTH(it->it_seq); /* iterator truncated */
  13356. it->it_index = index;
  13357. }
  13358. Py_RETURN_NONE;
  13359. }
  13360. PyDoc_STRVAR(setstate_doc, "Set state information for unpickling.");
  13361. static PyMethodDef unicodeiter_methods[] = {
  13362. {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
  13363. length_hint_doc},
  13364. {"__reduce__", (PyCFunction)unicodeiter_reduce, METH_NOARGS,
  13365. reduce_doc},
  13366. {"__setstate__", (PyCFunction)unicodeiter_setstate, METH_O,
  13367. setstate_doc},
  13368. {NULL, NULL} /* sentinel */
  13369. };
  13370. PyTypeObject PyUnicodeIter_Type = {
  13371. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  13372. "str_iterator", /* tp_name */
  13373. sizeof(unicodeiterobject), /* tp_basicsize */
  13374. 0, /* tp_itemsize */
  13375. /* methods */
  13376. (destructor)unicodeiter_dealloc, /* tp_dealloc */
  13377. 0, /* tp_vectorcall_offset */
  13378. 0, /* tp_getattr */
  13379. 0, /* tp_setattr */
  13380. 0, /* tp_as_async */
  13381. 0, /* tp_repr */
  13382. 0, /* tp_as_number */
  13383. 0, /* tp_as_sequence */
  13384. 0, /* tp_as_mapping */
  13385. 0, /* tp_hash */
  13386. 0, /* tp_call */
  13387. 0, /* tp_str */
  13388. PyObject_GenericGetAttr, /* tp_getattro */
  13389. 0, /* tp_setattro */
  13390. 0, /* tp_as_buffer */
  13391. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
  13392. 0, /* tp_doc */
  13393. (traverseproc)unicodeiter_traverse, /* tp_traverse */
  13394. 0, /* tp_clear */
  13395. 0, /* tp_richcompare */
  13396. 0, /* tp_weaklistoffset */
  13397. PyObject_SelfIter, /* tp_iter */
  13398. (iternextfunc)unicodeiter_next, /* tp_iternext */
  13399. unicodeiter_methods, /* tp_methods */
  13400. 0,
  13401. };
  13402. PyTypeObject _PyUnicodeASCIIIter_Type = {
  13403. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  13404. .tp_name = "str_ascii_iterator",
  13405. .tp_basicsize = sizeof(unicodeiterobject),
  13406. .tp_dealloc = (destructor)unicodeiter_dealloc,
  13407. .tp_getattro = PyObject_GenericGetAttr,
  13408. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
  13409. .tp_traverse = (traverseproc)unicodeiter_traverse,
  13410. .tp_iter = PyObject_SelfIter,
  13411. .tp_iternext = (iternextfunc)unicode_ascii_iter_next,
  13412. .tp_methods = unicodeiter_methods,
  13413. };
  13414. static PyObject *
  13415. unicode_iter(PyObject *seq)
  13416. {
  13417. unicodeiterobject *it;
  13418. if (!PyUnicode_Check(seq)) {
  13419. PyErr_BadInternalCall();
  13420. return NULL;
  13421. }
  13422. if (PyUnicode_IS_COMPACT_ASCII(seq)) {
  13423. it = PyObject_GC_New(unicodeiterobject, &_PyUnicodeASCIIIter_Type);
  13424. }
  13425. else {
  13426. it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
  13427. }
  13428. if (it == NULL)
  13429. return NULL;
  13430. it->it_index = 0;
  13431. it->it_seq = Py_NewRef(seq);
  13432. _PyObject_GC_TRACK(it);
  13433. return (PyObject *)it;
  13434. }
  13435. static int
  13436. encode_wstr_utf8(wchar_t *wstr, char **str, const char *name)
  13437. {
  13438. int res;
  13439. res = _Py_EncodeUTF8Ex(wstr, str, NULL, NULL, 1, _Py_ERROR_STRICT);
  13440. if (res == -2) {
  13441. PyErr_Format(PyExc_RuntimeWarning, "cannot decode %s", name);
  13442. return -1;
  13443. }
  13444. if (res < 0) {
  13445. PyErr_NoMemory();
  13446. return -1;
  13447. }
  13448. return 0;
  13449. }
  13450. static int
  13451. config_get_codec_name(wchar_t **config_encoding)
  13452. {
  13453. char *encoding;
  13454. if (encode_wstr_utf8(*config_encoding, &encoding, "stdio_encoding") < 0) {
  13455. return -1;
  13456. }
  13457. PyObject *name_obj = NULL;
  13458. PyObject *codec = _PyCodec_Lookup(encoding);
  13459. PyMem_RawFree(encoding);
  13460. if (!codec)
  13461. goto error;
  13462. name_obj = PyObject_GetAttrString(codec, "name");
  13463. Py_CLEAR(codec);
  13464. if (!name_obj) {
  13465. goto error;
  13466. }
  13467. wchar_t *wname = PyUnicode_AsWideCharString(name_obj, NULL);
  13468. Py_DECREF(name_obj);
  13469. if (wname == NULL) {
  13470. goto error;
  13471. }
  13472. wchar_t *raw_wname = _PyMem_RawWcsdup(wname);
  13473. if (raw_wname == NULL) {
  13474. PyMem_Free(wname);
  13475. PyErr_NoMemory();
  13476. goto error;
  13477. }
  13478. PyMem_RawFree(*config_encoding);
  13479. *config_encoding = raw_wname;
  13480. PyMem_Free(wname);
  13481. return 0;
  13482. error:
  13483. Py_XDECREF(codec);
  13484. Py_XDECREF(name_obj);
  13485. return -1;
  13486. }
  13487. static PyStatus
  13488. init_stdio_encoding(PyInterpreterState *interp)
  13489. {
  13490. /* Update the stdio encoding to the normalized Python codec name. */
  13491. PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
  13492. if (config_get_codec_name(&config->stdio_encoding) < 0) {
  13493. return _PyStatus_ERR("failed to get the Python codec name "
  13494. "of the stdio encoding");
  13495. }
  13496. return _PyStatus_OK();
  13497. }
  13498. static int
  13499. init_fs_codec(PyInterpreterState *interp)
  13500. {
  13501. const PyConfig *config = _PyInterpreterState_GetConfig(interp);
  13502. _Py_error_handler error_handler;
  13503. error_handler = get_error_handler_wide(config->filesystem_errors);
  13504. if (error_handler == _Py_ERROR_UNKNOWN) {
  13505. PyErr_SetString(PyExc_RuntimeError, "unknown filesystem error handler");
  13506. return -1;
  13507. }
  13508. char *encoding, *errors;
  13509. if (encode_wstr_utf8(config->filesystem_encoding,
  13510. &encoding,
  13511. "filesystem_encoding") < 0) {
  13512. return -1;
  13513. }
  13514. if (encode_wstr_utf8(config->filesystem_errors,
  13515. &errors,
  13516. "filesystem_errors") < 0) {
  13517. PyMem_RawFree(encoding);
  13518. return -1;
  13519. }
  13520. struct _Py_unicode_fs_codec *fs_codec = &interp->unicode.fs_codec;
  13521. PyMem_RawFree(fs_codec->encoding);
  13522. fs_codec->encoding = encoding;
  13523. /* encoding has been normalized by init_fs_encoding() */
  13524. fs_codec->utf8 = (strcmp(encoding, "utf-8") == 0);
  13525. PyMem_RawFree(fs_codec->errors);
  13526. fs_codec->errors = errors;
  13527. fs_codec->error_handler = error_handler;
  13528. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  13529. assert(fs_codec->utf8 == 1);
  13530. #endif
  13531. /* At this point, PyUnicode_EncodeFSDefault() and
  13532. PyUnicode_DecodeFSDefault() can now use the Python codec rather than
  13533. the C implementation of the filesystem encoding. */
  13534. /* Set Py_FileSystemDefaultEncoding and Py_FileSystemDefaultEncodeErrors
  13535. global configuration variables. */
  13536. if (_Py_IsMainInterpreter(interp)) {
  13537. if (_Py_SetFileSystemEncoding(fs_codec->encoding,
  13538. fs_codec->errors) < 0) {
  13539. PyErr_NoMemory();
  13540. return -1;
  13541. }
  13542. }
  13543. return 0;
  13544. }
  13545. static PyStatus
  13546. init_fs_encoding(PyThreadState *tstate)
  13547. {
  13548. PyInterpreterState *interp = tstate->interp;
  13549. /* Update the filesystem encoding to the normalized Python codec name.
  13550. For example, replace "ANSI_X3.4-1968" (locale encoding) with "ascii"
  13551. (Python codec name). */
  13552. PyConfig *config = (PyConfig*)_PyInterpreterState_GetConfig(interp);
  13553. if (config_get_codec_name(&config->filesystem_encoding) < 0) {
  13554. _Py_DumpPathConfig(tstate);
  13555. return _PyStatus_ERR("failed to get the Python codec "
  13556. "of the filesystem encoding");
  13557. }
  13558. if (init_fs_codec(interp) < 0) {
  13559. return _PyStatus_ERR("cannot initialize filesystem codec");
  13560. }
  13561. return _PyStatus_OK();
  13562. }
  13563. PyStatus
  13564. _PyUnicode_InitEncodings(PyThreadState *tstate)
  13565. {
  13566. PyStatus status = init_fs_encoding(tstate);
  13567. if (_PyStatus_EXCEPTION(status)) {
  13568. return status;
  13569. }
  13570. return init_stdio_encoding(tstate->interp);
  13571. }
  13572. static void
  13573. _PyUnicode_FiniEncodings(struct _Py_unicode_fs_codec *fs_codec)
  13574. {
  13575. PyMem_RawFree(fs_codec->encoding);
  13576. fs_codec->encoding = NULL;
  13577. fs_codec->utf8 = 0;
  13578. PyMem_RawFree(fs_codec->errors);
  13579. fs_codec->errors = NULL;
  13580. fs_codec->error_handler = _Py_ERROR_UNKNOWN;
  13581. }
  13582. #ifdef MS_WINDOWS
  13583. int
  13584. _PyUnicode_EnableLegacyWindowsFSEncoding(void)
  13585. {
  13586. PyInterpreterState *interp = _PyInterpreterState_GET();
  13587. PyConfig *config = (PyConfig *)_PyInterpreterState_GetConfig(interp);
  13588. /* Set the filesystem encoding to mbcs/replace (PEP 529) */
  13589. wchar_t *encoding = _PyMem_RawWcsdup(L"mbcs");
  13590. wchar_t *errors = _PyMem_RawWcsdup(L"replace");
  13591. if (encoding == NULL || errors == NULL) {
  13592. PyMem_RawFree(encoding);
  13593. PyMem_RawFree(errors);
  13594. PyErr_NoMemory();
  13595. return -1;
  13596. }
  13597. PyMem_RawFree(config->filesystem_encoding);
  13598. config->filesystem_encoding = encoding;
  13599. PyMem_RawFree(config->filesystem_errors);
  13600. config->filesystem_errors = errors;
  13601. return init_fs_codec(interp);
  13602. }
  13603. #endif
  13604. #ifdef Py_DEBUG
  13605. static inline int
  13606. unicode_is_finalizing(void)
  13607. {
  13608. return (get_interned_dict(_PyInterpreterState_Main()) == NULL);
  13609. }
  13610. #endif
  13611. void
  13612. _PyUnicode_FiniTypes(PyInterpreterState *interp)
  13613. {
  13614. _PyStaticType_Dealloc(interp, &EncodingMapType);
  13615. _PyStaticType_Dealloc(interp, &PyFieldNameIter_Type);
  13616. _PyStaticType_Dealloc(interp, &PyFormatterIter_Type);
  13617. }
  13618. void
  13619. _PyUnicode_Fini(PyInterpreterState *interp)
  13620. {
  13621. struct _Py_unicode_state *state = &interp->unicode;
  13622. // _PyUnicode_ClearInterned() must be called before _PyUnicode_Fini()
  13623. assert(get_interned_dict(interp) == NULL);
  13624. _PyUnicode_FiniEncodings(&state->fs_codec);
  13625. // bpo-47182: force a unicodedata CAPI capsule re-import on
  13626. // subsequent initialization of interpreter.
  13627. interp->unicode.ucnhash_capi = NULL;
  13628. unicode_clear_identifiers(state);
  13629. }
  13630. /* A _string module, to export formatter_parser and formatter_field_name_split
  13631. to the string.Formatter class implemented in Python. */
  13632. static PyMethodDef _string_methods[] = {
  13633. {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
  13634. METH_O, PyDoc_STR("split the argument as a field name")},
  13635. {"formatter_parser", (PyCFunction) formatter_parser,
  13636. METH_O, PyDoc_STR("parse the argument as a format string")},
  13637. {NULL, NULL}
  13638. };
  13639. static PyModuleDef_Slot module_slots[] = {
  13640. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  13641. {0, NULL}
  13642. };
  13643. static struct PyModuleDef _string_module = {
  13644. PyModuleDef_HEAD_INIT,
  13645. .m_name = "_string",
  13646. .m_doc = PyDoc_STR("string helper module"),
  13647. .m_size = 0,
  13648. .m_methods = _string_methods,
  13649. .m_slots = module_slots,
  13650. };
  13651. PyMODINIT_FUNC
  13652. PyInit__string(void)
  13653. {
  13654. return PyModuleDef_Init(&_string_module);
  13655. }
  13656. #ifdef __cplusplus
  13657. }
  13658. #endif